473,326 Members | 2,023 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

getattr from local scope

Hey there

My question is pretty simple - I want to use something like getattr to
grab a symbol from the local scope from a string.

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 I can use eval, but I've always been told that if you're using
eval, you're doing it wrong. Also not using eval limits the scope
damage
that can be caused by any errors in my application which could cause
the
database to be poisoned.

Cheers for any help :-)

-Rob

Apr 23 '06 #1
4 7669
ro*********@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.
Apr 23 '06 #2
Edward Elliott <no****@127.0.0.1> wrote:
ro*********@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()


sys.modules[__name__].__dict__ may be more handily accessed by the
built-in function globals().
Alex
Apr 23 '06 #3
Alex Martelli wrote:
sys.modules[__name__].__dict__ may be more handily accessed by the
built-in function globals().


Well there you go. Glad it's not that awkward.
Apr 23 '06 #4
ro*********@gmail.com wrote:
I know I can use eval, but I've always been told that if you're using
eval, you're doing it wrong. Also not using eval limits the scope damage
that can be caused by any errors in my application which could cause
the database to be poisoned.


a more robust approach is to explicitly add public entry points to a
dictionary, and dispatch via that dictionary:

a simple decorator can be handy for this purpose:

registry = {}

def public(func):
registry[func.__name__] = func

@public
def func1():
print "func1"

@public
def func2():
print "func2"

def func3():
print "internal func3"

registry["func1"]()
registry["func3"]() # this will fail

in pre-decorator versions of python, this can be implemented either
by explicitly registering the entry points:

def func2():
print "func2"
public(func2)

or

def func2():
print "func2"
registry["func2"] = func2

or by using a prefix to make accidental publishing less likely:

def public_func2():
print "func2"

globals()["public_" + funcname]()

and/or by making all the callbacks methods of a class, and use getattr
on an instance of that class.

</F>

Apr 24 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Thomas Rast | last post by:
Hello I've found out about a fundamental problem of attribute lookup, the hard way. asyncore.py uses the following code: class dispatcher: # ... def __getattr__(self, attr):
9
by: Stefan Turalski \(stic\) | last post by:
Hi, I done sth like this: for(int i=0; i<10; i++) {...} and after this local declaration of i variable I try to inicialize int i=0;
3
by: Rotlaus | last post by:
Hello, lets assume i have some classes: class A(object): def __init__(self): b = B() class B(object): def __init__(self):
0
by: Gabriel Genellina | last post by:
En Wed, 20 Aug 2008 05:34:38 -0300, Gabriel Rossetti <gabriel.rossetti@arimaz.comescribi�: Yes, functions are objects, but inner functions aren't attributes of the outer; they live in its...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.