考虑以下代码:
GLOBAL_VARIABLE = 1
def someFunction():
    nonLocalVariable = 2
    def anotherFunction():
        localVariable = 3
        class LocalClass(object):
            __metaclass__ = MyMetaClass
            __customCode = """
                    GLOBAL_VARIABLE + nonLocalVariable + localVariable
                """
    anotherFunction()
someFunction()
我是 的实现者MyMetaClass,这是一个基于__customCode属性内容为类生成方法的元类。__customCode
可以包含 Python 表达式,所以我想确保在中提到的变量名__customCode指的是与在普通 Python 方法中定义的相同变量名相同的对象。
当元类被调用时,它会收到一个包含类内容的字典,这意味着它知道关于__customCode,但这并没有多大帮助。如果您使用inspect.currentframe(1),您将获得语句正在执行的堆栈帧,class
也就是说anotherFunction()。该堆栈框架具有一个.f_locals属性(包含localVariable)和一个.f_globals
属性(包含GLOBAL_VARIABLE,除其他外),但这两者并不能说明整个故事。
给定的堆栈框架anotherFunction()(或我可以从 的实现中获取的任何其他内容MyMetaClass),我如何才能发现所在的名称空间nonLocalVariable以及嵌套在全局和本地名称空间之间的任何其他名称空间?
我目前正在使用 Python 2.7,但如果 Python 3.x 中的答案不同,那也很高兴知道。