programing tip

함수 이름을 문자열로 얻는 방법?

itbloger 2020. 10. 2. 21:46
반응형

함수 이름을 문자열로 얻는 방법?


파이썬에서 함수를 호출하지 않고 어떻게 함수 이름을 문자열로 얻습니까?

def my_function():
    pass

print get_function_name_as_string(my_function) # my_function is not in quotes

출력해야합니다 "my_function".

파이썬에서 그러한 기능을 사용할 수 있습니까? 그렇지 않다면 get_function_name_as_stringPython에서을 구현하는 방법에 대한 아이디어가 있습니까?


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__속성이 있으므로 하나의 특수 이름 만 기억할 수 있습니다.


내부에서 현재 함수 또는 메서드의 이름을 가져 오려면 다음을 고려하십시오.

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

my_function.func_name

함수의 다른 재미있는 속성도 있습니다. dir(func_name)나열하려면 입력 하십시오. func_name.func_code.co_code문자열로 저장된 컴파일 된 함수입니다.

import dis
dis.dis(my_function)

거의 사람이 읽을 수있는 형식으로 코드를 표시 합니다. :)


이 함수는 호출자의 함수 이름을 반환합니다.

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

친절한 래퍼로 Albert Vonpupp의 대답과 같습니다.


당신이 너무 급 방법에 관심이 있다면, 파이썬은 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"

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():

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.


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)])

import inspect

def foo():
   print(inspect.stack()[0][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

참고URL : https://stackoverflow.com/questions/251464/how-to-get-a-function-name-as-a-string

반응형