How to import python modules

regular import

Regular import is the most commonly used import method, as follows

import time
import os

While this saves space, it goes against the Python style guide. The Python Style Guide recommends putting each import statement on its own line. Sometimes when importing a module, you want to rename the module in the following way

import time as mytime
import os as myos

relative import

# demo1
from ..test2.demos2 import *
#如果直接运行demo1 ValueError: attempted relative import beyond top-level package
#demo1是某个包中的一个模块,而你试图以脚本模式执行,这种模式不支持相对导入。
可以采用绝对导入解决
from 根目录名.test.test1.demo1 import  *

In python, only relative import can be used in the package, and relative import cannot be used in the user's application, because whether it is relative import or absolute import, it is equivalent to the current module. For the user's main application, that is For the entry file, the module name is always " main ", so the user's application must use absolute imports, while the imports in the package can use relative imports.
Here, relative import ., .., should be understood as: . : Search in the current package.. : Search in the previous package

#demo1.py
a=2
b=3

# demos2.py
from ..test1.demo1 import *
c=4
d=5
print(b)

#test
from 根目录名.test.test2.demos2 import *
print(a)

#运行test 输出 3 2 运行demos2.py ValueError: attempted relative import beyond top-level package

Import using the from statement

Many times you just want to import a module or part of a library

from re import RegexFlag

It is better to use the above approach in the scenario. In complex codebases, it can be useful to be able to see where a function was imported from. However, if your code is well maintained and modular, it is very convenient and concise to import only part of the content from a module.
If you happen to be writing your own module or package, some people would suggest that you import everything in the __init__.py file to make the module or package easier to use. I personally prefer explicit imports rather than implicit imports.
The backslash is a line continuation character in Python, telling the interpreter that this line of code continues to the next line.

from os import path,name
from os import (path,name)
这是一个有用的技巧,不过你也可以换一种方式:

from os import path,\
    name

#spam.py
print('from the spam.py')

money=1000

def read1():
    print('spam->read1->money',money)

def read2():
    print('spam->read2 calling read')
    read1()

def change():
    global money
    money=0
#测试一:导入的函数read1,执行时仍然回到spam.py中寻找全局变量money
#test.py
from spam import read1
money=1000
read1()
'''
执行结果:
from the spam.py
spam->read1->money 1000
'''

#测试二:导入的函数read2,执行时需要调用read1(),仍然回到spam.py中找read1()
#test.py
from spam import read2
def read1():
    print('==========')
read2()

'''
执行结果:
from the spam.py
spam->read2 calling read
spam->read1->money 1000
'''

#测试三:导入的函数read1,被当前位置定义的read1覆盖掉了
#test.py
from spam import read1
def read1():
    print('==========')
read1()
'''
执行结果:
from the spam.py
==========
'''
from spam import *
#把spam中所有的不是以下划线(_)开头的名字都导入到当前位置,大部分情况下我们的python程序不应该使用这种导入方式,因为*你不知道你导入什么名字,很有可能会覆盖掉你之前已经定义的名字。而且可读性极其的差,在交互式环境中导入时没有问题。 
from spam import * #将模块spam中所有的名字都导入到当前名称空间
print(money)
print(read1)
print(read2)
print(change)

'''
执行结果:
from the spam.py
<function read1 at 0x1012e8158>
<function read2 at 0x1012e81e0>
<function change at 0x1012e8268>
'''
__all__来控制*(用来发布新版本)
在spam.py中新增一行

__all__=['money','read1'] #这样在另外一个文件中用from spam import *就这能导入列表中规定的两个名字

circular import

If you create two modules that import each other, circular imports occur. E.g:

a.py

import b

def demo():
    print("in a_demo")
    a.demo()

demo()

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

import a

def demo():
    print('In b_demo"')
    a.demo()

demo()

If you run either module, an AttributeError will be raised. 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 currently executing), module a will not be able to complete the import of module b. In general, the solution is to refactor the code to avoid this from happening.

init.py

As long as the package is imported for the first time or any other part of the package, the __init__.py file under the package will be executed in turn (we can print a line in each package file to verify), this file can be empty , but you can also store some code to initialize the package

from glance.api import *

Import all from the package api. In fact, this statement will only import the names defined in the __init__.py file under the package api. We can define __all___ in this file:

x=10

def func():
    print('from api.__init.py')

__all__=['x','func']
# __init__.py 文件的作用是将文件夹变为一个Python模块,Python 中的每个模块的包中,都有__init__.py 文件。  

# 通常__init__.py 文件为空,但是我们还可以为它增加其他的功能。我们在导入一个包时,实际上是导入了它的__init__.py文件。这样我们可以在__init__.py文件中批量导入我们所需要的模块,而不再需要一个一个的导入。

# __init__.py中还有一个重要的变量,__all__, 它用来将模块全部导入。

# py文件的汇编,只有在import语句执行时进行,当.py文件第一次被导入时,它会被汇编为字节代码,并将字节码写入同名的.pyc文件中。后来每次导入操作都会直接执行.pyc 文件(当.py文件的修改时间发生改变,这样会生成新的.pyc文件),在解释器使用-O选项时,将使用同名的.pyo文件,这个文件去掉了断言(assert)、断行号以及其他调试信息,体积更小,运行更快。(使用-OO选项,生成的.pyo文件会忽略文档信息)
# __init__.py
__all__ = ['os', 'sys', 're', 'urllib']
# a.py
from package import *

#这时就会把注册在__init__.py文件中__all__列表中的模块和包导入到当前文件中来。
#可以了解到,__init__.py主要控制包的导入行为。要想清楚理解__init__.py文件的作用,还需要详细了解一下import语句引用机制:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325813154&siteId=291194637
Recommended