11 - Python import module package

@Author : Roger TX ([email protected])
@Link : https://github.com/paotong999

Summary Python import module

Python includes a wealth of built-in modules and external packages, often need to import the module or pack in their daily programming, Python's import mechanism is actually very flexible. It will be described herein below aspects related issues introduced module package:

  • General Import (regular imports)
  • Use statement to import from
  • Introducing opposite (relative imports)
  • Optional introduction (optional imports)
  • Local introduced (local imports)

First, the General Import

General Import to import should be used in the most ordinary way, something like this:

import sys

You only need to use the word import, and then specify the module or package you want to import. Benefits introduced by this manner is introduced into a plurality of disposable packages or modules:

import os, sys, time

While this saves space, but contrary to the Python style guide. Python Style Guide recommends that each import statement on a separate line.
Sometimes when you import the module you want to rename this module. This feature is easy to implement:

import sys as system
print(system.platform)

The code above we import the sysmodule is renamed system. We can call the modules in accordance with the ways and means the same as before, but with a new module name. There are also some sub-modules must use dot notation to import.

import urllib.error

This situation is not common, but know something about always do no harm.

Second, the use fromstatement to import

Many times you only want to import a part of a module or library. We look at how to achieve this in Python:

from functools import lru_cache

The above line of code that lets you directly call lru_cache. If you import functools the usual way, then you have to call something like this lru_cache:

functools.lru_cache(*args)

Depending on your actual usage scenario, the above approach may be better. In a complex code base, which can be seen from the point where a function is imported useful. However, if your code is well maintained, high degree of modularity, then import only from a certain part of the module is also very easy and simple.

Of course, you can also use all methods to import content from the module, like this:

from os import *

This practice should be noted that __all__this variable. This variable is the built-in variable, not shown default value, includes all. However, if the function is defined, only the value in the variable introduced. Can py, you can also file in the package __init__.pyappears in.

  • When used in a normal module, which represents a property module allows other modules may be introduced into the
  • In the package __init__.pywhen the package is only introduced into the __all__module is contained within the variable, but __init__.pymay perform some initialization content, such as: from . import test1introduction of other modules in the current directory

In a few cases this practice is very convenient, but it will also disrupt your namespace. The problem is, you might define an import module with the same name as variable or function, then if you try to use osmodules of the same name variables or functions, the actual use will be what you define yourself. Therefore, you may encounter a very last people confused logic error. My only standard library modules imported only recommend overall Tkinter.

If you just want to write your own modules or packages, someone will suggest you __init__.pyimport all the content files, so that module or package easier to use. I personally prefer to import the display, rather than implicitly imported.
You can also take the compromise to import multiple items from a package:

from os import path, walk, unlink
from os import uname, remove

In the above code, we introduced five functions from os module. You may have noticed, we are through multiple imports from the same module to achieve. Of course, if you prefer, you can also use parentheses to import multiple disposable items:

from os import (path, walk, unlink, uname, remove, rename)

This is a useful technique, but you can also put it another way:

from os import path, walk, unlink, uname, \
             remove, rename

Backslash is above the Python line continuation character, line tells the interpreter it continues to the next row.

Third, the relative introduced

PEP 328 describes the reasons for the introduction of relative imports, and chose which syntax. Specifically, it is to decide how to use a period relative to import other packages or modules. The reason for this is to avoid introducing standard library module case occasionally conflict. Here we give the file in the folder structure to PEP 328 as an example, look at the relative import is how it works:

my_package/
    __init__.py
    subpackage1/
        __init__.py
        module_x.py
        module_y.py
    subpackage2/
        __init__.py
        module_z.py
    module_a.py

Find a place to create the above files and folders on the local disk. In the top of the __init__.pyfile, enter the following code:

from . import subpackage1
from . import subpackage2

Next, enter the subpackage1folder in which to edit the __init__.pyfile, enter the following code:

from . import module_x
from . import module_y

Now edit the module_x.pyfile, enter the following code:

from module_y import spam as ham

def main():
    ham()

Relative import applies to you eventually have to put the code in the package. If you write a lot of strong correlation code, you should use this import mode. You will find many popular package also uses relative imports on PyPI. Also note that if you want to import levels across multiple files, you only need to use multiple periods. However, PEP 328 recommended levels relative to import no more than two layers.

Fourth, the optional introduction (Optional imports)

If you want to use a priority module or pack, but also want to have an alternative in the absence of this module or pack case, you can use the optional import this way. Doing so can import multiple versions of a software or support to achieve performance gains. In github2 package code as an example:

try:
    # For Python 3
    from http.client import responses
except ImportError:  
     # For Python 2.5-2.7
    try:
        from httplib import responses  # NOQA
    except ImportError:      # For Python 2.4
        from BaseHTTPServer import BaseHTTPRequestHandler as _BHRH
        responses = dict([(k, v[0]) for k, v in _BHRH.responses.items()])

Fifth, the local import

When you are in the role of local import modules in the domain, you do it is a local import. If you import a Python module at the top of the script file, then you are introduced to the global scope in the module, which means that any function or method may access the following modules.

The module introduced into local scope function, which means that the module can only be used within a function. One of the benefits of using local scope, is the module that you use to import may take a long time, if that is the case, place it in a function call is not always in perhaps more reasonable, rather than directly in the global scope import.

Honestly, I almost never used local import, mainly because if the import statements are everywhere inside the module, it will be difficult to distinguish the reasons for doing so and use. By convention, all import statements should be located on top of the module.

Import Notes

In terms of import module, there are several programmers often make mistakes. Here we introduce two.

  • Introduction cycle (circular imports)
  • Import cover (Shadowed imports, import temporarily to cover translation)

Importing cycle
if you create two modules, both import at each other, then there will be introduced into circulation.
If you run any of the modules, will lead AttributeError. This is because these two are trying to import other modules. In short, we want to import module is a module b, b but because the module is also trying to import a module (then being performed), a module will not be able to complete the import module b, the general need to avoid this from happening.

Import coverage
when the module with the same name as the standard library module you created if you import the module, will be covered by the import. Interpreter first looks module with the same name in the current script is located in the folder.

to sum up

In this article, we talked about importing a lot of content, but also in part not involved. PEP 302 introduces import hook (import hooks), in support of some very cool features, such as imported directly from github. Python standard library also has a importlib module, it is worth learning to see. Of course, you can also see more of the code written by someone else, continue to tap more useful coup.

Reproduced in: https: //www.jianshu.com/p/0c626120779e

Guess you like

Origin blog.csdn.net/weixin_33795833/article/details/91053874