Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to `from x import *` when x is a string

I am making a program where a user can save a file, load it back, and name the file the way they want.

How can I dynamically import all attributes of that module?

E.g. something like the pseudocode below:

module_name = input()
from module_name import *

Assume module_name ends with ".py".
I am using python 3.5.

like image 421
Penguin Game Zone Avatar asked Dec 09 '25 14:12

Penguin Game Zone


1 Answers

This sounds like a terrible idea, but here is an example of loading math module and using some of its functions.

import importlib

my_module = importlib.import_module('math')    
globals().update(my_module.__dict__)

print(globals())
print(sin(pi/2))

(Code improvements by jmd_dk)


It sounds like a bad idea because from x import * will import everything and potentially overwrite local attributes.

Additionally, there are most likely more clear ways to achieve your goals by using a dictionary.

like image 79
user Avatar answered Dec 11 '25 10:12

user



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!