1

Importing a module with a local name is easy with the import statement:

import numpy as np

I believe np here is referred to as the "local name" but I could be confused.

I can't work out how to use the importlib module to do the same thing. importlib.import_module() doesn't take an option for the local name as far as I can tell. Any suggestions?

Dave Kielpinski
  • 984
  • 1
  • 6
  • 19

2 Answers2

5

import_module just returns the module; it doesn't assign it to a name at all. You can just assign it to a variable yourself:

short_name = importlib.import_module('really_long_module_name')
BrenBarn
  • 228,001
  • 34
  • 392
  • 371
1

Just use:

np = importlib.import_module('numpy')

importlib.import_module returns the module object it got for you, and doesn't, per se, bind any name in the current scope.

So, you do your own binding in the usual way -- by assignment! -- and it's entirely up to you how you want to name the variable you're assigning to:-)

Alex Martelli
  • 811,175
  • 162
  • 1,198
  • 1,373