文字列を関数にマップする最良の方法を知りたいです。これまでのところ、私は使用できることを知っています:
- globals()[func_string]
- sys.modules[__name__]
- funcs_dictionary["func_string" : func]
コードは次のとおりです。
>>> def foo(arg):
... print "I'm foo: %s" % arg
...
>>> def bar(arg):
... print "I'm bar: %s" % arg
...
>>>
>>> foo
<function foo at 0xb742c7d4>
>>> bar
<function bar at 0xb742c80c>
>>>
globals()[func_string]:
>>> def exec_funcs_globals(funcs_string):
... for func_string in funcs_string:
... func = globals()[func_string]
... func("from globals() %s" % func)
...
>>> exec_funcs_globals(["foo", "bar"])
I'm foo: from globals() <function foo at 0xb742c7d4>
I'm bar: from globals() <function bar at 0xb742c80c>
>>>
sys.modules[__name__]:
>>> import sys
>>>
>>> def exec_funcs_thismodule(funcs_string):
... thismodule = sys.modules[__name__]
... for func_string in funcs_string:
... func = getattr(thismodule, func_string)
... func("from thismodule %s" % func)
...
>>> exec_funcs_thismodule(["foo", "bar"])
I'm foo: from thismodule <function foo at 0xb742c7d4>
I'm bar: from thismodule <function bar at 0xb742c80c>
>>>
funcs_dictionary["func_string" : func]:
>>> funcs = {
... "foo" : foo,
... "bar" : bar
... }
>>>
>>> def exec_funcs_dict(funcs_string):
... for func_string in funcs_string:
... func = funcs[func_string]
... func("from thismodule %s" % func)
...
>>> exec_funcs_dict(["foo", "bar"])
I'm foo: from thismodule <function foo at 0xb742c7d4>
I'm bar: from thismodule <function bar at 0xb742c80c>
もともと、sys.modules[__name__] がモジュールをリロードしてパフォーマンスを低下させるのではないかと心配していました。しかし、上記のコードは関数ポインタが同じであることを示しているように見えるので、心配する必要はないのでしょうか?
オプション 1、2、3 の最適な使用例は何ですか?