Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to import module with Python

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to import Python module", the content of the explanation is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn "Python how to import module" bar!

Regular import

Regular import should be the most commonly used import method, something like this:

Import sys

You just need to use the word import and then specify the module or package you want to import. The advantage of importing in this way is that you can import multiple packages or modules at once:

Import os, sys, time

Although this saves space, it violates the Python style guidelines. The Python style guide recommends that each import statement be on a separate line.

Sometimes when you import a module, you want to rename it. This feature is easy to implement:

Import sys as system print (system.platform)

The above code renames the sys module we imported to system. We can call the module's method in the same way as before, but we can use a new module name. There are also some submodules that must be dotted before they can be imported.

Import urllib.error

This situation is not common, but it always does no harm to know something about it.

Import using the from statement

Many times you just want to import a module or a part of the library. Let's take a look at how to do this in Python:

From functools import lru_cache

The above code allows you to call lru_cache directly. If you import functools as usual, you must call lru_cache like this:

Functools.lru_cache (* args)

Depending on your actual usage scenario, the above approach may be better. In a complex code base, it is useful to see where a function was imported. However, if your code is well maintained and highly modular, it is convenient and concise to import only part of the content from a module.

Of course, you can also import the entire contents of the module using the from method, like this:

From os import *

This is convenient in a few cases, but it can also disrupt your namespace. The problem is that you may have defined a variable or function with the same name as the import module, and if you try to use a variable or function with the same name in the os module, you will actually use what you define. As a result, you may end up with a rather confusing logic error. The only module in the standard library that I recommend importing completely is Tkinter.

If you happen to be writing your own module or package, you will be advised to import everything in the _ _ init__.py file to make the module or package easier to use. Personally, I prefer to import explicitly rather than implicitly.

You can also compromise by importing multiple items from a package:

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

In the above code, we imported five functions from the os module. You may have noticed that we did this by importing from the same module multiple times. Of course, you can also import multiple items at once using parentheses if you like:

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

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

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

The above backslash is a continuation character in Python, telling the interpreter that this line of code continues to the next line.

Relative import

PEP 328 describes the reasons for introducing relative imports and which syntax you chose. Specifically, periods are used to determine how to import other packages or modules relatively. The reason for this is to avoid conflicts between modules imported into the standard library by chance. Here we take the folder structure given in PEP 328 as an example to see how relative imports work:

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 on your local disk to create the above files and folders. In the top-level _ _ init__.py file, enter the following code:

From. Import subpackage1 from. Import subpackage2

Next, go to the subpackage1 folder, edit the _ _ init__.py file, and enter the following code:

From. Import module_x from. Import module_y

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

From .module _ y import spam as ham def main (): ham ()

Finally, edit the module_y.py file and enter the following code:

Def spam (): print ('spam' * 3)

Open the terminal and cd to the folder where the my_package package is located, but do not enter my_package. Run the Python interpreter under this folder. I use IPython because its auto-completion function is very convenient:

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 imports apply to the code you eventually put into the package. If you have written a lot of highly relevant code, you should use this import method. You will find that there are many popular packages on PyPI that also use relative imports. Also note that if you want to import across multiple file levels, you only need to use multiple periods. However, PEP 328 recommends no more than two tiers relative to the imported level.

Also note that if you add if__name__=='__main__', to the module_x.py file and then try to run the file, you will encounter an error that is difficult to understand. Edit the file and try it.

From. Module_y import spam as ham def main (): ham () if _ _ name__ ='_ _ main__': # This won't work! Main ()

Now enter the subpackage1 folder from the terminal and 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 from. Module_y import spam as ham ValueError: Attempted relative import in non- package

If you are using Python 3, the error message looks something like this:

Traceback (most recent call last): File "module_x.py", line 1, in 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 in a package and you try to execute it in script mode, but this mode does not support relative import.

If you want to use this module in your own code, you must add it to Python's import retrieval path (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 what you need to add is the folder path above the my_package, not the my_package itself. The reason is that my_package is the package we want to use, so if you add its path, you will not be able to use this package.

Let's talk about optional import.

Optional Import (Optional imports)

If you want to give priority to a module or package, but also want to have an alternative without that module or package, you can use the optional import method. By doing so, you can import multiple versions of a software that support it or achieve performance improvements. Take the code in the github2 package as an example:

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

The lxml package also uses an optional import method:

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, the use of optional imports is common and is a skill worth mastering.

Local import

When you import a module in a local scope, you perform a local import. If you import a module at the top of the Python script file, you are importing the module into the global scope, which means that any subsequent function or method may access the module. For example:

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 import the sys module into the global scope, but we do not use this module. Then, in the square_root function, we import the math module into the local scope of the function, which means that the math module can only be used within the square_root function. If we try to use math in the my_pow function, NameError is thrown. Try to execute the script and see what happens.

One of the advantages of using a local scope is that the module you use may take a long time to import, and if so, it may make more sense to place it in a function that is not called frequently rather than directly in the global scope. To be honest, I have almost never used partial imports, mainly because if there are import statements everywhere inside the module, it will be difficult to tell the reason and purpose of doing so. By convention, all import statements should be at the top of the module.

Import consideration

There are several common mistakes made by programmers when it comes to importing modules. Here we introduce two.

Circular Import (circular imports)

Override import (Shadowed imports, temporarily translated as override import)

Let's take a look at the circular import first.

Circular import

If you create two modules that import each other, there will be a circular import. For example:

# a.py import b def a_test (): print ("in a_test") b.b_test () a_test ()

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

Import a def b_test (): print ('In test_b "') a.a_test () b_test ()

If you run any module, it will raise an AttributeError. This is because both modules are trying to import each other. Simply put, module a wants to import module b, but because module b is also trying to import module a (which is being executed at this time), module a will not be able to complete the import of module b. I've seen some hack solutions to this problem, but in general, what you should do is ReFactor the code to avoid this.

Override import

When you create a module with the same name as a module in the standard library, if you import the module, an override import will occur. For example, create a file called math.py and write the following code in it:

Import math def square_root (number) return math.sqrt (number) square_root (72)

Now open the terminal, try to run this file, and you will get the following traceback information:

Traceback (most recent call last): File "math.py", line 1, in import math File "/ Users/michael/Desktop/math.py", line 6, in 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 on earth is going on? In fact, when you run this file, the Python interpreter first looks for a module called math in the folder where the script is currently running. In this example, the interpreter finds the module we are executing and tries to import it. But we don't have a function or property called sqrt in our module, so we throw AttributeError.

Thank you for your reading, the above is the content of "how to import the module of Python". After the study of this article, I believe you have a deeper understanding of how to import the module of Python, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report