What is the role of __all__ in Python?

Asked 2 years ago, Updated 2 years ago, 113 views

I'm studying Python. In the _init__.py file, __all__ <- I keep looking at it What do you use this for?

python syntax namespace

2022-09-22 22:32

1 Answers

__all___ is a list with a string as an element. This string means the symbol to be exported from from <module> import *.

For example, the following code foo.py exports symbol bar and baz.

#foo.py
__all__ = ['bar', 'baz'] # specify to export bar, baz from import *

waz = 5
bar = 10
def baz(): return 'baz'

Now, when temp.py imports foo module

#temp.py
from fromoo import * #bar, baz imported

print bar #success
print baz #Success
exception occurred because printwaz # "waz" was not specified in __all____ on foo.py

However, if import * without specifying _all__, all symbols (excluding symbols that start with _) are imported If you clear the __all__ part of foo.py, print waz will run without any problems.

For this reason, set __init__ in the __init__ file.


2022-09-22 22:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.