AppDividend
Latest Code Tutorials

What is Python __all__ and How to Use it

0

Python __all__ is a variable that can be set in the __init__.py file of a package. The __all__ variable is a list of strings that defines those symbols that are imported when a program does. Let’s see __all__ in detail.

What is Python __all__

Python __all__ is a list of public objects of that module, as interpreted by import *. The __all__  overrides the default of hiding everything that begins with an underscore. 

Objects that start with an underscore or are not mentioned in __all__ if __all__ is present are not exactly hidden; they can be seen and accessed perfectly normally if you know their names. It is only in the case of an “import *“, which is not recommended anyway, that the contrast carries any weight.

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.

What does __all__ do?

The __all__ tells the semantically “public” names from the module. If there is a name in __all__, the users are expected to use it, and they can expect that it will not change.

By default, Python will export all names that do not start with an _. You certainly could rely on this mechanism.

Using the _ convention can be more elegant because it removes the redundancy of naming the names again.

Python __all__ example

The following file data.py explicitly exports the variables men and lifestyle.

__all__ = ['men', 'lifestyle']

men = 5

def lifestyle(): return 'lifestyle'

These variables can then be imported in an app.py file like the following.

from data import *

print(men)

print(lifestyle())

Output

5
lifestyle

So, if you comment the __all__ = [‘men’, ‘lifestyle’], then the code will be executed to completion, as the default behavior of import * is to import all variables that do not begin with the underscore, from the given namespace.

The __all__ in __init__.py

The __init__.py files are required to make Python treat the directories as containing packages. In the simplest case, __init__.py can be an empty file, but it can also execute initialization code for the package or set the __all__ variable.

A package is typically made up of modules that may import one another but are necessarily tied together with an __init__.py file.

That is it for Python __all__.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.