3

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"?

blueFast
  • 41,341
  • 63
  • 198
  • 344
  • 1
    possible duplicate of [How can I import a package using __import__() when the package name is only known at runtime?](http://stackoverflow.com/questions/1057843/how-can-i-import-a-package-using-import-when-the-package-name-is-only-know) –  Sep 13 '12 at 12:08

2 Answers2

8
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.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
1

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

rpbear
  • 640
  • 7
  • 15