__all__ is a special variable used in modules in python.
When a module defines an __all__ variable, it is expected to be a list of strings where each string is the name of an object that will be imported to another file when you use the statement from module import *.
It offers several benefits, particularly in terms of managing the namespace and improving the readability and maintainability of code.
Syntax
__all__ = ['Var1', 'Var2', 'VarN']
Example 1: Basic Usage
The following file app1.py explicitly exports the variables number_of_people and daily_routine.
#app1.py
__all__ = ['number_of_people', 'daily_routine']
number_of_people = 5
def daily_routine():
return 'This is the daily routine.'
These members can then be imported in another file, like app2.py, as shown below:
#app2.py
from app1 import *
# This works, as number_of_people and daily_routine function are included in __all__
print(number_of_people)
print(daily_routine())
To see the output, you need to run app2.py in the command line
Output
Example 2: Importing Variables Not Defined in __all__
Now, using the same file mentioned above, we will add private_function() and attempt to import it in the app2.py file.
This will raise a AttributeError because it is not included in __all__.
#app1.py
__all__ = ['number_of_people', 'daily_routine']
number_of_people = 5
def daily_routine():
return 'This is the daily routine.'
def private_function():
return 'This is a private function.'
app2.py:
#app2.py
from app1 import *
# This works, as number_of_people and daily_routine function are included in __all__
print(number_of_people)
print(daily_routine())
# This will raise an AttributeError, as private_function
# is not included in __all__ and hence not imported with `import *`
print(private_function())
Bashir Alam
Hi:)
Great content. Really find it usefull