0

Folks, I would like to import python files, and functions dynamically. The modulenames should be passed to a function like so:

def scrape(url, foo):
    modulename = url['modulename']
    import modulename
    modulename.modulename(url, foo)

This is erroring out with:

ImportError: No module named modulename

So how can we get python to use 'modulename' as a variable?

Thanks!

Cmag
  • 14,946
  • 25
  • 89
  • 140

2 Answers2

5

You can use importlib.import_module():

def scrape(url, foo):
    import importlib
    modulename = importlib.import_module(url["modulename"])
    modulename.modulename(url, foo)
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • great, now... its not translating the dynamic function name. how do i get around that? – Cmag Nov 14 '13 at 16:43
1

You can also use

module = __import__('module_name')

Example:

module = __import__('math')
print module.sqrt(4)
>> 2

Or, if you want to use a dynamic method name as well

module = __import__('math')
method =  getattr(module, 'sqrt')
method(4)
>> 2
Steinar Lima
  • 7,644
  • 2
  • 39
  • 40