问题:如何获得一个函数名作为字符串?

在Python中,如何在不调用函数的情况下以字符串形式获取函数名称?

def my_function():
    pass

print get_function_name_as_string(my_function) # my_function is not in quotes

应该输出"my_function"

此类功能在Python中可用吗?如果没有,关于如何get_function_name_as_string在Python中实现的任何想法?

In Python, how do I get a function name as a string, without calling the function?

def my_function():
    pass

print get_function_name_as_string(my_function) # my_function is not in quotes

should output "my_function".

Is such function available in Python? If not, any ideas on how to implement get_function_name_as_string, in Python?


回答 0

my_function.__name__

使用__name__是首选的方法,因为它可以统一应用。与不同func_name,它还可以用于内置函数:

>>> import time
>>> time.time.func_name
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'builtin_function_or_method' object has no attribute 'func_name'
>>> time.time.__name__ 
'time'

同样,双下划线向读者表明这是一个特殊的属性。另外,类和模块也具有__name__属性,因此您只记得一个特殊名称。

my_function.__name__

Using __name__ is the preferred method as it applies uniformly. Unlike func_name, it works on built-in functions as well:

>>> import time
>>> time.time.func_name
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'builtin_function_or_method' object has no attribute 'func_name'
>>> time.time.__name__ 
'time'

Also the double underscores indicate to the reader this is a special attribute. As a bonus, classes and modules have a __name__ attribute too, so you only have remember one special name.


回答 1

要从内部获取当前函数或方法的名称,请考虑:

import inspect

this_function_name = inspect.currentframe().f_code.co_name

sys._getframeinspect.currentframe尽管后者避免访问私有功能,但它也可以代替。

要获取调用函数的名称,请考虑f_back中的inspect.currentframe().f_back.f_code.co_name


如果还使用mypy,它可能会抱怨:

错误:“ Optional [FrameType]”的项目“ None”没有属性“ f_code”

要抑制上述错误,请考虑:

import inspect
import types
from typing import cast

this_function_name = cast(types.FrameType, inspect.currentframe()).f_code.co_name

To get the current function’s or method’s name from inside it, consider:

import inspect

this_function_name = inspect.currentframe().f_code.co_name

sys._getframe also works instead of inspect.currentframe although the latter avoids accessing a private function.

To get the calling function’s name instead, consider f_back as in inspect.currentframe().f_back.f_code.co_name.


If also using mypy, it can complain that:

error: Item “None” of “Optional[FrameType]” has no attribute “f_code”

To suppress the above error, consider:

import inspect
import types
from typing import cast

this_function_name = cast(types.FrameType, inspect.currentframe()).f_code.co_name

回答 2

my_function.func_name

函数还有其他有趣的属性。键入dir(func_name)以列出它们。func_name.func_code.co_code是已编译的函数,存储为字符串。

import dis
dis.dis(my_function)

将以几乎人类可读的格式显示代码。:)

my_function.func_name

There are also other fun properties of functions. Type dir(func_name) to list them. func_name.func_code.co_code is the compiled function, stored as a string.

import dis
dis.dis(my_function)

will display the code in almost human readable format. :)


回答 3

该函数将返回调用者的函数名称。

def func_name():
    import traceback
    return traceback.extract_stack(None, 2)[0][2]

就像阿尔伯特·冯普普(Albert Vonpupp)用友好的包装纸回答的那样。

This function will return the caller’s function name.

def func_name():
    import traceback
    return traceback.extract_stack(None, 2)[0][2]

It is like Albert Vonpupp’s answer with a friendly wrapper.


回答 4

如果你有兴趣类的方法也一样,Python的3.3+具有__qualname____name__

def my_function():
    pass

class MyClass(object):
    def method(self):
        pass

print(my_function.__name__)         # gives "my_function"
print(MyClass.method.__name__)      # gives "method"

print(my_function.__qualname__)     # gives "my_function"
print(MyClass.method.__qualname__)  # gives "MyClass.method"

If you’re interested in class methods too, Python 3.3+ has __qualname__ in addition to __name__.

def my_function():
    pass

class MyClass(object):
    def method(self):
        pass

print(my_function.__name__)         # gives "my_function"
print(MyClass.method.__name__)      # gives "method"

print(my_function.__qualname__)     # gives "my_function"
print(MyClass.method.__qualname__)  # gives "MyClass.method"

回答 5

我喜欢使用函数装饰器。我添加了一个类,它也乘以函数时间。假设gLog是标准的python记录器:

class EnterExitLog():
    def __init__(self, funcName):
        self.funcName = funcName

    def __enter__(self):
        gLog.debug('Started: %s' % self.funcName)
        self.init_time = datetime.datetime.now()
        return self

    def __exit__(self, type, value, tb):
        gLog.debug('Finished: %s in: %s seconds' % (self.funcName, datetime.datetime.now() - self.init_time))

def func_timer_decorator(func):
    def func_wrapper(*args, **kwargs):
        with EnterExitLog(func.__name__):
            return func(*args, **kwargs)

    return func_wrapper

所以现在您要做的就是装饰它,瞧

@func_timer_decorator
def my_func():

I like using a function decorator. I added a class, which also times the function time. Assume gLog is a standard python logger:

