What is Python __all__? Explained with examples

Do you wanna know what the Python __all__ variable means and how Python __all__ works? Well, here we go.

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. It is known for its large number of built-in modules. A Python module is a file containing Python definitions and statements. A module can define functions, classes, and variables. A module can also include runnable code. Grouping related code into a module makes the code easier to understand and use. It also makes the code logically organized. We can either import just one function from a module or can import all functionalities from the module. But sometimes, even after importing everything from the module, some variables and methods cannot be imported. To import such variables and methods, we use python __all__ variable. In this article, we will discuss how we can use the Python __all__ variable to import everything from the module.



How to create a module in Python?

A module is a collection of code or functions that uses the . py extension. A Python library is a set of related modules or packages bundled together. It is used by programmers as well as developers. It is mostly used by community members, developers, and researchers. There are various modules in python for specific purposes, for example, plotly for interactive visualization, matplotlib for visualization, pandas for data frames, etc. But in this section, we will learn how we can create our own python module and import it.

Open a blank python file and add the following code. You can add your own class or program as well.

# Import a library
import random
# Define constants
MODEL = (2014, 2016, 2018, 2020, 2022)
CARS = ("BMW", "Toyota")
# Define a custom class
class Car:
    #init method
    def __init__(self, model: str, name: str):
        self.model = model
        self.name = name
        
    def __str__(self):
        return f"Name: {self.name},  Model:  {self.model}"
    
    
# Define a custom function
def get_random_name():
    
    # returning random names and colors
    return Car(random.choice(MODEL), random.choice(CARS))
# Create a random object
random_car = get_random_name()

The above Python program returns a random name and model for a car. Now, save the file with any name. In my case, the name of the file is module.py.

Different ways to import Python modules

There are various ways to import a python module. We can either import all functionalities of the module or can get access to only one method. Here, we will discuss both ways and will import the module that we have just created.

Now open the new python and import the module.

# importing the module
from module import get_random_name
# accessting the method from module
car = get_random_name()
# printing
print(car)

Output:

python-__all__-variable-import

As you can see, we have imported just one function from the module and we were able to access the function.

Another method is to import everything from the module using an asterisk (*) as shown below:

# importing the module
from module import *
# accessting the method from module
car = get_random_name()
# printing
print(car)

Output:

python-__all__-variable-importing-module

As you can see, we were able to access the function. Let us also try to access the variables from the module.

# importing the module
from module import *
# Create new object 
car = Car(MODEL[0], CARS[1])
# printing
print(car)

Output:

python-__all__-variable-variables

Sometimes even importing all functionalities from the module cannot import everything. Let us discuss how we can import such functionalities.

Why use Python __all__ variable?

sometimes importing module does not import all the variable, especially those which starts with an underscore (_). In such cases Python __all__ helps to import those variables. Those variables are known as protected variables. Protected variables are those data members of a class that can be accessed within the class and the classes derived from that class. In Python, there is no existence of “Public” instance variables. However, we use the underscore ‘_’ symbol to determine the access control of a data member in a class.

Now let us change the variables in our module to protected ones and try to import the module again.

# Import a library
import random
# Define constants
__MODEL__ = (2014, 2016, 2018, 2020, 2022)
__CARS__ = ("BMW", "Toyota")
# Define a custom class
class Car:
    #init method
    def __init__(self, model: str, name: str):
        self.model = model
        self.name = name
        
    def __str__(self):
        return f"Name: {self.name},  Model:  {self.model}"
    
    
# Define a custom function
def get_random_name():
    
    # returning random names and colors
    return Car(random.choice(__MODEL__), random.choice(__CARS__))
# Create a random object
random_car = get_random_name()

As you can see, now we have protected variables in our module. Let us now import the module again and try to get access to these variables.

# importing the module
from module import *
# Create new object 
car = Car(__MODEL__[0], __CARS__[1])
# printing
print(car)

Output:

python-__all__-variables-error

As you can see, we get an error because now the variables are protected and can only be accessed inside the module. So, in order to access the protected variables, we use python __all__ variable.

Python __all__ to access protected variables

In order to access the protected class using python __all__, we have to create a list inside the module that contains the variables including protected ones as shown below:

# Import a library
import random
# creating python __all__ variable
__all__ = ['__MODEL__', '__CARS__', 'Car', 'random_car', 'random','get_random_name']
# Define constants
__MODEL__ = (2014, 2016, 2018, 2020, 2022)
__CARS__ = ("BMW", "Toyota")
# Define a custom class
class Car:
    #init method
    def __init__(self, model: str, name: str):
        self.model = model
        self.name = name
        
    def __str__(self):
        return f"Name: {self.name},  Model:  {self.model}"
    
    
# Define a custom function
def get_random_name():
    
    # returning random names and colors
    return Car(random.choice(__MODEL__), random.choice(__CARS__))
# Create a random object
random_car = get_random_name()

Now, let us import the module again and try to get access to the variables again.

# importing the module
from module import *
# Create new object 
car = Car(__MODEL__[0], __CARS__[1])
# printing
print(car)

Output:

python-__all__-variable-variables

As you can see, we were able to get access to the protected variables using python __all__.

Summary

Protected variables are those data members of a class that can be accessed within the class and the classes derived from that class. In Python, there is no existence of “Public” instance variables. However, we use the underscore ‘_’ symbol to determine the access control of a data member in a class. We can get access to Python-protected variables and methods using python __all__. In this short article, we learned how we can get access to protected variables from modules using python.

Related Articles

Leave a Comment

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

Scroll to Top