1

I have a function defined in file f1.py as:

def fn1():
 return 1

def fn2():
 return 2

For learning exercise I am trying the following, which works:

import f1
from f1 import fn1, fn2

But the following approach doesn't work:

pkgName = 'f1'
fnName = 'fn1'
from pkgName import fnName

How can I pass package name and function name as variable?

blhsing
  • 91,368
  • 6
  • 71
  • 106
Zanam
  • 4,607
  • 13
  • 67
  • 143
  • Does this answer your question? [How to import a module given its name as string?](https://stackoverflow.com/questions/301134/how-to-import-a-module-given-its-name-as-string) – Alexander Santos Jan 03 '20 at 17:23
  • I am not sure as I dont know how to implement the syntax for function call – Zanam Jan 03 '20 at 17:25

1 Answers1

1

You can use the __import__ function to import the module first, and then access the function as an attribute of the module object with getattr:

module_name = 'f1'
function_name = 'fn1'
fn = getattr(__import__(module_name, fromlist=[function_name]), function_name)
fn()
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • This however doesn't work if my module_name = 'loc1.loc2.f1'. I know this is a bit tangential but I don't want to just start a new thread for this. – Zanam Jan 03 '20 at 17:37