Importing With a Wildcard
00:00
In this lesson, you will learn about wildcard imports. Now, what is a wildcard import? It’s an import of the following structure. So from a module name, import *
, instead of defining exactly which pieces of that module you would like to import, you import everything.
00:19 Now, when I say everything, that is not entirely true because objects whose names have a leading underscore are not imported. By now, that should make sense to you because objects with a leading underscore are non-public.
00:33 They are internal to the module and therefore should not be used outside of the module. As we have seen before as well, you can actually still access those non-public names.
00:46 PEP 8 actually discourages wildcard imports. Remember PEP 8 from the earlier parts of the course. Wildcard imports should be avoided as they make it unclear which names are present in the namespace, confusing both readers and many automated tools.
01:04 So let’s look at an example. Please switch to your terminal,
01:09
and make sure that your terminal is in the directory where your shapes.py
module is saved. So in my case, that is in VSCodeUnderscores
.
01:20 Now from here, I would like to open the Python REPL as we have done before.
01:25
And now I’m going to do a wildcard import for the shapes module: from shapes import *
. Now I’m not going to press Enter yet. I would like to show you again what was actually in the shapes module.
01:41
This is the shapes module shapes.py
. We had _PI
and then we had a Circle
class, a Square
class, and then we had an _validate()
helper function.
01:53
And remember that at the very top, I also showed you the import statement for the true pi
number from the math library. So that is what’s in the shapes.py
module.
02:06
If you now move back to the REPL, let’s press Enter here and see what this import does. Well, let’s call dir()
and then let’s see what’s in the namespace.
02:18
You’ll recognize Circle
, you’ll recognize Square
, and you’ll recognize pi
, the one that was imported from the math library.
02:26
What you are not seeing is _PI
and _validate()
. So when you do a wildcard import using the asterisk, you are not importing the objects that are starting with a single leading underscore.
02:41 There are objects with double leading underscores and double trailing underscores, so these are dunder methods that we will cover later in the course.
02:50 That’s it for wildcard imports. See you in the next lesson.
Become a Member to join the conversation.