How Python Gets the name of the current function and calls it through a string

Source: Internet
Author: User

Gets the current function name:

Application Environment: Sometimes, in order to simplify and better extend the program, we need to get to the currently running function name

Method 1 (not recommended)

import sysdef I_want_to_know_my_name():    print(sys._getframe().f_code.co_name) #你懂得,下划线开头的不应该使用的

Method 2

import tracebackdef who_am_i():    return traceback.extract_stack()[-2][2]def I_want_to_know_my_name():    print(who_am_i())

Method 3

import inspectdef who_am_i2():    return inspect.stack()[1][3]def I_want_to_know_my_name():    print(who_am_i2())      
Calling a function from a string

Called by reflection or exec, there are examples of classes and functions below
Class:

class foo(object):    def load(self):        f = getattr(self, "load_json")        f()    def load_json(self):        print("This is load_json module")myfunc = foo()myfunc.load()

Function (Reflection):

# 单模块情况下, 多模块就import module1,  然后getattr(module1....)import sysdef bar():    print("This is bar")def foo():    print("This is foo")def check_str(stra):    mod = sys.modules[__name__] #获取当前模块对象    if hasattr(mod, stra):        getattr(mod, stra)()    else:        print("No this module")check_str("bar") #你可能会问如果输入check_str会怎么样, 我会告诉你缺少变量并报错,不过最好还是在上面函数加判断避免这种情况出现

function (EXEC):

def bar():    print("This is bar")def foo(stra):    try:        exec(stra)    except:        print("No this module")foo("bar()")
Examples of combined use

Assuming a function of load is provided externally, through a series of judgments, I get to a value of ext_module_name, through this value and "load", I am all kinds of low wrong, is load. If you need to extend XML later, Gson, Yaml, and so on, only write the corresponding # # #_load就可以了

import tracebackext_module_name = "_pickle_" #假设这个变量是之前一系列过程得到的结果def who_am_i():    return traceback.extract_stack()[-2][2]def _json_load():    print("json load")def _pickle_load():    print("pickle load")def load():    my_name = who_am_i()    try:        return exec("%s%s()" % (ext_module_name, my_name))    except Exception as e:        raise eload()

How Python Gets the name of the current function and calls it through a string

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.