
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
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.
- Related Articles
- Python zip() Function
- Intersection() function Python
- gcd() function Python
- Python - fmod() function
- Python format() function
- Python frexp() Function
- Python fsum() function
- Python - int() function
- How can a Python function return a function?
- Iterator function in Python
- Calendar function in Python
- Function Decorators in Python?
- Function Annotations in Python
- vars() function in Python
- id() function in Python

Advertisements