Skip to main content
How To Use Python __all__

How To Use Python __all__ With Example

in this tutorial, We’ll learn What is Python _all_ and How to Use it. Python all is a variable that can be set in the init.py file of a package.

This is directly related to how you want to manage the imports of your packages or modules, such as from import *.

By default, Python will export all names that do not start with an _.

What is Python __all__

The all variable is a list of strings that defines those symbols that are imported when a program does import the module. The all overrides the default of hiding everything that begins with an underscore.

How To Use __all__

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

Let’s explore all in detail with some code examples.

Let’s create a all.py file and added the below code here:

def hello():
    print ( "hello")

def fname():
    print ( "adam")

def lname():
    print ( "joe")

age = 32
salary = 3424

__all__ = [
    "hello","age"
]

Let’s try to import the module. We have only added hello and age to all.

These variables and methods can then be imported in a app.py file.

from all import *

print(age)

print(fname())

Output:

32
adam

However, You will receive an error if we attempt to access any other variables that are not part of the all list.

from all import *

print(salary)

Output:

NameError:name 'salary' is not defined

You can access other variables which are not part of all, by using a directly defined name in import.

from all import salary

print(salary)

Output:

3424

we have given ‘salary’ name as in the import statement.

How To use __all__ in __init_.py

Python must use the init.py files to recognise the folders as holding packages. A package is typically made up of modules that may import one another but are necessarily tied together with an __init.__.py file.

Let’s create two files:

test1.py file:

def hello():
    print ( "hello")

def lname():
    print ( "joe")

age = 32

Let’s create another module test2.py file

def fname():
    print ( "adam")

def dept():
    print ( "devops")

salary = 3424

Create a hello package, imported test1 and test2 file into the __init__.py.

from .test1 import *
from .test2 import *

__all__ = [
    "hello","age","fname"
]

Access those methods which are defined in __all__.

from hello import *

print(hello())

Output:

hello

Let’s try to access those methods which are not defined in all.

from hello import *
print(salary)

Output:

NameError:name 'salary' is not defined

Conclusion:

Python all affects the from import * behavior. Those variables that are not mentioned in all are still accessible from outside the module by using from import.

Reference :

Importing Package

Leave a Reply

Your email address will not be published. Required fields are marked *