Introduction
TheImportAndFrom-importStatements are a constant cause of serious confusion for newcomers to Python. Luckily, once you 've figured out what they really do, you'll never have problems with them again.
This note tries to sort out some of the more common issues relatedImportAndFrom-importAnd everything.
There are always Ways to Import a Module
Python provides at least three different ways to import modules. You can useImportStatement,FromStatement, or the builtin_ Import __Function. (There are more contrived ways to do this too, but that's outside the scope for this small note .)
Anyway, here's how these statements and functions work:
Import XImports the module X, and creates a reference to that module in the current namespace. Or in other words, after you 've run this statement, you can useX. nameTo refer to things defined in module X.
From X import *Imports the module X, and creates references in the current namespace to allPublicObjects defined by that module (that is, everything that doesn't have a name starting with "_"). or in other words, after you 've run this statement, you can simply use a plainNameTo refer to things defined in module X. But X itself is not defined, soX. nameDoesn' t work. And ifNameWas already defined, it is replaced by the new version. And ifNameIn X is changed to point to some other object, your module won't notice.
From X import a, B, cImports the module X, and creates references in the current namespace to the given objects. Or in other words, you can now useAAndBAndCIn your program.
Finally,X = _ import _ ('x ')Works likeImport X, With the difference that you 1) pass the module name as a string, and 2) explicitly assign it to a variable in your current namespace.
What Does Python Do to Import a Module?When Python imports a module, it first checks the module registry (Sys. modules) To see if the module is already imported. If that's the case, Python uses the existing module object as is.
Otherwise, Python does something like this:
- Create a new, empty module object (this is essential a dictionary)
- Insert that module object inSys. modulesDictionary
- Load the module code object (if necessary, compile the module first)
- Execute the module code object in the new module's namespace. All variables assigned by the code will be available via the module object.
This means that it's fairly cheap to import an already imported module; Python just has to look at the module name up in a dictionary.