2012-03-27 10 views
11

estoy programando en Python, y me pregunto si puedo comprobar si una función ha sido llamada en mi códigoaveriguar si una función se ha llamado

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

¿Cómo voy a hacer esto?

+0

me escribió una [decorador contando] (http: //code.activestate.com/recipes/577534-counting-decorator/?in=user-4173873) que cuando se aplica te dirá cuántas veces se invocó una función. Puede adaptar esto a su necesidad si lo desea. –

+0

¿Qué esperas hacer con esta información? –

Respuesta

20

Si está bien para la función para conocer su propio nombre, se puede utilizar un atributo de función:

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


example() 

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

También es posible usar un decorador para establecer el atributo:

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

Es interesante saber que la función puede obtener un atributo porque todo en Python es un objeto. Las funciones son objetos de la clase "función". Y puede asignar un atributo a una instancia porque no tiene que declarar variables en Python, por lo que puede asignarlas en tiempo de ejecución. –

0

Aquí hay una decorador que observará toda su función, usando colorama, para obtener un buen resultado.

Proveedores: importación coloramac excepto ImportError: clase StdClass: pasar transeúnte def (* args, ** kwargs): Paso Colorama = StdClass() colorama.init = transeúnte 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 
salida:
Hello world! 
The function 'bonjour' hasn't been called. Defined in "path_to_file.py" 
Cuestiones relacionadas