Skip to content
Advertisement

How can I get hold of a function reflectively within in the same module

I need to be able to be able to call a function reflectively that’s defined within the same module e.g

a = getattr('foo_1')
b = a(5)

def foo_1(x) : return x*x

This fails because getattr requires 2 params, but I don’t know what to put for the first param, as there is no enclosing type or other module to import by name. If feel sure that the answer is very simple, but I haven’t found it yet.

(Yes, I know this looks silly – if the function is defined in the same module, why not just call it directly? The reason is that the code is being built dynamically from multiple sources and then run. foo_1 might or might not exist and will anyway be one of many functions following name style foo_<n>. I need to find the ones that do exist, and then call them. This is just a simplified example. I would also appreciate advice on the best way to test whether, say, foo_1 does or does not exist before attempting to call it.)

Advertisement

Answer

Use globals to access the names in your module namespace:

def foo_1():
    print('hi')


globals()['foo_1']()

Result:

hi
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement