首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >查看函数是否已被调用

查看函数是否已被调用
EN

Stack Overflow用户
提问于 2012-03-27 09:42:38
回答 3查看 27.9K关注 0票数 22

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

代码语言:javascript
复制
def example():
    pass
example()
#Pseudocode:
if example.has_been_called:
   print("foo bar")

我该怎么做呢?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-03-27 10:06:48

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

代码语言:javascript
复制
def example():
    example.has_been_called = True
    pass
example.has_been_called = False


example()

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

您还可以使用装饰器来设置属性:

代码语言:javascript
复制
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")
票数 32
EN

Stack Overflow用户

发布于 2019-11-22 19:19:45

我们可以使用mock.Mock

代码语言:javascript
复制
from unittest import mock


def check_called(func):
    return mock.Mock(side_effect=func)


@check_called
def summator(a, b):
    print(a + b)


summator(1, 3)
summator.assert_called()
assert summator.called == True
assert summator.call_count > 0

summator.assert_called_with(1, 3)

summator.assert_called_with(1, 5)  # error
# AssertionError: Expected call: mock(1, 5)
# Actual call: mock(1, 3)
票数 2
EN

Stack Overflow用户

发布于 2016-11-14 15:01:20

这里有一个装饰器,它将使用colorama观察你所有的函数,并返回一个很好的输出。

代码语言:javascript
复制
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

输出:

代码语言:javascript
复制
Hello world!
The function 'bonjour' hasn't been called. Defined in "path_to_file.py" 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9882280

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档