Can I get a list of variables that reference another in Python 2.7?

Imagine that I have:

X = [0,1] Y = X Z = Y 

Is there a function like referenced_by (X) that returns something like ['Y', 'Z'] ? And a function like point_to (Y) that returns 'X' ?

I know that there is to check if the objects are the same, I just would like to get a quick way to get the names.

+4
source share
1 answer

Yes and no. You can get a list of global variables:

 for name, val in globals().items(): if val is obj: yield name 

You can also get a list of local variables:

 for name, val in locals().items(): if val is obj: yield name 

However, in doing so, you will skip all variables in different contexts than local for your function or global for the module. You can find variables in call contexts using frame magic, but you cannot find anything global for other modules, for example.

What would you use for this, I do not know.

You will also not find any attributes that refer to the object, but the attributes are not variables, so this may be OK.

You can get all the objects that reference your object. And this will include global and local residents for all functions. But you cannot get the name of the variables in this case. You can do

 >>> import gc >>> gc.get_referrers(obj) 

Get a list of all objects referencing an obj object. Once again, this is pretty useless. :-)

If you need names, you can search for keys in cases where the referrer is a dictionary or a stack frame:

 import gc import types def find_ref_names(obj): for ref in gc.get_referrers(obj): if isinstance(ref, types.FrameType): look_in = [ref.f_locals, ref.f_globals] elif isinstance(ref, dict): look_in = [ref] else: continue for d in look_in: for k, v in d.items(): if v is obj: yield k def main(): a = "heybaberiba" b = a c = b print list(find_ref_names(b)) if __name__ == '__main__': main() 

This will print:

 ['a', 'c', 'b', 'obj'] 

But since you donโ€™t know in what context the variables a , b , c and obj defined, this is again pretty useless. As an example, move the definition of a to the module level and get this result:

 ['c', 'b', 'a', 'obj', 'a', 'a'] 

Where one of these a is global and the others are copies to local contexts.

Regarding your second question:

And a function like point_to (Y) that returns "X"?

Same. Both X and Y are just names pointing to the same object, in this case a list. X is no different from Y , and Y does not indicate X Y indicates [0,1] , as well as X

+2
source

Source: https://habr.com/ru/post/1490867/


All Articles