Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dynamic function names

Tags:

python

factory

I'm looking for a better way to call functions based on a variable in Python vs using if/else statements like below. Each status code has a corresponding function

if status == 'CONNECT':
    return connect(*args, **kwargs)
elif status == 'RAWFEED':
    return rawfeed(*args, **kwargs)
elif status == 'RAWCONFIG':
    return rawconfig(*args, **kwargs)
elif status == 'TESTFEED':
    return testfeed(*args, **kwargs)
...

I assume this will require some sort of factory function but unsure as to the syntax

like image 599
drjeep Avatar asked Mar 25 '09 10:03

drjeep


1 Answers

you might find getattr useful, I guess

import module
getattr(module, status.lower())(*args, **kwargs)
like image 61
SilentGhost Avatar answered Sep 21 '22 14:09

SilentGhost