Can an object inspect the name of the variable it's been assigned to?

前端 未结 7 1518

In Python, is there a way for an instance of an object to see the variable name it\'s assigned to? Take the following for example:

class MyObject(object):
           


        
7条回答
  •  情歌与酒
    2020-11-29 11:58

    Here is a simple function to achieve what you want, assuming you wish to retrieve the name of the variable where the instance is assigned from a method call :

    import inspect
    
    def get_instance_var_name(method_frame, instance):
        parent_frame = method_frame.f_back
        matches = {k: v for k,v in parent_frame.f_globals.items() if v is instance}
        assert len(matches) < 2
    return list(matches.keys())[0] if matches else None
    

    Here is an usage example :

    class Bar:
        def foo(self):
            print(get_instance_var_name(inspect.currentframe(), self))
    
    bar = Bar()
    bar.foo()  # prints 'bar'
    
    def nested():
        bar.foo()
    nested()  # prints 'bar'
    
    Bar().foo()  # prints None
    

提交回复
热议问题