Can I ensure that users that import my Python code use Unicode literals?

笑着哭i 提交于 2020-01-16 18:19:42

问题


My code includes

from __future__ import unicode_literals

and has many functions that accept (and expect) Unicode strings as input in order to function fully.

Is there a way to ensure that users (in scripts, Python, or IPython, etc.) also use Unicode literals so that, for example

my_func("AβC")

does not cause an error ("ascii' codec can't decode byte 0xce ...") and so that

my_func(u"AβC")

is not necessary?


回答1:


No, unicode_literals is a per-module configuration and must be imported in each and every module where it is to be used.

The best way is just to mention it in the docstring of my_func that you are expecting unicode objects.

If you insist, you could enforce it to fail early:

def my_func(my_arg):
    if not isinstance(my_arg, unicode):
        raise Exception('This function only handles unicode inputs')

If you need it in many places, it might be nicer to implement it with a decorator.

On python3.5 or up, you could use type hints to enforce this.



来源:https://stackoverflow.com/questions/33743602/can-i-ensure-that-users-that-import-my-python-code-use-unicode-literals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!