class EnterExitLog():
    def __init__(self, funcName):
        self.funcName = funcName

    def __enter__(self):
        gLog.debug('Started: %s' % self.funcName)
        self.init_time = datetime.datetime.now()
        return self

    def __exit__(self, type, value, tb):
        gLog.debug('Finished: %s in: %s seconds' % (self.funcName, datetime.datetime.now() - self.init_time))

def func_timer_decorator(func):
    def func_wrapper(*args, **kwargs):
        with EnterExitLog(func.__name__):
            return func(*args, **kwargs)

    return func_wrapper

so now all you have to do with your function is decorate it and voila

@func_timer_decorator
def my_func():

回答 6

sys._getframe()不能保证在所有Python实现中都可用(请参阅ref),您可以使用该traceback模块执行相同的操作,例如。

import traceback
def who_am_i():
   stack = traceback.extract_stack()
   filename, codeline, funcName, text = stack[-2]

   return funcName

调用stack[-1]将返回当前过程详细信息。

sys._getframe() is not guaranteed to be available in all implementations of Python (see ref) ,you can use the traceback module to do the same thing, eg.

import traceback
def who_am_i():
   stack = traceback.extract_stack()
   filename, codeline, funcName, text = stack[-2]

   return funcName

A call to stack[-1] will return the current process details.


回答 7

import inspect

def foo():
   print(inspect.stack()[0][3])

哪里

  • stack()[0]调用者

  • stack()[3]方法的字符串名称

import inspect

def foo():
   print(inspect.stack()[0][3])

where

  • stack()[0] the caller

  • stack()[3] the string name of the method


回答 8

作为@Demyn答案的扩展,我创建了一些实用程序函数,这些函数打印当前函数的名称和当前函数的参数:

import inspect
import logging
import traceback

def get_function_name():
    return traceback.extract_stack(None, 2)[0][2]

def get_function_parameters_and_values():
    frame = inspect.currentframe().f_back
    args, _, _, values = inspect.getargvalues(frame)
    return ([(i, values[i]) for i in args])

def my_func(a, b, c=None):
    logging.info('Running ' + get_function_name() + '(' + str(get_function_parameters_and_values()) +')')
    pass

logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter(
    '%(asctime)s [%(levelname)s] -> %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)

my_func(1, 3) # 2016-03-25 17:16:06,927 [INFO] -> Running my_func([('a', 1), ('b', 3), ('c', None)])

As an extension of @Demyn’s answer, I created some utility functions which print the current function’s name and current function’s arguments:

import inspect
import logging
import traceback

def get_function_name():
    return traceback.extract_stack(None, 2)[0][2]

def get_function_parameters_and_values():
    frame = inspect.currentframe().f_back
    args, _, _, values = inspect.getargvalues(frame)
    return ([(i, values[i]) for i in args])

def my_func(a, b, c=None):
    logging.info('Running ' + get_function_name() + '(' + str(get_function_parameters_and_values()) +')')
    pass

logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter(
    '%(asctime)s [%(levelname)s] -> %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)

my_func(1, 3) # 2016-03-25 17:16:06,927 [INFO] -> Running my_func([('a', 1), ('b', 3), ('c', None)])

回答 9

您只想获取函数的名称,这里是一个简单的代码。假设您已经定义了这些功能

def function1():
    print "function1"

def function2():
    print "function2"

def function3():
    print "function3"
print function1.__name__

输出将为function1

现在说您在列表中有这些功能

a = [function1 , function2 , funciton3]

获得功能的名称

for i in a:
    print i.__name__

输出将是

功能1
功能2
功能3

You just want to get the name of the function here is a simple code for that. let say you have these functions defined

def function1():
    print "function1"

def function2():
    print "function2"

def function3():
    print "function3"
print function1.__name__

the output will be function1

Now let say you have these functions in a list

a = [function1 , function2 , funciton3]

to get the name of the functions

for i in a:
    print i.__name__

the output will be

function1
function2
function3


回答 10

我看到了一些使用装饰器的答案,尽管我觉得有些冗长。这是我用来记录函数名称以及它们各自的输入和输出值的东西。我在这里对其进行了修改,以仅打印信息,而不是创建日志文件,并将其修改为应用于OP特定示例。

def debug(func=None):
    def wrapper(*args, **kwargs):
        try:
            function_name = func.__func__.__qualname__
        except:
            function_name = func.__qualname__
        return func(*args, **kwargs, function_name=function_name)
    return wrapper

@debug
def my_function(**kwargs):
    print(kwargs)

my_function()

输出:

{'function_name': 'my_function'}

I’ve seen a few answers that utilized decorators, though I felt a few were a bit verbose. Here’s something I use for logging function names as well as their respective input and output values. I’ve adapted it here to just print the info rather than creating a log file and adapted it to apply to the OP specific example.

def debug(func=None):
    def wrapper(*args, **kwargs):
        try:
            function_name = func.__func__.__qualname__
        except:
            function_name = func.__qualname__
        return func(*args, **kwargs, function_name=function_name)
    return wrapper

@debug
def my_function(**kwargs):
    print(kwargs)

my_function()

Output:

{'function_name': 'my_function'}

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。