Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain __all__ in Python?

I have been using Python more and more, and I keep seeing the variable __all__ set in different __init__.py files. Can someone explain what this does?

like image 951
varikin Avatar asked Sep 04 '08 21:09

varikin


People also ask

What does __ all __ mean in Python?

The __all__ in Python is a list of strings defining what symbols in a module will be exported when from <module> import * is used on the module.

Why is __ main __ used in Python?

In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.

What is the value of __ name __ In a Python interpreter?

The __name__ Attribute and the __main__ Scope The Python interpreter automatically adds this value when we are running a Python script or importing our code as a module. The __name__ in Python is a special variable that defines the name of the class or the current module or the script from which it gets invoked.

What is __ name __ Main in Python?

Python files are called modules and they are identified by the . py file extension. A module can define functions, classes, and variables. So when the interpreter runs a module, the __name__ variable will be set as __main__ if the module that is being run is the main program.


1 Answers

Linked to, but not explicitly mentioned here, is exactly when __all__ is used. It is a list of strings defining what symbols in a module will be exported when from <module> import * is used on the module.

For example, the following code in a foo.py explicitly exports the symbols bar and baz:

__all__ = ['bar', 'baz']  waz = 5 bar = 10 def baz(): return 'baz' 

These symbols can then be imported like so:

from foo import *  print(bar) print(baz)  # The following will trigger an exception, as "waz" is not exported by the module print(waz) 

If the __all__ above is commented out, this code will then execute to completion, as the default behaviour of import * is to import all symbols that do not begin with an underscore, from the given namespace.

Reference: https://docs.python.org/tutorial/modules.html#importing-from-a-package

NOTE: __all__ affects the from <module> import * behavior only. Members that are not mentioned in __all__ are still accessible from outside the module and can be imported with from <module> import <member>.

like image 76
Alec Thomas Avatar answered Oct 16 '22 16:10

Alec Thomas