Create... Under each folder __init__.py file , This file will be executed before importing the specific modules under this package . It can define some contents related to modules . Like publishing : The following code only imports spam and grok. If the from module import * All modules that do not begin with an underscore will be imported . But if defined __all__ Only the listed modules will be imported , If you define an empty list , No modules will be imported .
def spam():
pass
def grok():
pass
age = 30
# Only export 'spam' and 'grok'
__all__ = [ 'spam', 'grok']
Reload , This method is not recommended for use in production environments .
import importlib
from chapter10 import module_split
importlib. reload( module_split)
Through the string import module
req = importlib. import_module( 'requests')
res = req. get( 'http://www.python.org')
import importlib
import sys
from collections import defaultdict
_post_import_hooks = defaultdict( list)
class PostImportFinder:
def __init__( self):
self. _skip = set()
def find_module( self, full_name, path = None):
if full_name in self. _skip:
return None
self. _skip. add( full_name)
return PostImportLoader( self)
class PostImportLoader:
def __init__( self, finder):
self. _finder = finder
def load_module( self, full_name):
importlib. import_module( full_name)
module = sys. modules[ full_name]
for func in _post_import_hooks[ full_name]:
func( module)
self. _finder. _skip. remove( full_name)
return module
def imported_action( full_name):
def decorate( func):
if full_name in sys. modules:
func( sys. modules[ full_name])
else:
_post_import_hooks[ full_name]. append( func)
return func
return decorate
sys. meta_path. insert( 0, PostImportFinder())
@ imported_action( 'threading')
def warn_threads( mod):
print( 'Call Threads.')
Add decorators to existing function definitions ,imported_action The decorator is used to register the processor functions activated during import . This decorator is used to inspect sys.modules, To see if the module has been loaded . If it is , The processor is immediately called , Add to _post_improts_hooks A list of dictionaries . A module can register multiple processors ,_post_import_hooks Is used to collect all the processor objects .
from functools import wraps
from chapter10. modify_module import imported_action
def logged( func):
@ wraps( func)
def wrapper( * args, * * kwargs):
print( f'Calling { func. __name__} ,args: { args} ,kwargs: { kwargs} ')
return func( * args, * * kwargs)
return wrapper
@ imported_action( 'math')
def add_logging( mod):
mod. cos = logged( mod. cos)
mod. sin = logged( mod. sin)
import math
print( f'math.sin(2) = { math. sin( 2)} ')
import pkgutil
data = pkgutil. get_data( __package__, 'test_data.dat') # The first function can use the package name directly .
This function is similar to dynamically adding libraries to path Under the path .site-package The directory is the directory where the third-party packages and modules are installed . If you install the code manually , The code will be installed in site-package Under the table of contents . To configure path Of pth The file must be placed in site-packages in , But the configured path can be in any desired directory on the system .
import sys
print( f'sys path: { sys. path} ')
import sys
sys. path. insert( 0, '/test/dir')
sys. path. insert( 0, '/test/dir')
import sys
from os import path
file_path = path. abspath( path. dirname( __file__))
sys. path. insert( 0, path. join( file_path, 'test'))
print( f'sys path: { sys. path} ')
This function is similar to java Inside maven Private service function . Upload module for other applications dependency.
#step1: To write setup.py file
from distutils. core import setup
setup( name = 'projectname',
version = '1.0',
author = 'Your Name',
author_email = '[email protected]',
url = 'http://www.you.com/projectname',
packages =[ 'projectname', 'projectname.utils'],
)
#setp2: establish MANIFEST.INF file
include *. txt
recursive - include examples *
recursive - include Doc *
#setp3: Execute command release
python3 setup. py sdist