Join us and get access to thousands of tutorials and a community of expert Pythonistas.
This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.
Applying __all__ Effectively
00:00
You’ve already seen some of the key benefits of __all__, like controlling what’s exposed to wildcard imports, defining a clear public API, improving the readability of your API, and reducing namespace clutter.
00:14
But there are also a few things to watch out for, like the fact that __all__ does not discover modules automatically. Its contents must be provided manually.
00:23
Names included in __all__ must exist in the package namespace, because undefined names in __all__ will raise errors on import. And the all-important caveat that explicit imports are unaffected by __all__.
00:37 By design. Anything in a module can be imported by name, and that’s just how Python is set up. Nothing is truly private. Lastly, some best practices to consider.
00:48
When designing modules and packages, use __all__ to make your API explicit. Keep it lean and focused, rather than exporting everything. Don’t forget to continue to update it as your API evolves, and include only the names intended for external use, including metadata or other names you want to expose explicitly. And speaking of metadata, let’s look at an example of that.
01:11
Another use for __all__ that you might not have thought of is to explicitly provide objects that would normally be skipped by a wildcard import.
01:19
Most commonly, this technique is used for metadata that uses Python’s dunder convention. Back in the IDE, looking at that pokereader module again, suppose you want to add metadata in the form of version and author.
01:32
You might do it like this. Assign __version__ the string "1.0.0",
01:40
and __author__ the string "Real Python".
01:43
Even without __all__, neither of these variables would be exported by default with a wildcard import. Because they start with an underscore, Python would consider them non-public.
01:53
So to assure those items will be available, add them to the __all__ list.
02:02 And save. Open the REPL one more time.
02:08
from pokereader import *,
02:11
Run dir(). And there they are, __author__ and __version__. And you can examine them directly. __author__ contains the string "Real Python",
02:23
and __version__ the string "1.0.0". Always remember, what your API exposes should be whatever the users might need. Sometimes that even includes dunder properties.
02:35 Alright, it’s time to land this plane. Join me in the next and final lesson to wrap up and think about where to go from here.
Become a Member to join the conversation.