Return name of caller function?

Matthew Peter survivedsushi at yahoo.com
Wed Jun 27 22:44:57 CEST 2007


--- Jay Loden <python at jayloden.com> wrote:

> 
> Matthew Peter wrote:
> > For example, how do I get this to work?
> > 
> > def func():
> >     print "This is", __?__
> >     return __caller__
> > 
> > def echo():
> >     print "This is ", __?__
> >     return func()
> > 
> > 
> >>>> print echo()
> > This is echo
> > This is func
> > echo
> 
> This may not be what you're looking for but here's the solution I ended up with
> after some help from the list. It's designed for getting the name of an instance
> method, but in case it applies to your particular situation: 
> 
> #!/usr/bin/python
> 
> import functools
> 
> class TestClass:
>   def __init__(self):
>     pass
> 
>   def __getattr__(self, name):
>     try:
>       return getattr(self.__class__, name)
>     except AttributeError:
>       return functools.partial(self.foo, name)
> 
>   def foo(self, name, **args):
>     print "This is", name
> 
> test = TestClass()
> test.someMethod()
> test.anotherMethod()
> 
> Otherwise the inspect module may be the way to go, as Stephen already pointed out
> (though I must admit it seems a very inelegant route, especially compared to
> Python's usually clean and clear style). 
> 
> -Jay
> 


Thanks for the reply. 

The goal is to get it working outside of a class. Overloading the method with
getattr semi-works but it doesn't work in the larger context of what I am trying to
accomplish. 

You could avoid the exception block in your example:


>   def __getattr__(self, name):
>     try:
>       return getattr(self.__class__, name)
>     except AttributeError:
>       return functools.partial(self.foo, name)

to:

   def __getattr__(self, name, *args, **kw):
       return getattr(self.__class__, name, functools.partial(self.foo, name, *args,
**kw))
 
   def foo(self, name, *args, **kw):
     print "This is", name, args, kw
 

print test.squeaky("I need oil")





       
____________________________________________________________________________________
Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase.
http://farechase.yahoo.com/



More information about the Python-list mailing list