473,782 Members | 2,542 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.RunSch edule, 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 7804
ro*********@gma il.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.RunSch edule, 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*********@gma il.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.RunSch edule, 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*********@gma il.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
1682
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
2210
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
1967
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
1201
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 local namespace instead (and inner functions won't exist until the outer function executes) Try using locals()
0
9639
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10311
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10146
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10080
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9942
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7492
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5378
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4043
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3639
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.