Import and modular python

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

1. Import

import statement:
  1. Find the specified module is loaded and initialized generation module object can not be found, an exception is thrown
  2. Cash in the local namespace associated with the scope of import is located, and further increase the name created on
# import os.path  # 注意os模块和path模块都加载了,但是dir()中只能拿到os
import os  # import后只能写模块名
import os.path
import os.path as osp  # 取别名,注意是os.path的别名,不是os的别名

print(dir())
# ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
# '__package__', '__spec__', 'os']
# print(sorted(locals().keys()))
# print(sorted(globals().keys()))

print(os)
print(os.path)
print(osp)
print(os.path.exists('c:/tt'))  # 虽然没有导入path模块但是解释器替你做了,所以此语句可以执行
print(osp.exists('c:/text.txt'))

def a():
    import pathlib
    print(dir())  # ['pathlib'] 受作用域的影响


a()
print('~~~~~~~~~~')
print(dir())
# ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
# '__package__', '__spec__', 'a']

  Summary: Import top-level module, its name will be added to the local term space, and bind to its module object; import non-top-level module, only its top-level module name is added to the local term space. Import module must be fully qualified name to access. If you used as, as the name bind directly to the imported module object, and the local name added with the term space.

from ... import statement
from os import stat  # from后必须是模块,可以逗号分隔
from os.path import exists
from pathlib import Path
from pathlib import *
from functools import _make_key
# from os import path as osp
from functools import wraps as wr, update_wrapper

# from module import * | module | class | function | ...
print(dir())

from os.path import exists  # 注意from后的模块并不导入,只是加载
import os.path


print(exists)

print(os.path.exists)
print(os.path.__dict__['exists'])
print(getattr(os.path, 'exists'))
# <function exists at 0x0000000001DE31E0>
to sum up:
  • Find the from clause specified in the module, loads and initializes it (note not import)
  • For the name of the import clause:
        1. First check whether the import clause from the module has an attribute that name
        2. If not, then try to import sub-module that name
        3. have not found, an exception is thrown ImportError
        4. the name to save space in local terms, as if clause, after the name is used as clause
from pathlib import Path
import pathlib as pl


print(id(Path), Path)
# 42604072 <class 'pathlib.Path'>
print(id(pl.Path), pl.Path)
# 42604072 <class 'pathlib.Path'>
p1 = Path()
p2 = pl.Path()  # 注意p1和p2肯定不一样
print(Path is pl.Path)  # True

2. Custom Modules

Custom module naming convention:

  1. The module name is the file name
  2. The module name must meet the requirements of an identifier, a combination of letters, numbers, and underscores beginning of non-digital, and do not use Chinese.
  3. Do not use the system module name to avoid conflict, unless you know the name of the module uses.
  4. Usually the module name all lowercase, underscores to separate.

3. The module search order

Use sys.path View search order:

import pathlib
import sys


print(*sys.path, sep='\n')
print(pathlib.Path.__doc__)
print(sys.path)
"""C:\Users\Administrator\PycharmProjects\面向对象进阶\venv\Scripts\python.exe C:/Users/Administrator/PycharmProjects/面向对象进阶/模块化/导入.py
C:\Users\Administrator\PycharmProjects\面向对象进阶\模块化
C:\Users\Administrator\PycharmProjects\面向对象进阶
C:\Users\Administrator\PycharmProjects\面向对象进阶\venv\Scripts\python36.zip
C:\Users\Administrator\AppData\Local\Programs\Python\Python36\DLLs
C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib
C:\Users\Administrator\AppData\Local\Programs\Python\Python36
C:\Users\Administrator\PycharmProjects\面向对象进阶\venv
C:\Users\Administrator\PycharmProjects\面向对象进阶\venv\lib\site-packages
C:\Users\Administrator\PycharmProjects\面向对象进阶\venv\lib\site-packages\setuptools-39.1.0-py3.6.egg
C:\Users\Administrator\PycharmProjects\面向对象进阶\venv\lib\site-packages\pip-10.0.1-py3.6.egg
PurePath subclass that can make system calls.

    Path represents a filesystem path but unlike PurePath, also offers
    methods to do system calls on path objects. Depending on your system,
    instantiating a Path will return either a PosixPath or a WindowsPath
    object. You can also instantiate a PosixPath or WindowsPath directly,
    but cannot instantiate a WindowsPath on a POSIX system or vice versa.
    
['C:\\Users\\Administrator\\PycharmProjects\\面向对象进阶\\模块化', 'C:\\Users\\Administrator\\PycharmProjects\\面向对象进阶', 'C:\\Users\\Administrator\\PycharmProjects\\面向对象进阶\\venv\\Scripts\\python36.zip', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\Administrator\\PycharmProjects\\面向对象进阶\\venv', 'C:\\Users\\Administrator\\PycharmProjects\\面向对象进阶\\venv\\lib\\site-packages', 'C:\\Users\\Administrator\\PycharmProjects\\面向对象进阶\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg', 'C:\\Users\\Administrator\\PycharmProjects\\面向对象进阶\\venv\\lib\\site-packages\\pip-10.0.1-py3.6.egg']

"""

  When you load a module when needed from front to back in order to find these search path, do not search the subdirectories of these directories. Search module to load, search not to throw an exception. The path can also be a dictionary, zip file, egg file. .egg file, created by the setuptools package libraries, third party libraries commonly used formats, add a zip file metadata information.
Path order:

  1. The main program directory, run the main script directory where
  2. PYTHONPATH directory, the directory also set the environment variable PYTHONPATH search path module
  3. Standard library catalog, Python comes with a library module directory.

