how to find the last decorator of a chain

samwyse samwyse at gmail.com
Sun May 31 22:40:36 EDT 2009


On May 30, 6:16 pm, Gabriel <gabr... at opensuse.org> wrote:

> I have something like this:
>
> @render(format="a")
> @render(format="b")
> @....
> def view(format, data):
>   return data

> In my understanding this equivalent to:
>
> render('a',
>  render('b',
>   view(***)))

Not quite.  'render' is a function of one argument that returns a
decorator. So, the equivalent is more like this:
  view = render('a')(render('b')(view))
or more simply:
  fb = render('b')
  view = fb(view)
  fa = render('a')
  view = fa(view)

> Is there any way to know, in this case, that 'a' is the 'default' format?

Will this do?  (In case the formatting gets messed up, I've also
posted the code to http://python.pastebin.com/f7f229d9d)

##from functools import wraps

def render(c):
    def decorator(f):
##        @wraps(f)
        def wrapper(*args, **kwds):
            if getattr(wrapper, 'outermost', False):
                print('outer wrapper', c)
            else:
                print('inner wrapper', c)
            return f(*args, **kwds)
        return wrapper
    return decorator

def mark_as_top(f):
    print('marking', f)
    f.outermost = True
##    @wraps(f)
    return f

@mark_as_top
@render('a')
@render('b')
@render('c')
@render('d')
def f():
    pass

f()




More information about the Python-list mailing list