#100DaysOfWeb in Python Transcripts
Chapter: Appendix: Python language concepts
Lecture: Concept: Imports and importing modules
Login or
purchase this course
to watch this video and the rest of the course contents.
0:01
Packages and modules must be imported in Python before they can be used. It doesn't matter if it's in external package of the package index,
0:10
in module from the standard library or even a module or package you yourself have created, you have to import it.
0:17
So code as it's written right here likely will not work, you will get some kind of NameError, "os doesn't exist, path doesn't exist".
0:24
That's because the os module and the path method contained within it have not been imported. So we have to write one of two statements above,
0:34
don't write them both, one or the other. So, the top one lets us import the module and retains the namespace,
0:40
so that we can write style one below, so here we would say os.path.exist so you know that the path method is coming out of the os module.
0:48
Alternatively, if you don't want to continue repeat os.this, os.that, and you just want to say "path", you can do that by saying this other style,
0:57
from os import path. And then you don't have to use the namespace, you might do this for method used very commonly
1:03
whereas you might use style one for methods that are less frequently used. Now, there is the third style here, where we could write "from os import *",
1:11
that means just like the line above, where we are importing path, but in fact, import everything in the os module.
1:18
You are strongly advised to stay away from this format unless you really know what you are doing, this style will import and replace
1:25
anything in your current namespace that happens to come out of the os. So for example, if you had some function that was called register,
1:34
and maybe there is a register method inside os module, this import might erase your implementation, depending where it comes from.
1:42
So, modules must be imported before you use them, I would say prefer to use the namespace style, it's more explicit on where path actually comes from,
1:51
you are certain that this is the path from the os module, not a different method that you wrote somewhere else
1:55
and it just happens to have the same name. Style two also works well, style three- not so much.