3. Run Module

  name , each module will define a __name__ special variable to store the name of the current module, if not specified, it defaults to the source file name, the package is limited if it is named.
Interpreter initialization time, initializes sys.modules dictionary (save the loaded modules), load the builtins (global functions, constants) module, main__ module, sys module, and initialize the module search path sys.path
Python scripting language, any script can be executed directly, or as a module imports. When the standard input (knock command code), script ($ Python the test.py time) or interactive read, the module will be provided for the __name__ in __main
, the top-level code modules in this role __main__ execution domain. Top Code: Indent outermost module code. If the import is imported, its __name__ default is the module name.

if name == ‘main’:用途
  1. Functional testing of the module: the main module for the non-test function of the module, the class
  2. Avoiding side effects master switching module: codes top, without the package, there is no problem when the main module. However, once a new master module, the module would be the old master module is introduced, since the code is not the original package, performed together.

4. Package

  pycharm, create Directiory and create different Python package, the former is to create a common catalog, which is to create a directory with __init__.py file, that package.

4.1 sub-module

py file in the package directory, subdirectory all its sub-modules.

4.2 summary of modules and packages

  Better organization module package, especially a large module that many lines of code, it can be split into many sub-module, it is easy to use certain functions to load the appropriate module.Package directory the init .py will be executed when the package was first introduced, content can be empty, can also be used for initialization code for the package, it is best not to delete it (lower version can not be deleted). Import sub-modules will be the parent module loads, but will not import the parent module import module. Can only be used between the package directory. Point number as the break character, showing the hierarchical relationship of the modules and submodules. Modules are packaged, such as the same function, but it is possible to package variables, classes, functions. A module is a namespace, the inside top identifier, its properties are, by dict view or dir (module). Packages are modules, but not necessarily a bag module, the module is a special packet, an organization, comprising path properties.

# import a  # 注意目录没有__file__属性
#
#
# print(dir(a))
# print(type(a))
# print(a)
# print(a.__path__)
# print(a.x)


# import m  # 注意只加载m,不会递归加载
# from m import m1
# import m.m1
# import m.m2.m21
import m
from m.m2 import m22  # 此时m2不在当前名词空间中
import sys


print(dir())  # 加载了m和m1,当前名词空间中只有m
# print(m.m1)

print(list(filter(lambda x: x.startswith('m'), sys.modules.keys())))
print(m.abc)
print(m.m2.y)
print(m.m2.__dict__.keys())
print(m.m2.m22)

Note: Do not delete file __init__.py

5. Absolute introduced, relative introduced

5.1 absolute imports

  In the import statement or from import module, the module name to the front than the beginning. Point. Import absolutely always go to the module search path to find, of course, will look at whether the module has been loaded.

5.2 relative imports

  It can only be used within the package, and can be used only from statementsUsed. Dot represents the current directory, ... indicate the parent directory, not in the top relative import module.

from . import d  # 有相对导入的模块不能作为主模块了,直接运行会报错
from .. import e

# d = 1000
print(d.__file__)
print(e.__file__)

== Note: refer to each other between the inner cladding, relative import basically, once a module is used relative imports, as the main module can not run. ==

6. Access Control

6.1 module name begins with an underscore

  __ _ or the beginning of the module is able to be introduced into it? Create a file called _xyz.py or __xyz.py measure can be successfully imported because they are valid identifier, it can be used as the module name.

print(__name__)
A = 5
_B = 20
__C = 300

print(dir())
# ['A', '_B', '__C', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', 
# '__loader__', '__name__', '__package__', '__spec__']

  Common variable, variable protection, private variables, special variables, have not been hidden, which means that no private variables within the module, no special processing is defined in the module.

# import test
#
# from test import A, _B, __C
from test import *  # 最前面带下划线的是无法导入的


print(dir())

6.2 from … import * 和__all__

  all__ is a list of elements is a string, each element is a variable name in the module. from xyz import *, if xyz is defined __all , only the import __all__ name in the list, no __all__ method, you can import only publicly owned.

# test.py
print(__name__)

__all__ = ['X', '_Y']

X = 5
_Y = 20
__Z = 300

__my__ = 500


def _a():
    pass


class __A:
    pass


print(dir())

# test2.py
from test import *  # 只能导入__all__列表中的名称,即X, _Y
import test


print(dir())
print(test._Y)
to sum up:

1, using imported from xyz import *

  • If the module is not All , from xyz * Import to import only the first non-underlined the module variable. If the packet is the sub-module not introduced unless
    all settings, or the init .py import them

  • If the module has all , from xyz Import * Import only all specified in the list of names, even if the term is to begin with an underscore, or sub-modules

  • Import from xyz import * mode, simple to use, but its side effects are imported without the use of a large number of variables, and even may cause a conflict name. And all can be introduced into the controlled variable name introduced in this way the module can provide, it is to prevent too much from xyz import * variables import module, thus avoiding collisions. Therefore, when writing module, you should try to join All .

2、from module import name1, name2 导入
  Introduced in this way is clear, even if it is introduced into the sub-module names begin with an underscore or import programmers for introducing the name and its corresponding control object.
3. The modification variable module
  Module objects are the same, so the variable module is the same, to modify the module variable will affect all users. Unless a last resort, or know exactly what you're doing, do not change the variable module. Monkeys learned earlier patch, or by patching the way, modify the contents of variables, classes, functions, and other modules.

Guess you like

Origin blog.csdn.net/sqsltr/article/details/90673614