Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python __import__() Function



ThePython __import__() function is abuilt-in function used to import a module during runtime. It should be noted that the use of this function is often discouraged as it can change the semantics of the import statement.

In our Python program, we need variousfunctions and classes from othermodules. Though we can also import named modules at the beginning of the code, sometimes, we may need the module temporarily for only a few lines of code. In this situation, we use__import__() function.

Syntax

Following is the syntax of the Python__import__() function −

__import__(name, globals, locals, fromlist, level)

Parameters

The Python__import__() function accepts the following parameters −

  • name − It represents the name of the module we want to import in our program.

  • globals − It specify how to interpret the specified module.

  • locals − It also specify how to interpret the imported module.

  • fromlist − This parameter specifies objects or submodules that we want to import as a list.

  • level − The level 0 represents absolute and a positive number represent the relative level.

Return Value

The Python__import__() function returns the object or module that we specify.

__import__() Function Examples

Practice the following examples to understand the use of__import__() function in Python:

Example: Use of __import__() Function

The following example shows the basic usage of Python __import__() function. Here, we are importing a module named "math" into our program.

#importing the moduleimportingModule = __import__("math")# using sqrt method from the moduleprint(importingModule.sqrt(49))

When we run above program, it produces following result −

7.0

Example: Calling Specific Method of a Module at Runtime Using __import__()

We can also select a specific method from a given module to import into our program. In the code below, we are importing onlysqrt() method fromMath module.

#importing only sqrt method from Math moduleimportingSqrt = getattr(__import__("math"), "sqrt")print("The square root of given number:")print(importingSqrt(121))

Following is an output of the above code −

The square root of given number:11.0

Example: Import a Module with an Alias Using __import__() Function

The code below demonstrates how to import thenumpy module by giving an alias to it.

#importing only numpy modulenp = __import__('numpy', globals(), locals(), [], 0)print("The newly created array:")print(np.array([22, 24, 26, 28, 30, 32]))

Output of the above code is as follows −

The newly created array:[22 24 26 28 30 32]
python_built_in_functions.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp