- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How do you dynamically add Python modules to a package while your programming is running?
To dynamically import Python modules, you can use the importlib package's import_module(moduleName) function. You need to have moduleName as a string. For example,
>>> from importlib import import_module >>> moduleName = "os" >>> globals()[moduleName] = import_module(moduleName)
If you want to dynamically import a list of modules, you can even call this from a for loop. For example,
>>> import importlib >>> modnames = ["os", "sys", "math"] >>> for lib in modnames: ... globals()[lib] = importlib.import_module(lib)
The globals() call returns a dict. We can set the lib key for each library as the object returned to us on import of a module.
If you've imported a package and now want to dynamically import one of its module, you can still use the same function and get the expected result. The module you want to import should have its full name and not just the module name. For example,
>>> import importlib >>> pack = 'datetime' >>> mod = 'date' >>> globals()[pack] = importlib.import_module(pack) >>> globals()[pack + '.' + mod] = importlib.import_module(pack + '.' + mod)
- Related Articles
- Is there a need to import Java.lang package while running Java programs?
- How to find which Python modules are being imported from a package?
- How to manipulate figures while a script is running in Python Matplotlib?
- Loading JavaScript modules dynamically
- How do Python modules work?
- Do I need to import the Java.lang package anytime during running a program?
- while and do-while in Dart Programming
- Why Your Computer is Running Slow and How You Can Fix It?
- How do we use easy_install to install Python modules?
- How to add a button dynamically in android?
- How do I create a namespace package in Python?
- How do I get IntelliJ to recognize common Python modules?
- How to do CGI programming in Python?
- How to emulate a do-while loop in Python?
- How to use the Time package in Lua programming?

Advertisements