In article <[email protected]>, William <[email protected]> wrote:
> I have a question. Suppose I do the following: > > def myfunc(a,b): > return a+b > > myfunc2=myfunc > > is there anyway to find all of the references to myfunc? That is, can I find > out all of the functions that may be aliased to myfunc? The general idea is to search the appropriate namespaces and check for object identity, so something like: >>> def myfunc(a,b): ... return a+b ... >>> myfunc2 = myfunc >>> >>> name = None >>> namespace = globals() >>> >>> for name in namespace: ... if namespace[name] is myfunc: ... print " %s = %s" % (name, namespace[name]) ... myfunc = <function myfunc at 0xc2670> myfunc2 = <function myfunc at 0xc2670> > second question: > > class MyClass(object): > def __init__(a,b): > self.a=a > self.b=b > def myfunc(self): > return self.a+self.b > > myclass=MyClass(3,4) > myclass.myfunc2=myclass.myfunc > > Is there any way to find all the references to myclass.myfunc--in this case, > myclass.myfunc2? This is a little trickier since the object you are searching for is a bound method; while it might seem like it should, testing for object identity doesn't work. (You'd could test for identity of the function objects pointed to by the bound methods' __func__ attributes.) However, plain old test for equality works, so, for example, to search the instance object's attribute space: >>> class MyClass(object): ... def __init__(self,a,b): ... self.a=a ... self.b=b ... def myfunc(self): ... return self.a+self.b ... >>> myclass = MyClass(3,4) >>> myclass.myfunc2 = myclass.myfunc >>> >>> for name in dir(myclass): ... obj = getattr(myclass, name) ... if obj == myclass.myfunc: ... print " %s is %s" % (name, obj) ... myfunc is <bound method MyClass.myfunc of <__main__.MyClass object at 0xc6d70>> myfunc2 is <bound method MyClass.myfunc of <__main__.MyClass object at 0xc6d70>> -- Ned Deily, [email protected] -- http://mail.python.org/mailman/listinfo/python-list
