You can treat __all__ is a special variable that can be used to control what names are imported In case of from package import *. By default, the * operator will import all names from the module that is a public variable. However, if the module defines a __all__ variable, then only the names listed in __all__ will be imported.

For example, Module called my_module with two names: foo and bar. The __all__ variable is set to a list containing the name foo.

def foo():
    print("foo")

def bar():
    print("bar")

__all__ = ["foo"]

If we import my_module using the * operator, only the name foo will be imported. We can verify this by printing the names of all the names that were imported:

import my_module as m

print(m.__all__)

This will print the following output:

['foo']

As you can see, only the name foo was imported. The name bar was not imported because it was not listed in the __all__ variable.

The __all__ variable is a way to specify which names from a module should be imported when using the from module import * syntax. This can be helpful for preventing other modules from accidentally importing names that they should not have access to.

Few notes about __all__:

  • If the asterisk (*) is not defined in the import statement, then all names from the module that do not start with an underscore will be imported into the current namespace..
  • The __all__ variable is only used when the * operator is used to import names from a module. If names are imported from a module using the from module import name syntax, then the __all__ variable will not be used.

Support On Demand!

Python