欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

[Python] Importing Python Modules

程序员文章站 2022-09-10 11:19:53
introduction the import and from-import statements are a constant cause of serious confu...

introduction

the import and from-import statements 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 related to import and from-import and everything.

there are many ways to import a module

python provides at least three different ways to import modules. you can use the import statement, the 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 x imports 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 use x.name to refer to things defined in module x.

  • from x import * imports the module x, and creates references in the current namespace to all publicobjects 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 plain name to refer to things defined in module x. but x itself is not defined, so x.name doesn’t work. and if name was already defined, it is replaced by the new version. and if name in x is changed to point to some other object, your module won’t notice.

  • from x import a, b, c imports the module x, and creates references in the current namespace to the given objects. or in other words, you can now use a and b and c in your program.

  • finally, x = __import__(‘x’) works like import 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:

    1. create a new, empty module object (this is essentially a dictionary)
    2. insert that module object in the sys.modules dictionary
    3. load the module code object (if necessary, compile the module first)
    4. 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 the module name up in a dictionary.