Contact at mumbai.academics@gmail.com or 8097636691
Responsive Ads Here

Wednesday, 13 June 2018

Python New module: importlib

Python 3.1 includes the importlib package, a re-implementation of the logic underlying Python’s import statement. importlib is useful for implementors of Python interpreters and to users who wish to write new importers that can participate in the import process. Python 2.7 doesn’t contain the completeimportlib package, but instead has a tiny subset that contains a single function, import_module().
import_module(name, package=None) imports a module. name is a string containing the module or package’s name. It’s possible to do relative imports by providing a string that begins with a . character, such as ..utils.errors. For relative imports, the package argument must be provided and is the name of the package that will be used as the anchor for the relative import. import_module() both inserts the imported module into sys.modules and returns the module object.
Here are some examples:
>>> from importlib import import_module
>>> anydbm = import_module('anydbm')  # Standard absolute import
>>> anydbm
<module 'anydbm' from '/p/python/Lib/anydbm.py'>
>>> # Relative import
>>> file_util = import_module('..file_util', 'distutils.command')
>>> file_util
<module 'distutils.file_util' from '/python/Lib/distutils/file_util.pyc'>
importlib was implemented by Brett Cannon and introduced in Python 3.1

No comments:

Post a Comment