ane*_*oid 7 python unicode python-import python-2.7
__all__Python 2.7.5中不允许使用Unicode文字吗?我在顶部有一个__init__.py文件from __future__ import unicode_literals,还有编码utf-8.(其中还有一些unicode字符串,因此将来会导入.)
为了确保在导入时只有部分模块可见from mypackage import *,我已将我的课程添加到__all__.但我明白了TypeError: Item in ``from list'' not a string.这是为什么?错误?
但是,当我将类名转换为str in时__all__,它的工作正常.
[当我from mypackage import SomeClass在下面的run.py中指定时它也有效...因为未处理的项目__all__.]
mypackage中/ somemodule.py:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class SomeClass(object):
pass
Run Code Online (Sandbox Code Playgroud)
mypackage/__init__.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .somemodule import SomeClass
__all__ = ['SomeClass']
Run Code Online (Sandbox Code Playgroud)
run.py:
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from mypackage import *
print('yay')
Run Code Online (Sandbox Code Playgroud)
为了避免错误,我将'all'声明更改为:
__all__ = [str('SomeClass')] #pylint: disable=invalid-all-object
Run Code Online (Sandbox Code Playgroud)
当然,这是pylint抱怨的.
我的另一个选择是不导入unicode_literals并显式地将init中的所有字符串转换为unicode u'uni string'.
Mar*_*ers 11
不,不允许使用unicode值__all__,因为在Python 2中,名称是字符串,而不是unicode值.
你确实必须__all__使用unicode文字对所有字符串进行编码.您可以单独执行此操作:
__all__ = ['SomeClass']
__all__ = [n.encode('ascii') for n in __all__]
Run Code Online (Sandbox Code Playgroud)
在Python 3,变量名是Unicode值太大,所以__all__被预期有unicode字符串.
| 归档时间: |
|
| 查看次数: |
1266 次 |
| 最近记录: |