Re: Decorators not worth the effort

Discussion in 'Python' started by andrea crotti, Sep 14, 2012.

  1. I think one very nice and simple example of how decorators can be used is this:

    def memoize(f, cache={}, *args, **kwargs):
    def _memoize(*args, **kwargs):
    key = (args, str(kwargs))
    if not key in cache:
    cache[key] = f(*args, **kwargs)

    return cache[key]

    return _memoize

    def fib(n):
    if n <= 1:
    return 1
    return fib(n-1) + fib(n-2)

    @memoize
    def fib_memoized(n):
    if n <= 1:
    return 1
    return fib_memoized(n-1) + fib_memoized(n-2)


    The second fibonacci looks exactly the same but while the first is
    very slow and would generate a stack overflow the second doesn't..

    I might use this example for the presentation, before explaining what it is..
    andrea crotti, Sep 14, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jean-Michel Pichavant

    Re: Decorators not worth the effort

    Jean-Michel Pichavant, Sep 14, 2012, in forum: Python
    Replies:
    4
    Views:
    189
    Steve Howell
    Sep 15, 2012
  2. Jean-Michel Pichavant

    Re: Decorators not worth the effort

    Jean-Michel Pichavant, Sep 14, 2012, in forum: Python
    Replies:
    1
    Views:
    134
    Steven D'Aprano
    Sep 14, 2012
  3. Chris Angelico

    Re: Decorators not worth the effort

    Chris Angelico, Sep 14, 2012, in forum: Python
    Replies:
    2
    Views:
    150
    88888 Dihedral
    Sep 14, 2012
  4. Jean-Michel Pichavant

    Re: Decorators not worth the effort

    Jean-Michel Pichavant, Sep 14, 2012, in forum: Python
    Replies:
    0
    Views:
    130
    Jean-Michel Pichavant
    Sep 14, 2012
  5. andrea crotti

    Re: Decorators not worth the effort

    andrea crotti, Sep 14, 2012, in forum: Python
    Replies:
    0
    Views:
    134
    andrea crotti
    Sep 14, 2012
Loading...

Share This Page