I have a python module which expected to expose an function with configurable name.
module.py looks like this:
def _actual_func():
print "do the actual work"
INTERFACE_NAME = _load_interface_name_from_conf()
if INTERFACE_NAME == 'foo':
def foo():
_actual_func()
elif INTERFACE_NAME == 'bar':
def bar():
_actual_func()
elif INTERFACE_NAME == 'baz':
def baz():
_actual_func()
The client uses my module like this:
import module
# call the interface function
FUNCTION_NAME_TO_CALL = _load_form_client_conf() # configured to equal INTERFACE_NAME
getattr(module, FUNCTION_NAME_TO_CALL)()
The problem is the code can only work when INTERFACE_NAME
equals 'foo'
, 'bar'
or 'baz'
. How can I rewrite my code so that I can configure the INTERFACE_NAME
to any string value?
Use setattr
. You will need sys
to get the module corresponding to your own module:
import sys
def _actual_func():
print("do the actual work")
INTERFACE_NAME = _load_interface_name_from_conf()
_thismodule = sys.modules[__name__]
setattr(_thismodule, INTERFACE_NAME, _actual_func)
I think you can do simpler by eval() function.
def foo():
pass
def bar():
pass
def call_func(name):
eval(name + "()")
call_func("foo")
call_func("bar")
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.