avatarLiu Zuo Lin

Summary

The article explains the use of __all__ in Python to control the importing of variables and functions when using from a import *.

Abstract

The article titled "all in Python Explained in 15 Seconds" provides an explanation of how to use the __all__ variable in Python to control the importing of variables and functions from one module to another. The article uses two examples to illustrate the difference between using from a import * without __all__ and with __all__. In the first case, all variables from module a are imported into module b, while in the second case, only the variables specified in __all__ are imported into module b. The article also provides an explanation of why and when to use __all__.

Opinions

  • The author believes that __all__ should be used when a module contains a lot of random stuff, but only a few variables need to be exported.
  • The author suggests that __all__ should be used to avoid accidentally importing a whole bunch of clutter when using from a import *.
  • The author provides a clear and easy-to-understand explanation of __all__ in Python.

__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

  1. Clap 50 times for this story
  2. Leave a comment telling me your thoughts
  3. 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/

Python
Python3
Python Programming
Programming
Coding
Recommended from ReadMedium