No Unicode in `__all__` for` __init__` package?

Are Unicode literals allowed in __all__ in Python 2.7.5? I have a __init__.py file with from __future__ import unicode_literals at the top, as well as utf-8 code. (It also has some Unicode strings, hence future imports.)

To make sure that only some of the modules are visible when importing from from mypackage import * , I added my class to __all__ . But I get TypeError: Item in ``from list'' not a string . Why is this? Mistake?

However, when I passed the class name str to __all__ , it works fine.
[It also works when I specify from mypackage import SomeClass in run.py below ... since the elements in __all__ not processed. ]


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

To avoid the error, I change the declaration of 'all' to:

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

which, of course, complains about pylint.

Another option is not to import unicode_literals and explicitly insert all strings in init into unicode with u'uni string' .

+7
python unicode python-import
source share
1 answer

No, unicode values ​​are not allowed in __all__ , because there are strings in Python 2 names, not Unicode values.

You really need to encode all lines in __all__ or not use literals in unicode format. You can do this as a separate step:

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

In Python 3, variable names are also unicode values, so __all__ expected to have unicode strings.

+11
source share

All Articles