Подтвердить что ты не робот

Узнать, была ли вызвана функция

Я программирую на Python, и мне интересно, могу ли я проверить, вызвана ли функция в моем коде

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

Как мне это сделать?

4b9b3361

Ответ 1

Если это нормально для функции, чтобы узнать свое имя, вы можете использовать атрибут функции:

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


example()

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

Вы также можете использовать декоратор для установки атрибута:

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

Ответ 2

Здесь декоратор, который будет смотреть всю вашу функцию, используя colorama, чтобы получить хороший результат.

попробовать:       import coloramac   кроме ImportError:       класс StdClass: pass       def passer (* args, ** kwargs): pass       colorama = StdClass()       colorama.init = passer       colorama.Fore = StdClass()       цветama.Fore.RED = цветama.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"