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

前端 未结 7 1532

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:53

    Yes, it is possible*. However, the problem is more difficult than it seems upon first glance:

    • There may be multiple names assigned to the same object.
    • There may be no names at all.
    • The same name(s) may refer to some other object(s) in a different namespace.

    Regardless, knowing how to find the names of an object can sometimes be useful for debugging purposes - and here is how to do it:

    import gc, inspect
    
    def find_names(obj):
        frame = inspect.currentframe()
        for frame in iter(lambda: frame.f_back, None):
            frame.f_locals
        obj_names = []
        for referrer in gc.get_referrers(obj):
            if isinstance(referrer, dict):
                for k, v in referrer.items():
                    if v is obj:
                        obj_names.append(k)
        return obj_names
    

    If you're ever tempted to base logic around the names of your variables, pause for a moment and consider if redesign/refactor of code could solve the problem. The need to recover an object's name from the object itself usually means that underlying data structures in your program need a rethink.

    * at least in Cpython

提交回复
热议问题