First, what is the module
In order to write maintainable code, many functions are grouped into separate files, so that each file contains relatively few code, and the programming language uses this kind of organizational method. In Python, a. py file is called a module.
Ii. What are the benefits of using modules?
- The greatest benefit is that the maintainability of the code is greatly improved. Second, writing code does not have to start from scratch. When a module is written, it can be referenced elsewhere. Frequently referencing other modules, including Python built-in modules and modules from third parties
- The use of modules also avoids conflicting function names and variable names. Each module has a separate namespace
Three, module classification
- Built-in standard module (also known as standard library) execution help (' modules ') View all Python-included modules list
- Third-party open source modules can be installed via the PIP Install Module name Network
- Custom Modules
Iv. Module Invocation
Import modulefrom Module Import xxfrom module.xx.xx import xx as rename from module.xx.xx import *
Note: Once the module is called, it is equivalent to executing the code in another py file
Custom Modules
This is the simplest, create a. py file, you can call it a module, you can import in another program
Module Lookup Path
found that their own module can only be used in the current path of the program can be imported, a directory and then import their own module on the error said can not find, this is why?
This is related to the import path
Import Sysprint (Sys.path)
Output
[' D:\\python\\14_day_training_camp\\python full stack development intermediate \ \ Second Module \\chapter4-Common module ', ' D:\\python\\14_day_training_camp ', ' D:\\python\\14_day_training_camp\\python full stack development intermediate \ \ Second Module \\chapter4-common Module \\my_proj ', ' d:\\python\\14_day_training_ Camp\\ job \ \ Fifth job \\ATM ', ' D:\\python\\14_day_training_camp\\python full stack Development Intermediate \\ATM program ', ' D:\\python36\\python36.zip ', ' D : \\Python36\\DLLs ', ' d:\\python36\\lib ', ' d:\\python36 ', ' d:\\python36\\lib\\site-packages ', ' d:\\python36\\lib\\ Site-packages\\openpyxl-2.3.3-py3.6.egg ', ' D:\\python36\\lib\\site-packages\\et_xmlfile-1.0.1-py3.6.egg ', ' D:\\ Python36\\lib\\site-packages\\jdcal-1.3-py3.6.egg ', ' D:\\python36\\lib\\site-packages\\file_ Magic-0.3.0-py3.6.egg ', ' d:\\python36\\lib\\site-packages\\win32 ', ' d:\\python36\\lib\\site-packages\\win32\\lib ', ' D:\\python36\\lib\\site-packages\\pythonwin ', ' D:\\Program files\\jetbrains\\pycharm 2018.1.1\\helpers\\ Pycharm_matplotlib_backend ']
The Python interpreter will follow the list order to go to each directory to match the module name you want to import, as long as it matches the module name in a directory, import it immediately, and no longer look back.
Note that the first element of the list represents the current directory, so your own defined module will be imported first in the current directory.
Iv. installation and use of open source modules
- PIP3 Install module name
- Download source installation on official website
Compiled source python setup.py build installation source python setup.py install
Five, Pack (package)
When the module files are more and more, the files need to be classified by different functions
. └──my_proj ├──crm #代码目录 │ ├──admin.py │ ├──apps.py │ ├──models.py │ ├── tests.py │ └──views.py ├──manage.py └──my_proj #配置文件目录 ├──settings.py ├──urls.py └──wsgi.py
Like the above, a folder to manage multiple module files, this folder is called a package
crm/views.py Content
Def sayhi (): print (' Hello world! ') Print (settings. DATABASES)
. └──my_proj ├──crm #代码目录 │ ├──admin.py │ ├──apps.py │ ├──models.py │ ├──tests.py │ └──views.py ├──manage.py └──my_proj #配置文件目录 ├──settings.py ├──urls.py └──wsgi.py
How to implement in- crm/views.py
proj/settings.py
module import?
Direct import words, will error, said to find not module
Call through manage.py
From CRM Import Viewsviews.sayhi ()
Output:
D:\Python\14_day_training_camp\Python full stack development intermediate \ Second Module \chapter4-common module \my_proj{' default ': {' ENGINE ': ' Django.db.backends.sqlite3 ', ' NAME ': ' D:\\python\\14_day_training_camp\\python full stack development intermediate \ \ Second Module \\chapter4-common modules \\my_ Proj\\db.sqlite3 '}}hello world!
Cross-module Import
The directory structure is as follows
According to the above structure, how to implement in the crm/views.py
import proj/settings.py
module?
Direct import words, will error, said to find not module
$ python3 views.pyTraceback (most recent call last): File "views.py", line 2, in <module> from proj import settingsModuleNotFoundError: No module named ‘proj‘
Because the path cannot be found, proj/settings.py is equivalent to the son (settings.py) of the brother (Proj) of Crm/views.py's father (CRM), settings.py is views.py cousin, in views.py can only import the same level Brother module code, or sub-level package module, do not know cousin Cousin's existence. What can I do about it?
The answer is to add an environment variable and add the father-level path to the Sys.path, so the import is equivalent to starting from the father level to find the module.
Adding environment variables in crm/views.py
Base_dir = Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__))) print (Base_dir) sys.path.append (Base_dir) From my_proj import Settingsdef sayhi (): print (' Hello world! ') Print (settings. DATABASES)
Output
D:\Python\14_day_training_camp\Python full stack development intermediate \ Second Module \chapter4-common module \my_proj{' default ': {' ENGINE ': ' Django.db.backends.sqlite3 ', ' NAME ': ' D:\\python\\14_day_training_camp\\python full stack development intermediate \ \ Second Module \\chapter4-common modules \\my_ Proj\\db.sqlite3 '}}
Absolute Import & Relative Import
CD can be used in Linux. Go back to the previous level directory, CD. /.. On the 2 floor, this one. Refers to the relative path, in Python, the import can also be..
For example:
. ├──__init__.py├──crm│ ├──__init__.py│ ├──admin.py│ ├──apps.py│ ├──models.py│ ├──tests.py│ ├──views.py #from. Proj import settings├──manage.py └──proj ├──__init__.py ├──settings.py #from. Import URLs ├──urls. PY └──wsgi.py
views.py Code
From.. Proj import Settingsdef sayhi (): print (' Hello world! ') Print (settings. DATABASES)
The result of the execution is error
Traceback (most recent): File "my_proj/crm/views.py", line 4, in <module> from. Proj import settingssystemerror:parent module ' not loaded, cannot perform relative import
Or someone will see this mistake.
ValueError: attempted relative import beyond top-level package
In fact, the reasons for these two errors are the same: when it comes to relative imports, the folder corresponding to the package must be correctly viewed by the Python interpreter as a package, not as a normal folder. Otherwise, the relative import of a package in Python cannot be achieved by using the nested relationship between packages because it is not considered as a pack.
The folder is considered as a package by the Python interpreter to meet two criteria:
- The __init__.py file must be in the folder, and the file can be empty, but the file must exist.
- You cannot execute a PY file in the folder as a top-level module (that is, it cannot be used as a portal for the main function).
So the solution to this problem is that since you are performing a relative import in the views.py, do not use views.py as an entry procedure, and you can call views.py at the previous level manage.py
. ├──__init__.py├──crm│ ├──__init__.py│ ├──admin.py│ ├──apps.py│ ├──models.py│ ├──tests.py│ ├──views.py #from. Proj import settings├──manage.py #from CRM import views└──proj ├──__init__.py ├──settings.py #from. I mport URLs ├──urls.py └──wsgi.py
It turns out it's still not working, error.
ValueError: attempted relative import beyond top-level package
But after the change to the from ..proj import settings
from . import models
implementation of success, why?
from .. import models
The reason for the error is that this code will see the manage.py layer as the package, but in fact it is not, because the package can not be the top entry code, if you want to do not go wrong, you can only move the manage.py up another layer.
The correct code directory structure is as follows
The execution of manage.py will not be an error.
Note: Although Python supports relative import, it is not recommended to use it frequently in projects where the path relationship between modules is more stringent and improper handling is error-prone.
Getting started with Python: Common modules-modules, Package introduction