Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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?

1 Answer

0 votes
by (106k points)

The variable __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, __all__  is a list of strings defining what symbols in a module will be exported when from <module> 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 __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.

Interested to learn more about Python? Come & join our Python online course

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...