Managing Wildcard Imports
00:00
The next step in managing your user interface is to manage what happens during a wildcard import. A wildcard import is what you see on screen right now, when someone uses the * to import every publicly available object into the namespace.
00:17
So from surpluscalculator import *, and that can get a little bit messy. For example, if you do that right now and then you type dir() with nothing in the parentheses, you’ll get the namespace, which will have your dunder methods.
00:33
It’ll have the functions you were hoping for, such as calculate_fixed_outgo() and calculate_random_income(). But it also has the income module and the outgo module and then simulations here.
00:45
And you might not want that to show up because the user doesn’t actually need that. So you can manage that in the __init__.py file by adding a variable or a list, and that is called __all__.
01:01
So __all__ is a list of strings, and each string represents objects that you’d like to show up in the public interface. So in your case here, it’ll be these functions here.
01:12
So calculate_random_income(), calculate_fixed_income(), calculate_random_outgo(), calculate_fixed_outgo(), and simulate_surplus().
01:20 And this is what that looks like. I’ve just copy-pasted it to save you some time because that’s quite a bit of typing. But the key point here being it’s the names of the functions, and they are in here as strings.
01:33 If I save that and then move back to the REPL,
01:37
if you now do the wildcard import again and do dir() with again parentheses and nothing in between them, you now have a cleaner user interface because all that’s showing up now is, of course, the dunder methods, but then there are the functions that you wanted to show up there.
01:55
But the modules that you didn’t include in the __all__ variable, in that list, are not showing up. So there’s no income, no outgo, and no simulations.
02:07 So that is how you manage wildcard imports. In the next lesson, you’ll just summarize what you’ve learned during this course.
Become a Member to join the conversation.
