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.
Exploring __all__ in Practice
00:00
__all__ is more than a tool to facilitate wildcard imports from packages, or to limit unwanted objects from being exported. Instead, think of it as a way to define the public API of a module or package.
00:12 In practical terms, you can use it to deliver a simple, consistent set of exported names, to prevent the exposure of internal details like constants or imports, or to allow packages to re-export selected names from multiple modules.
00:25
All of these serve to make the module or package API explicit and predictable. Let’s explore this concept with an example of using __all__ in a module.
00:35
Back in the IDE, pokereader.py is a fun little module that pulls data from pokeapi.co. It has one class, two functions, and a constant.
00:45
Importantly, the _fetch_pokemon() function is a helper used by get_pokemon_data() as well as internally in the Pokemon class. It’s already marked with a leading underscore, so given what you know about wildcards, do you think you need to use __all__ here? Pop open the REPL to find out what happens when you import from this file.
01:04
Note that because this module uses requests, which is a third-party library, you will need to have it installed in your environment in order to run this code.
01:12
Okay, from pokereader import *,
01:17
and added to the global namespace you can see BASE_URL, Pokemon, get_pokemon_data(), and requests.
01:25
Maybe not what you expected? While _fetch_pokemon() was in fact skipped, you also ended up importing BASE_URL and the requests library. Remember, a wildcard import will find all of the public names, including requests and BASE_URL.
01:40
So to keep the API clean, you should define __all__ as a list holding the strings get_pokemon_data and Pokemon.
01:51 Save the file, restart the REPL, and try again.
01:58
from pokereader import *, call dir(), perfect. The only things added were Pokemon and get_pokemon_data(), which realistically are the only objects you would want a user to import.
Become a Member to join the conversation.