Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import a package defined by a variable

Tags:

python

I want to do some package import timing tests. For this, I want to define a list of packages:

packages = [ 'random', 'dateutils', ... ]

for package in packages:
    import package

This is of course not working because import tries to import package "package". How can I tell import to import the package pointed to by the variable "package"?

like image 464
blueFast Avatar asked Apr 15 '26 09:04

blueFast


2 Answers

for package in packages:
    package = __import__(package)

Note that if you are importing a module from a package, such as A.B,

__import__('A.B') returns package A, but __import__('A.B', fromlist = [True]) returns module B.

like image 171
unutbu Avatar answered Apr 16 '26 22:04

unutbu


Read the description of "__import__" method in the manual may be helpful for you.

like image 32
rpbear Avatar answered Apr 16 '26 23:04

rpbear



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!