繁体   English   中英

对于包的`__init__`,`__ all__`中没有Unicode?

[英]No Unicode in `__all__` for a package's `__init__`?

Python 2.7.5中的__all__不允许使用Unicode文字吗? 我有一个__init__.py文件,顶部有from __future__ import unicode_literals ,编码为u​​tf-8。 (其中还有一些unicode字符串,因此将来会导入。)

为了确保在使用from mypackage import *时只有部分模块可见,我已将我的类添加到__all__ 但是我得到TypeError: Item in ``from list'' not a string 这是为什么? 错误?

但是,当我在__all__中将类名转换为str时,它的工作正常。
[当我from mypackage import SomeClass指定from mypackage import SomeClass时,它也适用于下面的run.py ...因为__all__中的项目未被处理。 ]


mypackage中/ somemodule.py:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

class SomeClass(object):
    pass

mypackage / __init__ .py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .somemodule import SomeClass

__all__ = ['SomeClass']

run.py:

# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from mypackage import *

print('yay')

为了避免错误,我将'all'声明更改为:

__all__ = [str('SomeClass')] #pylint: disable=invalid-all-object

当然,这是pylint抱怨的。

我的另一个选择是导入unicode_literals并使用u'uni string' init中的所有字符串显式地转换为unicode。

不, __all__不允许使用unicode值,因为在Python 2中,名称是字符串,而不是unicode值。

你确实必须编码__all__所有字符串或不使用unicode文字。 您可以单独执行此操作:

__all__ = ['SomeClass']
__all__ = [n.encode('ascii') for n in __all__]

在Python 3中,变量名也是unicode值,因此__all__ 应该具有unicode字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM