Brig
Brig

Reputation: 10321

Check Names pointing to Python Object

How can I get a list of all the names that point to a Python object?

import my_function from example

a = my_function
b = my_function

get_names(my_function)
[a, b]

Edit: The goal is to help find how to monkey patch an object that is loaded in an unknown way.

Upvotes: 0

Views: 42

Answers (2)

balderman
balderman

Reputation: 23815

See below (use globals and make sure you do not return the function itself)

from example import my_function

def get_names(func):
  result = []
  for k,v in globals().items():
    if v == func and k not in str(v).split():
      result.append(k)
  return result



def foo():
  pass

a = my_function
b = my_function
c = foo

print(get_names(my_function))

example.py

def my_function():
  pass

output

['a','b']

Upvotes: 0

Aaron
Aaron

Reputation: 11075

Search the global namespace for objects matching via identity, and report the keys (names).

def my_func():
    pass

a = my_func
b = my_func

def get_names(x):
    for k, v in globals().items():
        if v is x:
            yield k

print(list(get_names(my_func))) #prints ['my_func', 'a', 'b']

Upvotes: 2

Related Questions