How to import a module in Python with importlib.import_module
For relative imports you have to:
- a) use relative name
b) provide anchor explicitly
importlib.import_module('.c', 'a.b')
importlib.import_module('a.b.c')
How to use from x import y using importlib in Python
I don't think you can load methods directly, since this method just loads modules. A module is loaded with import module
and i defined as "A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. " (check documentation). from x import y
does also do the import module
but sets another namespace (see discussion here). What you can do is load your module and then set your namespace manually afterwards, this is what the from x import y syntax
does. You can load a module with the path (in this example i want to load read_csv
from pandas):
importlib.import_module(".io.parsers", "pandas")
(check the path with print(inspect.getmodule(read_csv).__name__)
)Also a solution like jottbe mentioned in the commentary would be possible
How to dynamically import_module from a relative path with python importlib
After some more reading, turn out à solution was staring me right in the face.
Instead of trying to do funny things with importlib you can use getattr
def find_my_class(class_name):
from .. import models as configuration_models
module = getattr(configuration_models, f"{class_name.lower()}s")
return getattr(module, class_name)
How to load python-Files dynamcially with importlib?
In the second example you are running through all members of a module, it is more a brute force approach.
The first example(second also), you can not find what you want. Test for a None if not found or an error during the instantiation.
You can also use import_module direct from importlib. This way you can use getattr to return what you want from the module and return None if an AttributeError is thrown.
You can use this method to return modules, variables, anything that is defined into a module.
import importlib
def get_from_module(module, attr_name):
module = importlib.import_module(module)
try:
return getattr(module, attr_name)
except AttributeError:
return None
klass = get_from_module("plugins." + modulename, classname)
if klass is not None:
instance = klass()
This method is available on my project, cartola, that has some lightweight util methods that I use in multiple projects. It is available at pypi, feel free to import get_from_module or get_from_string from the config module.See:
- https://github.com/candango/cartola/blob/develop/cartola/config.py
- https://pypi.org/project/cartola/
Can't import module with importlib.import_module
EDIT: I had tested the earlier code in console and it worked. However, I have modified the code again. I kept the bsddb
module directly in D drive
and changed the code again to:
import os
os.chdir("D:\\")
import importlib
m = importlib.import_module("bsddb.db")
print len(dir(m))
print dir(m)
This results in 319
and the list of functions and variables
exponsed by the module. It seems you may need to import module using the dot (.) notation
like above. How to do from module import * using importlib?
To emulate from X import *
you must import the module and then merge the appropriate names into the global namespace.
# get a handle on the module
mdl = importlib.import_module('X')
# is there an __all__? if so respect it
if "__all__" in mdl.__dict__:
names = mdl.__dict__["__all__"]
else:
# otherwise we import all names that don't begin with _
names = [x for x in mdl.__dict__ if not x.startswith("_")]
# now drag them in
globals().update({k: getattr(mdl, k) for k in names})
How do I dynamically import a module similar to the import X from Y syntax in Python?
You almost got it, except that the second argument to import_module
is the package name, not the attribute you want. When you want a attribute from a module, you must run the code for the entire module first, since python has no way to predict which lines will have side effects ahead of time.
So first you import the module:
X = importlib.import_module('X')
Then you need to get the attribute from the module:Y = getattr(module, 'Y')
Of course you probably don't want to create the temprorary variable X
, so you can doY = getattr(importlib.import_module('X'), 'Y')
Related Topics
How to Read a Response from Python Requests
Does Python Evaluate If's Conditions Lazily
Overflowerror: (34, 'Result Too Large')
How to Include Image Files in Django Templates
Disable Console Messages in Flask Server
How to Convert a Python List into a C Array by Using Ctypes
Break the Function After Certain Time
Python, Default Keyword Arguments After Variable Length Positional Arguments
How to Set Opacity of Background Colour of Graph with Matplotlib
Is There a Simple Process-Based Parallel Map for Python
Python Element-Wise Tuple Operations Like Sum
First Python List Index Greater Than X
_Getattr_ for Static/Class Variables
Selenium Webdriver in Python - Files Download Directory Change in Chrome Preferences
Display Realtime Output of a Subprocess in a Tkinter Widget
Multiprocessing.Pool Makes Numpy Matrix Multiplication Slower