1

Python package init file can have variable __all__ that lists the sub packages to be imported when using: from package import *

Is this same as writing import sub package name(s) in the init file (instead of __all__) ?

I have read article thay says if the init.py file in the package directory contains a list named all, it is taken to be a list of modules that should be imported when the statement from import * is encountered.

variable
  • 8,262
  • 9
  • 95
  • 215
  • 3
    `__all__` is intended to list the "exported names" from a module. it will not trigger imports of sub-packages – anthony sottile Oct 06 '19 at 19:22
  • @Anthony - an online articles says - if the __init__.py file in the package directory contains a list named __all__, it is taken to be a list of modules that should be imported when the statement from import * is encountered. – variable Oct 12 '19 at 05:20

1 Answers1

2

__all__ is more useful for individual sourcefiles than it is for an __init__.py file. In such __init__.py files, you're usually already importing only the variables and functions that you intend to make available from the outside of the package. For example:

package foo
+-- __init__.py
+-- bar.py
+-- baz.py

__init__.py

from .bar import *
from .baz import *

bar.py

def some_method(): 
    ...

def other_method():
    ...

def hidden_method():
    ...

class some_class:
    ...

__all__ = ['some_method', 'other_method', 'some_class']

And then outside of the package,

import foo

foo.some_method()  # works
foo.other_method()  # works
foo.hidden_method()  # error
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • This is a really intuitive answer :) –  Oct 08 '19 at 01:05
  • Also can you tell me What purpose does __all__ serve in the init file of a package? Same as that in module? – variable Oct 12 '19 at 04:32
  • @variable `__init__.py` is really just like any other python sourcefile, except that it's *implicitly* imported when you would try to import the entire folder. Technically you could write all your code just in a `__init__.py` file, in which case you might want to put an `__all__` variable in it to restrict what someone else would import from it. The same way you would for any other sourcefile. The difference here is that `__init__.py` isn't typically used this way, so `__all__` usually isn't useful in it. – Green Cloak Guy Oct 12 '19 at 04:39
  • Ok so __all__ should never have module name within it as it is invalid to do so. – variable Oct 12 '19 at 04:45
  • Foll is an article online which differs from your answer. If the __init__.py file in the package directory contains a list named __all__, it is taken to be a list of modules that should be imported when the statement from import * is encountered. – variable Oct 12 '19 at 05:18