About this question
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?
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?
Log in to share your answer and help other learners.
Log in to answerBest Answer · By JanBask Python Expert
Answered on Apr 2, 2021
The variable python __all__ is a list of public objects of that module, as interpreted by import *. This variable overrides the default of hiding everything that begins with an underscore.
In other words, python __all__ is a list of strings defining what symbols in a module will be exported when from import * is used on the module.
For example, the below-mentioned code saved as foo.py explicitly exports the symbols bar and baz:
__all__ = ['bar', 'baz']
waz = 5
bar = 10
def baz():
return 'baz'
So, the two symbols bar and baz can be imported like follows:
from foo import *
print(bar)
print(baz)
# The following will produce an exception, as "waz" is not exported by the module
print(waz)
So, if the above part of the code which contains python __all__ is commented out, then this code will be executed to completion, as the default behavior of import * is to import all symbols that do not begin with an underscore, from the given namespace.
Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.
Most-read guides across JanBask
Common Python interview questions, answered
Guides, tips and career advice on Python from JanBask experts.
Python How to Become a Python Developer: A Step-by-Step Guide for Beginners
Discover how to become a Python Developer via a practical 7-step guide build projects, maintain clean code, practice daily, and…
Python PCEP Certification Guide: Entry-Level Python Programmer Certification
Explore this PCEP certification guide for insights on cost, exam format, passing score, application, training, and study tips.…
Python Top 50+ Python Projects ideas for Beginners to Advanced
Discover innovative Python project ideas, explore advanced Python projects, and find good Python projects for beginners and…
Python How To Comment Out Multiple Lines In Python Like A Pro
Commenting out code is a common practice among programmers. It allows you to temporarily disable parts of your code without…