2012-03-27 6 views
11

呼び出されているかどうかを調べる私はPythonでプログラミングをしていて、機能は私がこれをどのように行うだろう機能が

def example(): 
    pass 
example() 
#Pseudocode: 
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") 
+0

私は[カウントデコレータ](HTTPを書きました//code.activestate.com/recipes/577534-counting-decorator/?in=user-4173873)適用されると、関数が何回呼び出されたかがわかります。必要に応じてこれをあなたのニーズに適応させることができます。 –

+0

この情報で何をしたいですか? –

答えて

20

は、あなたが関数属性を使用することができますcoloramaを使用してすべての関数を見るデコレータは素晴らしい出力を得ます。

試し:はImportError除く インポートcoloramac : クラスはstdClass: DEFパサー(* argsを、** kwargsから)を渡す: コロラマを渡す=はstdClass() colorama.init =通行人 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" 
+0

Pythonのすべてがオブジェクトなので、関数が属性を取得できることは興味深いことです。関数は、 "function"クラスのオブジェクトです。 Pythonで変数を宣言していないので、実行時に変数を割り当てることができるので、インスタンスに属性を割り当てることができます。 –

0

:属性を設定する

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


example() 

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

あなたはまた、デコレータを使用することができます:関数は、自身の名前を知ることがOKなら