#When writing code, you may need certain modules. So we import these modules using a single line of code in Python.
But what if we only know the name of the required module at runtime? How do we import that module? We can use Python's built-in __import__()
function. It also helps to import modules at runtime.
Syntax:
__import__(name, globals, locals, fromlist, level)
Parameters:
##name: The name of the module to be imported
globals and
locals: Interpretation names (global variables and local variables)
formlist: Object or child to be imported Modules (as a list)
level: Specifies whether to use absolute or relative imports. The default value is -1 (absolute and relative).
Example 1:
# 导入numpy np = __import__('numpy', globals(), locals(), [], 0) # array from numpy a = np.array([1, 2, 3]) # prints the type print(type(a))
<class 'numpy.ndarray'>
Example 2:
np = __import__('numpy', globals(), locals(), ['complex', 'array'], 0) comp = np.complex arr = np.array
__import__() is not necessary in daily Python programming. Its direct use is rare. But sometimes, this feature comes in handy when you need to import a module at runtime.
Python Tutorial"
This article is an introduction to the usage of import in python. I hope it will be helpful to friends in need!The above is the detailed content of Import usage in python (code example). For more information, please follow other related articles on the PHP Chinese website!