Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dynamic import - how to import * from module name from variable?

As discussed here, we can dynamically import a module using string variable.

import importlib
importlib.import_module('os.path')

My question is how to import * from string variable?

Some thing like this not working for now

importlib.import_module('os.path.*')
like image 661
Nam G VU Avatar asked Jun 12 '17 06:06

Nam G VU


People also ask

Can we import * from module in Python?

Import in python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.

How do I import a module dynamically?

To load dynamically a module call import(path) as a function with an argument indicating the specifier (aka path) to a module. const module = await import(path) returns a promise that resolves to an object containing the components of the imported module. } = await import(path);

What is import * in Python?

In Python, you use the import keyword to make code in one module available in another. Imports in Python are important for structuring your code effectively. Using imports properly will make you more productive, allowing you to reuse code while keeping your projects maintainable.


1 Answers

You can do the following trick:

>>> import importlib
>>> globals().update(importlib.import_module('math').__dict__) 
>>> sin
<built-in function sin>

Be warned that makes all names in the module available locally, so it is slightly different than * because it doesn't start with __all__ so for e.g. it will also override __name__, __package__, __loader__, __doc__.

Update:

Here is a more precise and safer version as @mata pointed out in comments:

module = importlib.import_module('math')

globals().update(
    {n: getattr(module, n) for n in module.__all__} if hasattr(module, '__all__') 
    else 
    {k: v for (k, v) in module.__dict__.items() if not k.startswith('_')
})

Special thanks to Nam G VU for helping to make the answer more complete.

like image 87
hurturk Avatar answered Oct 12 '22 06:10

hurturk