• # wrapper et decorateur

    Posté par (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:

    #!/usr/bin/env python
    def _function1(name, arg_recurrent):
     """ this function just print there args.
     We want to make it callable with only one arg"""
     print name, arg_recurrent
    def defaultArg(function, **defaultArgs):
     """ wrap a function to automatically add defaultArgs to the call"""
     def newFunction(*args, **kwords):
     for k, item in defaultArgs.items():
     kwords.setdefault(k, item)
     return function(*args, **kwords)
     return newFunction
    def canCall(functionToWrap):
     """ Automatically replace functionToWrap by wrap of functionToWrap when calling the function"""
     def decorator(function):
     def newFunction(*args, **kwords):
     newfunctionToWrap = defaultArg(functionToWrap, arg_recurrent=kwords.get("arg_recurrent",args[-1]))
     function.func_globals[functionToWrap.func_name] = newfunctionToWrap
     function(*args, **kwords)
     function.func_globals[functionToWrap.func_name] = functionToWrap
     return newFunction
     return decorator
    # create a new function
    function1 = defaultArg(_function1, arg_recurrent=3.14)
    def function2(arg_recurrent):
     """ create the fonction in the local namespace"""
     function1 = defaultArg(_function1, arg_recurrent=arg_recurrent)
     function1("function2")
    def function3():
     """ use the global function"""
     function1("function3")
    @canCall(_function1)
    def function4(arg_recurrent):
     # here we call the wrapped version of _function1
     _function1("function4")
    @canCall(_function1)
    def function5(arg_recurrent):
     print arg_recurrent,
     arg_recurrent += 10
     print arg_recurrent,
     _function1("function5")
    arg_r = 42
    function2(arg_r)
    function3()
    function4(arg_r+1)
    function4(arg_r-1)
    function1("main")
    _function1("_function1", 52)
    function5(arg_r)
    class Int:
     def __init__(self, value):
     self.value = value
     def __iadd__(self, value):
     self.value += value
     def __str__(self):
     return str(self.value)
    function5(Int(arg_r))
    
    

    Matthieu Gautier|irc:starmad