Added call_function_by_name

This commit is contained in:
Anton Beloglazov 2012-10-02 10:53:40 +10:00
parent e72a36a6bb
commit a9287cb347
2 changed files with 32 additions and 0 deletions

View File

@ -185,3 +185,27 @@ def init_logging(log_directory, log_file, log_level):
logger.addHandler(handler)
return True
@contract
def call_function_by_name(name, args):
""" Call a function specified by a fully qualified name.
:param name: A fully qualified name of a function.
:type name: str
:param args: A list of positional arguments of the function.
:type args: list
:return: The return value of the function call.
:rtype: *
"""
fragments = name.split('.')
module = '.'.join(fragments[:-1])
fromlist = fragments[-2]
function = fragments[-1]
m = __import__(module, fromlist=fromlist)
return getattr(m, function)(*args)

View File

@ -130,3 +130,11 @@ class Common(TestCase):
assert os.access(log_dir, os.W_OK)
shutil.rmtree(log_dir, True)
def test_call_function_by_name(self):
with MockTransaction:
arg1 = 'a'
arg2 = 'b'
expect(common).func_to_call(arg1, arg2).and_return('res').once()
assert common.call_function_by_name('neat.common.func_to_call',
[arg1, arg2]) == 'res'