This article is mainly about Python modules and packages after studying the official documentation modules and packages to get the notes.

The module

A module is a file that contains Python definitions and statements.

The file name is the module name with the.py suffix. The a.py file is the module named A. The module name can be retrieved from the global __name__ inside the module.

Create an A.py file and simply print out the module name:

print(__name__)
Copy the code

Use the module

Modules can be used in interactive instances of scripts or interpreters. When a module is imported, the code in the module is executed.

(1) Used in interpreter interaction instances

Enter PYTHon3 at the terminal to enter the interpreter’s interactive mode and import a:

>>> import a
a
Copy the code

(2) Run it as a script

Enter:

python3 module_name.py <arguments>
Copy the code

Python3 is used instead of Python to distinguish it from Python2.

When this is executed, the code in the module is executed as if it were import, but the __name__ variable is set to ‘__main__’.

The optional

list of arguments passed to the command line is available via the sys module’s sys.argv property. Argv [0] takes the name of the script (argv[0] takes ‘-c’ if Python code is executed using -c
).

Modify the a.py code as follows:

print(__name__)

if __name__ == '__main__':
    import sys
    for argv in sys.argv:
        print(argv)
Copy the code

Sys is one of the built-in modules (also known as standard modules) built into the interpreter. Built-in modules are not the core of the Python language and are built into the interpreter for efficiency or to use the underlying operating system.

Python3 a.py 1 2 3:

$ python3 a.py 1 2 3
__main__
a.py
1
2
3
Copy the code

The module’s private symbol table

Each module has its own private symbol table, which is used as the global symbol table for functions defined in the module. Use global variables in modules without worrying about conflicts with user-defined global variables. Module_name. Item_name can be used to access module global variables.

Global_var = global_var; global_var = global_var; global_var = global_var; global_var = global_var;

P. y:

global global_var

global_var = 'global_var_b'
Copy the code

C.p y:

import b

global global_var

global_var = 'global_var_c'

print(b.global_var)
print(global_var)
Copy the code

It is also ok to declare a global variable without explicitly using global in this example, because the variable declared at that location is itself a global variable.

Execute python c.py and print:

global_var_b
global_var_c
Copy the code

The global_var variable with the same name is declared in module B and module C, but because they are in their own private symbol tables, they do not interfere with each other and cause conflicts.

Several ways to import modules

Create module d.py:

print('ddd')
_d1 = 'd1'

def func_d1() :
    print(_d1)

def _func_d2() :
    print('d2')
Copy the code

Variables starting with _ are private variables that are used only in modules. For practice, variables starting with _ are used in other modules.

(1) Directly import modules

>>> import d
ddd
>>> d._d1
'd1'
>>> d.func_d1()
d1
>>> d._func_d2()
d2
Copy the code

(2) Import the required items

>>> from d import _d1, func_d1
ddd
>>> _d1
'd1'
>>> func_d1()
d1
Copy the code

(3) Import all non-private items

This is not recommended because using * does not make it clear what items have been imported.

>>> from d import *
ddd
>>> _d1
Traceback (most recent call last):
  File "<stdin>", line 1.in <module>
NameError: name '_d1' is not defined
>>> func_d1()
d1
Copy the code

(4) Set the alias

Set the alias of the module:

>>> import d as d123
ddd
>>> d123.func_d1()
d1
Copy the code

Set aliases for imported items:

>>> from d import func_d1 as func_d123
ddd
>>> func_d123()
d1
Copy the code

Module search path

In the example above, instead of using import./d.py to import the module, we use import D directly, and the interpreter will find the module file for us.

When importing module D, the interpreter’s search path is as follows:

(1) First look for the built-in module named D.

(2) If not, look for the d.py file from the directory list in the sys.path. variable.

The positions contained in sys.path are: the directory of the input script (or the current directory if no file is specified), the directory list of the PYTHONPATH environment variable, and the default installation directory.

In e.py add:

import sys

print(sys.path)
Copy the code

Run python3 e.py to print the following:

['/Users/momo/ practice e.py file directory /code', '/ usr/local/Cellar/[email protected]/3.7.10 _2 / Frameworks/Python framework Versions / 3.7 / lib/python37. Zip', '/ usr/local/Cellar/[email protected]/3.7.10 _2 / Frameworks/Python framework Versions / 3.7 / lib/python3.7', '/ usr/local/Cellar/[email protected]/3.7.10 _2 / Frameworks/Python framework Versions / 3.7 / lib/python3.7 / lib - dynload', '/ Users/momo/virtualenvs for_test/lib/python3.7 / site - packages']Copy the code

Module cache

To speed up template loading, Python caches the compiled version of a module in a __pycache__ directory called module.version.pyc. Version is usually the Python version number.

The file directory after the above exercise looks like this:

. ├ ─ ─ __pycache__ │ ├ ─ ─ a.c python - 37. Pyc │ ├ ─ ─ biggest python - 37. Pyc │ ├ ─ ─ Arthur c. python - 37. Pyc │ └ ─ ─, dc python - 37. Pyc ├ ─ ─ Amy polumbo y ├── b.Bass Exercises ── B.bass exercises ─ d.bass exercisesCopy the code

package

Packages are a way of constructing Python module namespaces with “dot-module names”. For example, the module name A.B represents A submodule named B in package A.

I understand a package to be a folder of organized modules and __init__.py files. It can be obtained in the form of A.B.

Create a package

Python treats directories containing the __init__.py file as packages. __init__.py can be an empty file, contain package comfort code, or set the __all__ variable (which is used to declare the module to be imported when using from package import *, note that import * is not recommended).

We create a package e:

├ ─ ─ e │ ├ ─ ─ just set py │ ├ ─ ─ e1 │ │ ├ ─ ─ just set py │ │ ├ ─ ─ module_1. Py │ │ └ ─ ─ module_2. Py │ └ ─ ─ e2 │ ├ ─ ─ just set py │ └ ─ ─ module_3. PyCopy the code

Package E contains two subpackages, E1 and e2, which contain their respective modules. The code inside the module is simple:

var_1 = 'var_1'

def func_1() :
    print('module_1')
Copy the code

Use the package

Create a file e.py to import packages for the exercise:

├── e │ ├─ __init__. └ ─ ─ e.p yCopy the code

There are two ways to use packages in e.py files:

1. Useimport

import e.e1.module_1

e.e1.module_1.func_1()
Copy the code

Each time you use this method, write a complete submodule name: E.e.1.module_1.

Python3 e.py can be executed on the terminal to see the effect:

$ python3 e.py
module_1
Copy the code

When using import item.subitem.subsubitem, each item must be a package except for the last item, which can be a package or a module.

import e.e1.module_1.func_1
ModuleNotFoundError: No module named 'e.e1.module_1.func_1'; 'e.e1.module_1' is not a package
Copy the code

2. Usefrom ... import ...(This is recommended)

from e.e1 import module_1

module_1.func_1()
Copy the code

You can also import the desired function or variable directly:

from e.e1.module_1 import func_1

func_1()
Copy the code

When using from Package import item, the item can be a submodule of the package, a function or variable defined in the package, etc.

3. Import sibling packages to each other

① Use absolute imports

For MODULE_3 of E2, use module_1 of E1:

from e.e1 import module_1

module_1.func_1()
Copy the code

Modify the contents of the e.py file as follows:

from e.e2 import module_3
Copy the code

If python3 e.py is executed on the terminal, module_1 will be printed.

Using absolute imports is clear and convenient.

② Use relative import

Use E1 module_1 in E1 module_2:

from . import module_1
Copy the code

For MODULE_3 of E2, use module_1 of E1:

from ..e1 import module_1
Copy the code