- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
To Continue Learning Please Login
Login with Google