access to the namespace of a function from within its invocation

Poor Yorick org.python.python-list at pooryorick.com
Fri Jul 13 05:13:47 CEST 2007


In the example below, the attribute "data" is added to a function 
object.  "me" can be used to get the function when it is invoked using 
an identifier that matches the "co_name" attribute of function's code 
object.  Can anyone conjure an example of accessing fun2.data from 
without prior knowledge of the value of fun2.f_code.co_name?

###code begin###
#!/bin/python

import sys

def me():
    t = sys._getframe(0)
    return t.f_back.f_globals[t.f_back.f_code.co_name]
def fun1():
    m = me
    print me().data
    
def makefun () :
    def tmpfunc():
        print 'need something like me().data'
    return tmpfunc

fun1.s = fun1
fun1.data=['one', 'two', 'three']
fun1()
fun2 = makefun()
fun2.data=['four', 'five','six']
fun2()

###code end###

-- 
Poor Yorick





More information about the Python-list mailing list