[Tutor] Equivalent of PHP's __FUNCTION__ ?

Kent Johnson kent37 at tds.net
Thu Dec 2 21:02:09 CET 2004


Kent Johnson wrote:
> Here is one way to do it, based on this Python Cookbook recipe:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062

Use of sys._getframe() is generally considered something of a skanky hack. (Though it is often done 
anyway.) Here is another solution that only uses supported public interfaces:

def debug(msg):
     import traceback
     frame = traceback.extract_stack(limit=1)[0]
     filename, line_number, name, text = frame

     return 'File "%s", line %d, in %s: %s' % (filename, line_number, name, msg)


> 
> def debug(msg):
>     import sys
>     frame = sys._getframe(1)
> 
>     name = frame.f_code.co_name
>     line_number = frame.f_lineno
>     filename = frame.f_code.co_filename
> 
>     return 'File "%s", line %d, in %s: %s' % (filename, line_number, 
> name, msg)
> 
> 
> def test():
>     print debug("Invalid arguments")
> 
> 
> test()
> 
> Kent
> 
> Mohamed Lrhazi wrote:
> 
>> Hello all,
>>
>> In php one can produce nice debugging and logging use code like:
>>     print __FUNCTION__ . ": Invalid arguments\n";
>>
>> __FUNCTION__ will be replaced by the name of the function to which 
>> that line belongs, same with __LINE__ and __FILE__ I believe.
>>
>> How do I get the current method's name? and class?
>>
>> Thanks.
>>
>> Mohamed~
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


More information about the Tutor mailing list