Faut probablement l'améliorer et l'adapter à tes besoins mais ça marche.
Le code devrait parler de lui même:
#!/usr/bin/env pythondef_function1(name,arg_recurrent):""" this function just print there args. We want to make it callable with only one arg"""printname,arg_recurrentdefdefaultArg(function,**defaultArgs):""" wrap a function to automatically add defaultArgs to the call"""defnewFunction(*args,**kwords):fork,itemindefaultArgs.items():kwords.setdefault(k,item)returnfunction(*args,**kwords)returnnewFunctiondefcanCall(functionToWrap):""" Automatically replace functionToWrap by wrap of functionToWrap when calling the function"""defdecorator(function):defnewFunction(*args,**kwords):newfunctionToWrap=defaultArg(functionToWrap,arg_recurrent=kwords.get("arg_recurrent",args[-1]))function.func_globals[functionToWrap.func_name]=newfunctionToWrapfunction(*args,**kwords)function.func_globals[functionToWrap.func_name]=functionToWrapreturnnewFunctionreturndecorator# create a new functionfunction1=defaultArg(_function1,arg_recurrent=3.14)deffunction2(arg_recurrent):""" create the fonction in the local namespace"""function1=defaultArg(_function1,arg_recurrent=arg_recurrent)function1("function2")deffunction3():""" use the global function"""function1("function3")@canCall(_function1)deffunction4(arg_recurrent):# here we call the wrapped version of _function1_function1("function4")@canCall(_function1)deffunction5(arg_recurrent):printarg_recurrent,arg_recurrent+=10printarg_recurrent,_function1("function5")arg_r=42function2(arg_r)function3()function4(arg_r+1)function4(arg_r-1)function1("main")_function1("_function1",52)function5(arg_r)classInt:def__init__(self,value):self.value=valuedef__iadd__(self,value):self.value+=valuedef__str__(self):returnstr(self.value)function5(Int(arg_r))
# wrapper et decorateur
Posté par GaMa (site web personnel) . En réponse au message Argument de fonction récurrent. Évalué à 1. Dernière modification le 01 juin 2012 à 14:44.
Faut probablement l'améliorer et l'adapter à tes besoins mais ça marche.
Le code devrait parler de lui même:
Matthieu Gautier|irc:starmad