cookbook_ modules and packages

A module package are organized into a hierarchy

Just make sure that each directory are defined in __init__.py can be.

2 precise control of the introduction of all symbols

When a user uses from module import * statement, we hope symbols imported from the module or package precise control.

A variable defined in the module __all__, lists the symbols used to display names may be derived.

__all__ = ["spam","grok"]

 

3 using relative introduced package name submodule

mypackage/
  __init__.py
  A/
    __init__.py
    spam.py
    grok.py
  B/
    __init__.py
    bar.py
    
 #spam.py
 from . import grok
 from ..B import bar

Use this method to import the bag module, it can be a good hard-coded to reduce the import module, if you use absolute name of the import, if the top of the file name change will import all the problems.

ps.

When a script executes import errors   python3 -m mypackage

 

The module 4 into a plurality of files

In the case of use without destroying the structure of a module into a plurality of modules

The first module into the package, introducing the submodules __init__.py file in the package.

 

5 Let the code in each directory import under the unified namespace

foo_package/
  spam/
    blah.py
bar_package/
  spam/
    grok.py
    
import sys
sys.path.extend(["foo_package","bar_package"])
import spam.blah
import spam.grok

In both directories spam as a common namespace, pay attention to these two directories are not __init__.py file.

 

6 reload module

Development environments, try not to use the production environment

import imp
import math
imp.reload(math)

 

7 zip file or directory so that the script can be run to become

MyApplication / 
  spam.py 
  bar.py 
  grok.py 
  __main__ .py 
  
  Python MyApplication 
  
  If you include __main__.py file, you can __main__.py in the method as a script to run, run

 

8 reads the data file in the package

mypackage /
   the __init__ .py 
  somedata.dat 
  spam.py is found 
  
Import pkgutil 
Data = pkgutil.get_data ( __PACKAGE__ , " somedata.dat " ) 

# Data byte string will be a
 

9 added to the directory in sys.path

Three solutions, the first is to add the use of PYTHONPATH environment variable.

env PYTHONPATH = /some/dir:/other/dir python3

 

The second is by creating .pth file, the file on site_packages python's .pth

#mtapplication
/some/dir
/other/dir

The third is hard-coded into the code

import sys
sys.path.insert(0,"/some/dir")
sys.path.insert(0,"/other/dir")

 

10 string name given import module

import importlib
math = importlib.import_module("math")

 

Guess you like

Origin www.cnblogs.com/jiaojianglong/p/11260225.html