Ticket #7379: trac-7379-decorator-defaults.patch

File trac-7379-decorator-defaults.patch, 2.1 KB (added by jason, 11 years ago)

FOR SAGE DEVEL REPOSITORY

  • sage/misc/misc.py

    # HG changeset patch
    # User Jason Grout <jason-sage@creativetrax.com>
    # Date 1273736889 18000
    # Node ID d371c3d0a47b3795707644ae241ede872e5dad7f
    # Parent  c9043beb804bcf2344772fca988da01909602320
    #7379: Make it possible for a decorator to work with or without arguments
    
    diff -r c9043beb804b -r d371c3d0a47b sage/misc/misc.py
    a b  
    25842584        wrapper._sage_src_=lambda: sage_getsource(wrapped)
    25852585        return wrapper
    25862586    return f
     2587
     2588def decorator_defaults(func):
     2589    """
     2590    This function allows a decorator to have default arguments.
     2591
     2592    Normally, a decorator can be called with or without arguments.
     2593    However, the two cases call for different types of return values.
     2594    If a decorator is called with no parentheses, it should be run
     2595    directly on the function.  However, if a decorator is called with
     2596    parentheses (i.e., arguments), then it should return a function
     2597    that is then in turn called with the defined function as an
     2598    argument.
     2599
     2600    This decorator allows us to have these default arguments without
     2601    worrying about the return type.
     2602
     2603    EXAMPLES::
     2604   
     2605        sage: from sage.misc.misc import decorator_defaults
     2606        sage: @decorator_defaults
     2607        ... def my_decorator(f,*args,**kwds):
     2608        ...     print kwds
     2609        ...     print args
     2610        ...     print f.__name__
     2611        ...       
     2612        sage: @my_decorator
     2613        ... def my_fun(a,b):
     2614        ...     return a,b
     2615        ... 
     2616        {}
     2617        ()
     2618        my_fun
     2619        sage: @my_decorator(3,4,c=1,d=2)
     2620        ... def my_fun(a,b):
     2621        ...     return a,b
     2622        ...   
     2623        {'c': 1, 'd': 2}
     2624        (3, 4)
     2625        my_fun
     2626    """
     2627    from sage.misc.misc import sage_wraps
     2628    @sage_wraps(func)
     2629    def my_wrap(*args,**kwds):
     2630        if len(kwds)==0 and len(args)==1:
     2631            # call without parentheses
     2632            return func(*args)
     2633        else:
     2634            return lambda f: func(f, *args, **kwds)
     2635    return my_wrap