简体   繁体   中英

Passing package name and function name as variable in python

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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM