getattr from local scope
Edward Elliott
nobody at 127.0.0.1
Sun Apr 23 17:55:53 EDT 2006
rob.haswell at gmail.com wrote:
> Basically my application has a scheduler which stores names of functions
> defined in the "schedule" module in a database, to be run on certain
> days. Every night I call schedule.RunSchedule, which grabs all the rows on
> the database that have to be run now, and I want to call the function
> defined the same module according to that string.
I know that sys.modules[__name__] gives the module object for the current
module. You could do:
m = sys.modules[__name__] # M now current module object
func = m.__dict__ [fs] # func has function named by string fs
func()
If func isn't in the current module, replace __name__ with 'Foo'. Add
try/catch as appropriate in case fs doesn't exist in module M.
If your database stores the function arguments in the same string as the
function name, you'll have to parse them out separately.
I make no claims to this solution being optimal, as it pretty much
stretches my knowledge of Python modules and reflection.
More information about the Python-list
mailing list