Python dynamic method for obtaining the currently running class name and function name

Source: Internet
Author: User

1. Use the built-in method and modifier to obtain the class name and function name

In python, function names can be obtained from both internal and external sources. When the external conditions are good, the object pointing to the function is used and the _ name _ attribute is used.
Copy codeThe Code is as follows: def a (): pass
A. _ name __
In addition, you can:
Copy codeThe Code is as follows: getattr (a, '_ name __')
Despite some cases, the external method is flexible.

Some users need some skills to obtain the name of a function from the function itself.
1. How to Use the sys module:
Copy codeThe Code is as follows:
Def ():
Print sys. _ getframe (). f_code.co_name
For f_code and co_name, refer to the pyc generation and namespace chapter in python source code parsing.
2. How to Use the modifier:
You can use the modifier to point to a variable for the function, and then take the _ name _ method of the variable object.
Copy codeThe Code is as follows: def timeit (func ):
Def run (* argv ):
Print func. _ name __
If argv:
Ret = func (* argv)
Else:
Ret = func ()
Return ret
Return run

@ Timeit
Def t ():
Print
T (1)

Ii. Use the inspect module to dynamically obtain the name of the currently running Function


Copy codeThe Code is as follows:
Import inspect

Def get_current_function_name ():
Return inspect. stack () [1] [3]
Class MyClass:
Def function_one (self ):
Print "% s. % s invoked" % (self. _ class _. _ name __, get_current_function_name ())
If _ name _ = "_ main __":
Myclass = MyClass ()
Myclass. function_one ()
It is convenient to dynamically obtain the name of the currently running function, especially for some debug systems.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.