Python3 module

Module

Introduction to Python3 modules

A module is a file that contains all the functions and variables you define, and its suffix is .py. Modules can be introduced by other programs to use functions and other functions in the module. This is also the way to use the Python standard library. We can encapsulate some reusable functions that have been written into modules and then publish them to the Python native library. Then you can import your written module in other programs. Simply put, the module is like a commonly used part. For example, when assembling a Gundam model, you can take the ready-made parts and use it to speed up our assembly speed. If the parts are all made by ourselves, it will be much slower and more difficult. The modules in the standard library are parts of Python that are provided for us to use. We can also develop our own modules. After the modules developed by ourselves are published locally, they can be used like the modules in the standard library.
The following is an example of using modules in the python standard library.

import sys  #The key word of the imported module is import, here the sys module is imported

print("The command line parameters are as follows:")for i in sys.argv:  #The variable or function in it can be called through the module
 print(i)print("\n\The nPython path is:")for path in sys.path:print(path)

operation result:

The command line parameters are as follows:
 E:/PythonProject/TestMould.py
The Python path is:
 E:\PythonProject
 E:\PythonProject
 E:\Python3.6\python36.zip
 E:\Python3.6\DLLs
 E:\Python3.6\lib
 E:\Python3.6
 E:\Python3.6\lib\site-packages

1、 import sys import the sys.py module in the python standard library; this is the method to import a certain module.
2、 sys.argv is a list of command line parameters.
3、 sys.path contains a list of paths where the Python interpreter automatically finds the required modules.

import statement

The import statement is used to import modules in the Python library. The modules can be used after being imported. The syntax is as follows:

