Python __import__() function


As we write python programs we need various other modules to leverage their functions, classes etc. in our current program. We can import those modules at the runtime using the import function. Though you can also import named modules at the beginning of the code, you may need the module temporarily for only few lines of code or you want to make the copy of an object from the module and modify and use it.

Syntax

The syntax of the __import__() function is −

__import__(name, globals=None, locals=None, fromlist=(), level=0)
Where
name - the name of the module you want to import
globals and locals - determines how to interpret name
fromlist - objects or submodules that should be imported by name
level - specifies whether to use absolute or relative imports

In the below example we import the DateTime module and dcreate custom objects with values as needed in the program.

Example

 Live Demo

dttime = __import__('datetime', globals(), locals(), [], 0)
print(dttime.datetime.now())
# Make a copy of dttime
x = dttime.datetime.now()
# Get your custom results
print(x.strftime("%d-%B"))

Output

Running the above code gives us the following result −

2021-01-12 07:38:54.903330
12-January

The use of __import__ is discouraged and you can import the entire module at the beginning of the code for greater efficiency.

Updated on: 25-Jan-2021

279 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements