|
|
Python Language...
Power of the Snake .. .. |
|
|
|
| Python > What is `__all__` in Python | |
Python's got this neat little trick up its sleeve called __all__ . Basically, it's like having a VIP list at a party. You slap it on a module, and it tells Python, "Hey, only these folks are allowed to strut their stuff when someone does a fancy import * from this module." So, if you've got a messy module with more junk than a Deadpool costume closet, but you only want to show off your A-listers, like 'a' and 'b', you toss them into __all__ and bam! Python knows the deal. No more accidental imports cluttering up your code like a bad guy convention. It's like having a bouncer at the door of your Python party, but way less intimidating and with fewer broken bones.
Case 1: No __all__
In the example, the 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
In the example, the 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 *
|
|