python bag module references and carded

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/DD_PP_JJ/article/details/102766918

Introduction: In view some of the code works, always will find something like:

from .util import utils
from . import datasets

Such statements referencing, which made me more confused, so take advantage of this opportunity to spend some time, a good tidy-related knowledge

1. python package mechanism

- 包
- 模块
- 框架: 如何组织包和模块

python provides the concept of packages, there is a hierarchical file directory structure for managing a plurality of modules source files.

  • Package is the folder, this has __init__.py file folder, and the folder may include other modules

  • A plurality of modules associated with a package, in order to maintain and use, at the same time can be limited to avoid conflicts namespace.

  • Importing a package in time, we will first call this package __init__.py file

Seated problems: from small to large

  • Statement
  • Def function
  • Class class
  • Module module, physically one file python
  • Package bag, physically a folder, the package may contain modules and packages

Packages and action module:

  • Write good wheels, tools, for use other modules

  • Effectively break down the program, to facilitate the management and maintenance of the code

  • Named prevent the problem repeat the same module (module1.name, module2.name)

– from bilibili https://www.bilibili.com/video/av65157512?p=2

Package information basic module and

  • Packages and module name
    • __name__
    • __package__
  • Storage location
    • __file__
  • View the contents of the package and modules
    • dir (os)
    • __dict__

Import package / module by:

  • General Import:

    • import M
      • Directly into the same directory import M
      • Different level directory using dot syntax import pkg1.pkg2.M
    • import M1, M2
    • import M as m
    • from A import B as b, C as c
      • A range is greater than B, C
        • Range: Package> Module> Resources
      • B, C this part as simple as possible
        • Right: from A.A1 import aa
        • Error: from A import A1.aa
    • from module import *
      • The module will then go to the corresponding python files to find __all__the contents of the corresponding variable
    • from 包 import *
      • Then the package will go to the corresponding __init__.pyfile to find the __all__corresponding variable content
  • note:

    • In use, the subject should be introduced into the module, rather than the package

    • If a package is introduced, not import any default module

    • solution:

      • In this package __init__.pyimport all the modules required

      • In the package from / import folder modules / sub-packet form introduced

        • from p1 import Tool1 as t1, Tool2 as t2
        • from p1.sub_p import sub_xx
      • from module import name form of import resources

        • from other import num
  • Encountered no module named xxx

    •   import sys
        sys.path.append('rc:\Desktop\xxx_dir')
        import xxx
        # 比较强硬的解决方法
      
  • Module search order:

    • Built> Custom> sys.path

2. python module relative references

Many times you'll meet the following error:

ValueError: attempted relative import beyond top-level package

This is usually due to the use of relative references and emerging issues.

We need to be clear:

  1. Relative references are not relative to the file structure! !
  2. With respect to the relative reference is__name__

for example:

- rootdir
  - subdir1
    - __init__.py
  	- subfile1.py
  - subdir2 
    - __init__.py
    - subfile2.py
- test.py

test.py call content subfile1.py of:

def print_mod1():
    print('__name__: {}'.format(__name__))
    print('__package__: {}'.format(__package__))
    print('Import Successfully!')

The output is:

__name__: subdir1.subfile1
__package__: subfile1
Import Successfully!

So this is the relative position with respect to __name__variables, such as:

A point: .on behalf of the current is subdir1

Point two: ..does not exist, the error will beyond top-level package, where top-level package is also very easy to understand, and that is the current subdir1.

You can view more content: https://www.cnblogs.com/jay54520/p/8438228.html

3. Examples

Directory structure is as follows:

[Image dump the chain fails, the source station may have security chain mechanism, it is recommended to save the picture down uploaded directly (img-MxGWGhqT-1572158854183) (assets / 1572056109473.png)]

  1. model folder:

__init__.py · Document reads as follows:

print('-'*5,"init for model folder",'-'*5)

models.pyDocument reads as follows:

def mm():
    print("this is rootpkg/model/models/model")
    print('__name__: {}'.format(__name__))
    print('__package__: {}'.format(__package__))
  1. src folder:

__init__.py · Document reads as follows:

print('-'*5,"init for src folder",'-'*5)

source.pyDocument reads as follows:

def ss():
    print("this is rootpkg/src/source/src")
    print('__name__: {}'.format(__name__))
    print('__package__: {}'.format(__package__))
  1. RootPkg folder:

__init__.py · Document reads as follows:

print('-'*5,"init for rootpkg folder",'-'*5)

main.pyDocument reads as follows:

from model import models
from src import source
from 模块/文件夹 import 具体某个python文件名

source.ss()
models.mm()
  1. Results are as follows:

    ----- init for model folder -----  
    ----- init for src folder ----- 
    # 这两个是在import模块的时候执行的__init__.py文件
    this is rootpkg/src/source/src
    __name__: src.source
    __package__: src
    this is rootpkg/model/models/model
    __name__: model.models
    __package__: model
    

    After the run there will be complete __pycache__folders

    [Image dump the chain fails, the source station may have security chain mechanism, it is recommended to save the picture down uploaded directly (img-sBm0xUjp-1572158854184) (assets / 1572056618738.png)]

Run successfully, but the best practices Tommy-Yu did not go straight through that part, you can look at the first reference of the blog, if anyone can run through, welcome to contact me. (Ps: personally I feel this blog is not said very clearly, the actual operation does go wrong)


reference

Guess you like

Origin blog.csdn.net/DD_PP_JJ/article/details/102766918
Bag