Howto MACRO in python ?

Sean Ross sross at connectmail.carleton.ca
Tue Aug 12 18:25:25 EDT 2003


"Bengt Richter" <bokr at oz.net> wrote in message
news:bhbhsm$2vv$0 at 216.39.172.122...
> maybe there ought to be a magic __self__ in the local namespace of a
function?

I've played with trying to get something like that, but I haven't got
anything reliable[1]. So far I have a very simple function that retrieves
the calling function object:

import inspect

class ThisResolutionError(Exception): pass

def this():
    fname = inspect.currentframe(1).f_code.co_name
    frameno = 2
    func = None
    while func is None:
        try:
            func = inspect.currentframe(frameno).f_locals.get(fname, None)
            frameno += 1
        except ValueError:
            # reached end of call stack
            raise ThisResolutionError, "could not resolve %s" % fname
    return func


So, when it works (which is not always), you can do things like:

def f():
    "f's doc string"
    __self__ = this()
    print __self__.__name__
    print __self__.__doc__
    print __self__.__dict__

    def g():
         __self__ = this()
         print "called nested function %s" % __self__.__name__
    g()


f.f_attr = "function attribute"
f()

-------------------output ----------------------
f
f's doc string
{'f_attr': 'function attribute'}
called nested function g



I would be interested to see something more general - something that could
be called inside of any namespace (at the module, class, method, or function
level) which you could then (atleast) query and (possibly) modify. Why would
I want to do that? Fun, mostly. I like the idea of being able to query any
object while being inside the object.

+1  __self__

Sean


[1] this() will not work in methods, and there can be issues if you put it
in nested functions

#
# you can do this (if you want)
#
def f():
    __self__ = this()
    def g():
         print "called nested function g"
    __self__.g  = g

f()
f.g()

----------------------
called nested function g

#
# but not this (the reason for which should be obvious)
#
def f():
    __self__ = this()
    def g():
         __self__ = this()
         print "called nested function %s" % __self__.__name__
    __self__.g  = g

f()
f.g()

-------------------------
ThisResolutionError: could not resolve g







More information about the Python-list mailing list