With this code I want to get "main, file" and "abc", but I get ModelBase, Model etc... I don't know what I can do. I define abc in b.py so i think it should execute in the global scope of b.py.

Module model.py:

class ModelBase(type):
    def __new__(cls,name,bases,attrs):
         module = attrs.pop('__module__');
         super_new = super(ModelBase,cls).__new__
         def test(cls):
             # want to print and references globals from Module b
             gl = globals()
             for i in gl:
                  print i
        new_class = super_new(cls,name,bases,{'__module__':module,'test':test})
        return new_class
class Model(object):
    __metaclass__ = ModelBase

Module b.py:

from model import *
class abc(Model):
    pass
tt = t();
tt.test();
有帮助吗?

解决方案

You can find the caller's globals by inspecting the call stack. However, pay attention to the remark in the docs of sys._getframe:

CPython implementation detail: This function should be used for internal and specialized purposes only. It is not guaranteed to exist in all implementations of Python.

Anyway, the code you need to get the globals of the immediate caller is

sys._getframe(1).f_globals
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top