找出是否调用了函数

2024-05-14 16:27:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用Python编程,我想知道我是否可以测试我的代码中是否调用了函数

def example():
    pass
example()
#Pseudocode:
if example.has_been_called:
   print("foo bar")

我该怎么做?


Tags: 函数代码iffooexampledef编程bar
3条回答

Memoization函数从20世纪60年代就出现了,在python中,可以将它们用作example()函数的装饰器。

标准的记忆功能如下:

def memoize(func):
    memo = {}
    def wrapper(*args):
        if not args in memo:
            memo[args] = func(*args)
        return memo[args]
    return wrapper 

你这样装饰你的功能:

@memoize
def example():
    pass

在python3.2中,可以使用functools.lru_cache而不是memoziation函数。

import functools

@functools.lru_cache(maxsize=None)
def example():
     pass

如果函数可以知道自己的名称,则可以使用函数属性:

def example():
    example.has_been_called = True
    pass
example.has_been_called = False


example()

#Actual Code!:
if example.has_been_called:
   print("foo bar")

您还可以使用decorator设置属性:

import functools

def trackcalls(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        wrapper.has_been_called = True
        return func(*args, **kwargs)
    wrapper.has_been_called = False
    return wrapper

@trackcalls
def example():
    pass


example()

#Actual Code!:
if example.has_been_called:
   print("foo bar")

这里有一个decorator,它将使用colorama监视您的所有功能,并返回一个不错的输出。

try:
    import colorama
except ImportError:
    class StdClass: pass
    def passer(*args, **kwargs): pass
    colorama = StdClass()
    colorama.init = passer
    colorama.Fore = StdClass()
    colorama.Fore.RED = colorama.Fore.GREEN = ''

def check_for_use(show=False):
    if show:
        try:
            check_for_use.functions
        except AttributeError:
            return
        no_error = True
        for function in check_for_use.functions.keys():
            if check_for_use.functions[function][0] is False:
                print(colorama.Fore.RED + 'The function {!r} hasn\'t been called. Defined in "{}" '.format(function, check_for_use.functions[function][1].__code__.co_filename))
                no_error = False
        if no_error:
            print(colorama.Fore.GREEN + 'Great! All your checked function are being called!')
        return check_for_use.functions
    try:
        check_for_use.functions
    except AttributeError:
        check_for_use.functions = {}
        if colorama:
            colorama.init(autoreset=True)

    def add(function):
        check_for_use.functions[function.__name__] = [False, function]
        def func(*args, **kwargs):
            check_for_use.functions[function.__name__] = [True, function]
            function(*args, **kwargs)
        return func
    return add

@check_for_use()
def hello():
    print('Hello world!')

@check_for_use()
def bonjour(nb):
    print('Bonjour tout le monde!')


# hello(); bonjour(0)

hello()


check_for_use(True) # outputs the following
输出:
Hello world!
The function 'bonjour' hasn't been called. Defined in "path_to_file.py" 

相关问题 更多 >

    热门问题