Python tutorial: How long do you learn Python? Which is something you learn through it?

Python tutorial: How long do you learn Python? Which is something you learn through it?

If you are a novice Python programmers, one of the elements that you first need to learn is how to import a module or package. But I have noticed that people who use Python from time to time for many years not know Python's import mechanism is actually very flexible. In this article, we will discuss the following topics:

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

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 sys rename module named 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.

Use statement to import from

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 lrucache. If you import functools the usual way, then you must call lrucache like this:

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 *
复制代码

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 the os module variable or function with the same name, will be the actual use of the contents of your own definition. Therefore, you may encounter a very last people confused logic error. My only standard library module only recommend overall import Tkinter.

If you just want to write your own modules or packages, someone will suggest you import everything in _init_.py file, giving 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.

Relative imports

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 _init_.py file, enter the following code:

from . import subpackage1
from . import subpackage2
复制代码

Next, enter the subpackage1 folder, edit them _init_.py file, enter the following code:

from . import module_x
from . import module_y
复制代码

Now edit module_x.py file, enter the following code:

from .module_y import spam as ham
def main():
 ham()
复制代码

Last edited module_y.py file, enter the following code:

def spam():
 print('spam ' * 3)
复制代码

Open a terminal, cd to the folder where the file mypackage package, but do not enter mypackage. In this folder, run the Python interpreter. I am using IPython, because of its auto-complete feature is very handy:

In [1]: import my_package
In [2]: my_package.subpackage1.module_x
Out[2]: <module 'my_package.subpackage1.module_x' from 'my_package/subpackage1/module_x.py'>
In [3]: my_package.subpackage1.module_x.main()
spam spam spam
复制代码

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.

Also note that if you add if to modulex.py file _name__ == '_main_', and then try to run this file, you will encounter an error that is difficult to understand. Editor at the file, give it a try!

from . module_y import spam as ham
def main():
 ham()
if __name__ == '__main__':
 # This won't work!
 main()
复制代码

Now from the terminal enters subpackage1 folder, execute the following command:

python module_x.py
复制代码

If you are using Python 2, you should see the following error message:

Traceback (most recent call last):
 File "module_x.py", line 1, in <module>
 from . module_y import spam as ham
ValueError: Attempted relative import in non-package
复制代码

If you're using Python 3, an error message something like this:

Traceback (most recent call last):
 File "module_x.py", line 1, in <module>
 from . module_y import spam as ham
SystemError: Parent module '' not loaded, cannot perform relative import
复制代码

This means that, module_x.py is a module of a package, and you try to execute script mode, but this mode does not support relative imports.

If you want to use this module in your own code, then you must add it to import retrieve the path of Python (import search path). The simplest approach is as follows:

import sys
sys.path.append('/path/to/folder/containing/my_package')
import my_package
复制代码

Note that you need to add is mypackage of the folder one path instead mypackage itself. The reason is that we want to use my_package package, so if you add its path, will not be able to use this package.

We next turn to alternative import.

Alternatively introduced (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()])
复制代码

lxml optional packages are also used to import mode:

try:
 from urlparse import urljoin
 from urllib2 import urlopen
except ImportError:
 # Python 3
 from urllib.parse import urljoin
 from urllib.request import urlopen
复制代码

As shown in the above example, using the optional import is very common, it is a worthy skill to master.

Local delivery

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. E.g:

import sys # global scope
def square_root(a):
 # This import is into the square_root functions local scope
 import math
 return math.sqrt(a)
def my_pow(base_num, power):
 return math.pow(base_num, power)
if __name__ == '__main__':
 print(square_root(49))
 print(my_pow(2, 3))
复制代码

Here, we will import the sys module to the global scope, but we did not use this module. Then, in squareroot function, we will import math module to the local scope of the function, which means that math module can only be used inside squareroot function. If we try to use math in my_pow function, cause NameError. Try to execute this script and see what happens.

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)

Let's look at circulation import.

Circulation import

If you create two modules, both import at each other, then there will be introduced into circulation. E.g:

# a.py
import b
def a_test():
 print("in a_test")
 b.b_test()
a_test()
复制代码

Then create another module in the same folder, the name it b.py.

import a
def b_test():
 print('In test_b"')
 a.a_test()
b_test()
复制代码

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. I have read some of the crack method (hack) to solve this problem, but in general, you should do is refactor the code to prevent this from happening.

Import coverage

When you create a module with the same name as a standard module in the library, if you import the module, it will be covered by the import. For example, to create a file called math.py in which the code is written as follows:

import math
def square_root(number):
 return math.sqrt(number)
square_root(72)
复制代码

Now open a terminal, try to run this file, you will get back the following information (traceback):

Traceback (most recent call last):
 File "math.py", line 1, in <module>
 import math
 File "/Users/michael/Desktop/math.py", line 6, in <module>
 square_root(72)
 File "/Users/michael/Desktop/math.py", line 4, in square_root
 return math.sqrt(number)
AttributeError: module 'math' has no attribute 'sqrt'
复制代码

What exactly is going on? In fact, when you run this file, Python interpreter named math module first looks in the current script file located in the folder. In this example, the interpreter found the module we are implementing to try to import it. But we did not call the module and sqrt functions or attributes, so I threw out AttributeError.

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.



Reproduced in: https: //juejin.im/post/5cf0cac0f265da1b6b1cbcc4

Guess you like

Origin blog.csdn.net/weixin_34194702/article/details/91475729