Why should I use __all__ in the __init__ of a python package?

I already read Can someone explain __all__ in Python? and I understand that it only affects expressions from ... import *

, but I can't figure out the real use case. Why should I repeat exported names in __all__

(DRY!) When I could just avoid importing those names in the namespace __init__

?

Example:

mypackage/__init__.py

from a import A

      

mypackage/a.py

A = "A"
A1 = "A1"

      

mypackage/b.py

B = "B"    

      

And then in python:

>>> from mypackage import *
>>> A
'A'
>>> 
>>> A1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'A1' is not defined
>>> b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined

      

As you can see, it A

is in the namespace, but A1

also b

not. Why do I need to define __all__ = ["A"]

?

+3


source to share


1 answer


The only time you want to define __all__

in your package __init__.py

is a list of "exported" member names that you want to export when the user does:

from package import *

      

This is described in 6.4.1. Import * from package

Note. If you don't define __all__

in your package, then the default behavior is as follows (from the documentation):



If __all__

not specified, the statement from sound.effects import * does not import all submodules from the sound.effects package into the current namespace; it only ensures that the sound.effects package has (perhaps any init code is executed in __init__.py

) and then imports all the names defined in the package. This includes any specific names (and submodules explicitly loaded) on __init__.py

. It also includes any packaging submodules that were explicitly loaded by previous imports. Consider this code:

A "naive" interpretation of this might be:

If you don't define __all__

; a from package import *

will bring in everything from this package and nothing imported into that pacakge __init__.py

.

+6


source







All Articles