getattr from local scope

Fredrik Lundh fredrik at pythonware.com
Mon Apr 24 06:08:14 EDT 2006


rob.haswell at 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>






More information about the Python-list mailing list