import module1[, module2[,… moduleN]

When the interpreter encounters an import statement, the module will be imported if it is in the current search path. The search path is a list of all directories that the interpreter will search in advance.
For example: we create a model.py file in the PyCharm tool, this file is equivalent to a module, and then you can customize a function in the file

Then create a Hello.py file, in which this module can be imported through import, and the functions in this module can be called through the imported module:

# Filename: Hello.py

# Import module
import model

# Now you can call the functions contained in the module
model.println()

operation result:

Test!

If you plan to use a function often, you can assign it to a variable:

import model

println=model.println
println()

operation result:

Test!

The above example belongs to the process of creating and importing a custom module.

A module will only be imported once, no matter how many import statements you execute, so this prevents the imported module from being executed over and over again.
When we use the import statement, how does the Python interpreter find the corresponding file?
This involves the Python search path:

This looks a lot like environment variables. In fact, the search path can also be determined by defining environment variables.
You can do a simple experiment to view the Python search path, code example:

import sys

print(sys.path) #Print out the directory listing

operation result:

[ ‘E:\PythonProject’, ‘E:\PythonProject’, ‘E:\Python3.6\python36.zip’, ‘E:\Python3.6\DLLs’, ‘E:\Python3.6\lib’, ‘E:\Python3.6’, ‘E:\Python3.6\lib\site-packages’]

sys.path returns a list, the first item of which represents the current directory (if executed from the interpreter, it will be an empty string), which is the path where the .py file is located.

from…import statement

Python's from statement allows you to import specified functions or variables from the module into the current script. The syntax is as follows:

from modname import name1[, name2[, … nameN]]

For example, to import the println function of the model module, the code example:

from model import println

println()

This statement will not import the entire model module into the current script, it will only import the println function in the model, and then we can directly call this function.
If you want to import multiple functions or variables, you need to use commas to separate them.

from…import statement*

It is possible to import all the contents of a module into the current script, just use the following statement:

from modname import *

This provides an easy way to import all the items in a module. However, this statement should not be used too much.

name attribute

Each module or script file will have a main program or code execution starting point, similar to the main method in Java, C/C++, and C#. When the script is running, the main program will be executed. This main program will be assigned a name when it is executed, but the name is not fixed, for example: when it is executed as a script, the name of the main program is main, and it is done in another script When executed for an imported module, the name of the main program is the name of the module. And each script has its own name attribute, the value of this attribute corresponds to the name of the current main program, the following is a practical example to demonstrate:

# filename:TestMould.py

if __name__ =='__main__':  #The name of the main program when executed as a script is__main__
 print(__name__)print("I was run as the current script")else:print(__name__)print("I was run as a module in another script")

operation result:

*** main***
The program itself is running

If executed as a module in another script, the value of the name attribute will not be main:

# filename:Hello.py

import TestMould  #When executed as an import module of another script, the name of the main program is the name of the module

operation result:

TestMould
I was run as a module in another script

Note: Each module (script) has a name attribute. When its value is 'main', it indicates that the module itself is running, that is, it is running as a script, otherwise it is Is running as an import module. Regardless of whether it is executed as a script or as an imported module, the main program will be executed, but the name is different.

dir() function

dir() is a built-in function (BIF). This function can find the names of all functions, attributes and variables defined in the imported module. Then return as a list of strings:

>>> import sys
>>> dir(sys)['__displayhook__','__doc__','__excepthook__','__name__','__package__','__stderr__', '__stdin
__', '__ stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', 'api_version
', ' argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displa
yhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'e
xec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval','getdefaultencoding','getfilesystemencoding','getprofile','getrecursionlimit','getrefcount','getsizeof','gettrace','getwindowsversion','hexversion','long_info','maxint','maxsize', '
 maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', '
 prefix', 'ps1', 'ps2', 'py3kwarning', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 's
 ettrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions','winver']>>>

If no parameters are passed in the dir function, then the dir() function will list the names of all functions, modules, variables, and attributes defined in the current script:

>>> import sys
>>> def test():...print("test")...>>> a=123>>>dir()['__builtins__','__doc__','__name__','__package__','a','sys','test']>>>

Standard Module

Python itself comes with some standard module libraries, as mentioned before, the specific standard modules will be introduced in a separate article some commonly used (because there are too many).
Some modules are built directly in the parser. Although these are not built-in functions of some languages, they can be used very efficiently, even system-level calls are no problem.
These components will be configured in different forms according to different operating systems. For example, the winreg module will only be provided to Windows systems.
It should be noted that there is a special module sys. sys is the abbreviation of System, which is built into every Python parser. The variables sys.ps1 and sys.ps2 define the strings corresponding to the primary prompt and the secondary prompt:

>>> import sys
>>> sys.ps1  #The main prompt in the interpreter
'>>> '>>> sys.ps2  #The sub prompt in the interpreter (this sub prompt will be displayed when we write a function)
'... '>>> sys.ps1 ='C> '  #Change the main prompt in the interpreter to'C> '
C>print('Yuck!')
Yuck!
C>

Package

A package is a form of managing the Python module namespace, similar to a folder, and there will be many sub-files under this folder, and these sub-files are modules one by one. When we need to use a module in a package, we need to use. As an accessor like other programming languages.
For example, the name of a module is AB, then it represents a submodule B in package A.
Just like when using modules, you don't have to worry about the mutual influence of global variables between different modules, and you don't have to worry about the same module name between different libraries by using the dot module name.
In this way, different authors can provide NumPy modules, or Python graphics libraries.
Suppose you want to design a set of modules (or call it a "package") that uniformly process sound files and data.
There are many different audio file formats (basically distinguished by suffix names, for example: .wav, :file:.aiff, :file:.au,), so you need to have a set of constantly increasing modules for Convert between different formats.
And for these audio data, there are many different operations (such as mixing, adding echo, adding equalizer functions, creating artificial stereo effects), so you also need a set of modules that can't be written to handle these operations.
Here is a possible package structure (in a hierarchical file system):

1. sound/Top-level package
2.  __ init__.py initialize the sound package
3.  formats/File format conversion subpackage
4.    __ init__.py
5.    wavread.py
6.    wavwrite.py
7.    aiffread.py
8.    aiffwrite.py
9.    auread.py
10.    auwrite.py
11....12.  effects/Sound effects sub-package
13.    __ init__.py
14.    echo.py
15.    surround.py
16.    reverse.py
17....18.  filters/filters sub-package
19.    __ init__.py
20.    equalizer.py
21.    vocoder.py
22.    karaoke.py
23....

When importing a package, Python will look for the subdirectories contained in the package according to the directories in sys.path.
The directory will only be considered as a package if it contains a file called init.py, mainly to prevent some vulgar names (such as string) from accidentally affecting the effective modules in the search path.
In the simplest case, just put an empty init.py file. Of course, this file can also contain some initialization code or assign values to all variables (to be introduced later).
Users can only import specific modules in one package at a time. Example:

import sound.effects.echo    #sound is the top-level package, effects is a sub-package, echo is a module under the sub-package

The above code will import a submodule of this form: sound.effects.echo. He must use the full name to access the function or attribute in the module:

sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)

There is another way to import submodules:

from sound.effects import echo

The above code will import a submodule of this form: echo, but he does not need those lengthy prefixes, so he can access the functions or attributes in the module like this:

echo.echofilter(input, output, delay=0.7, atten=4)

Another way is to import a specific function or variable directly:

from sound.effects.echo import echofilter

Similarly, this method will import the submodule: echo, and you can directly use his echofilter() function:

echofilter(input, output, delay=0.7, atten=4)

Note that when using the form from package import item, the corresponding item can be either a submodule (subpackage) in the package, or other names defined in the package, such as functions, classes, or variables.
The import syntax will first treat item as the name of a package definition, if not found, then try to import it according to a module. If you haven't found it yet, congratulations: ImportError was thrown.
Conversely, if you use an import form such as import item.subitem.subsubitem, all except the last item must be a package, and the last item can be a module or a package, but not the name of a class, function, or variable .

**Import from a package: ***

Imagine, what happens if we use from sound.effects import ?
Python will enter the file system, find all the submodules in this package, and import them one by one.
Unfortunately, this method does not work very well on the Windows platform, because Windows is a case-insensitive system.
On this type of platform, no one can guarantee whether a file called ECHO.py is imported as a module echo, Echo or even ECHO.
(For example, Windows 95 is annoying to capitalize the first letter of each file) and DOS's 8+3 naming rules deal with long module names, which makes the problem even more entangled.
In order to solve this problem, I can only bother the package author to provide an accurate package index.
The import statement follows the following rules: if there is a list variable called all in the package definition file init.py, then all the names in this list will be used when using from package import * Import as package content.
As the author of the package, don’t forget to ensure that all is also updated after the package is updated. You said I don’t do this, I don’t use import
, okay, no problem, who makes you the boss. Here is an example, the following code is included in sounds/effects/init.py:

__ all__ =["echo","surround","reverse"]

This means that when you use from sound.effects import *, you will only import these three submodules in the package.
If all is really not defined, when using the syntax from sound.effects import *, any sub-modules in the package sound.effects will not be imported. He just imported the package sound.effects and all the contents defined in it (maybe run the initialization code defined in init.py).
This will import all the names defined in init.py. And he will not destroy all the explicitly specified modules that we imported before this sentence. Look at this part of the code:

import sound.effects.echo
import sound.effects.surround
from sound.effects import*

In this example, before executing from...import, the echo and surround modules in the package sound.effects have been imported into the current namespace. (Of course if all is defined, it will be no problem)
Usually we do not advocate using * this method to import modules, because this method often leads to reduced code readability. However, this does save a lot of key-pressing effort, and some modules are designed to be imported only through specific methods.
Remember, there is never a mistake in using from Package import specific_submodule. In fact, this is also the recommended method. Unless the submodule you want to import may have the same name as the submodules of other packages.
If the package is a sub-package in the structure (such as the package sound in this example), and you want to import a sibling package (a package of the same level), you have to use the import absolute path to import. For example, if the module sound.filters.vocoder wants to use the module echo in the package sound.effects, you have to write from sound.effects import echo.

from.import echo
from..import formats
from..filters import equalizer

Both implicit and explicit relative imports start from the current module. The name of the main module is always "main". The main module of a Python application should always be referenced by an absolute path.
The package also provides an additional attribute path. This is a list of directories. Each of the included directories has init.py for this package. You have to define it before other init.py are executed. This variable can be modified to affect the modules and sub-packages contained in the package.
This function is not commonly used, and is generally used to expand the modules in the package.

Recommended Posts

Python3 module
Python Lesson 37-Module
Python3 built-in module usage
Python3 external module use
Prettytable module of python
matplotlib of python drawing module
Python Faker data forgery module
Python multithreading
Python CookBook
Python FAQ
Python3 dictionary
python (you-get)
Python string
Python basics
Python descriptor
Python basics 2
Python exec
Python notes
Python3 tuple
CentOS + Python3.6+
Python advanced (1)
Python decorator
Python IO
Python multithreading
Python toolchain
Python3 list
Python multitasking-coroutine
Python overview
python introduction
Python analytic
Python basics
07. Python3 functions
Python basics 3
Python multitasking-threads
​Full analysis of Python module knowledge
Python functions
python sys.stdout
python operator
Python entry-3
Centos 7.5 python3.6
Python string
How to view the python module
python queue Queue
Python basics 4
Python basics 5
Python requests module session code example
Python requests module cookie instance analysis
Python learning os module and usage
Error when installing Python module on Ubuntu
python Douban replaces pip to install python module
Python novices learn standard library module naming
Summary of common operations of Python time module
Method of installing django module in python
How does Python handle the json module
How to learn the Python time module
Centos6 install Python2.7.13
Python answers questions
Python basic syntax (1)
Python exit loop
Ubuntu16 upgrade Python3
Centos7 install Python 3.6.