__all__ in Python Explained in 15 Seconds
# provided you read pretty fast
Case 1 : No __all__
# a.py
a = 'apple'
b = 'boy'
c = 'cat'
d = 'donkey'
e = 'elephant'
f = 'fish'
# b.py
from a import *
print(dir())
# [..., 'a', 'b', 'c', 'd', 'e', 'f']
^ here, from a import *
imports everything from a.py
into b.py
. Which is why a, b, c, d, e & f show up in b.py
's dir()
Case 2: __all__ is defined
# a.py
a = 'apple'
b = 'boy'
c = 'cat'
d = 'donkey'
e = 'elephant'
f = 'fish'
__all__ = ['a', 'b']
# b.py
from a import *
print(dir())
# [..., 'a', 'b']
^ here, from a import *
imports only a
and b
. And this is because of __all__
in a.py telling b.py that it can only import a
and b
Note — this works only from from a import *
— you can still from a import c, d, e, f
and it will work
Why/when to use
If a.py contains a whole bunch of random stuff, but we only need to ‘export’ a
and b
, we should probably use __all__
so that we don’t accidentally import a whole bunch of clutter when using from a import *
Conclusion
Hope this was clear and easy to understand.
If You Wish To Support Me As A Creator
- Clap 50 times for this story
- Leave a comment telling me your thoughts
- Highlight your favourite part of the story
Thank you! These tiny actions go a long way, and I really appreciate it!
YouTube: https://www.youtube.com/@zlliu246
LinkedIn: https://www.linkedin.com/in/zlliu/