我可以确保导入我的Python代码的用户使用Unicode文字吗? [英] Can I ensure that users that import my Python code use Unicode literals?

查看:161
本文介绍了我可以确保导入我的Python代码的用户使用Unicode文字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码包括

from __future__ import unicode_literals

并具有许多接受(并期望)Unicode字符串作为输入以便完全发挥作用的功能.

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

有没有一种方法可以确保用户(在脚本,Python或IPython等中)也使用Unicode文字,例如,

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")

不会引起错误("ascii"编解码器无法解码字节0xce ..."),因此

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

my_func(u"AβC")

不是必需的吗?

推荐答案

否,unicode_literals是每个模块的配置,必须在要使用它的每个模块中导入.

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

最好的方法就是在my_func的文档字符串中提及您希望使用unicode对象的地方.

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.

在python3.5或更高版本上,您可以使用类型提示来强制执行.

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

这篇关于我可以确保导入我的Python代码的用户使用Unicode文字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