[Python-ideas] 'Injecting' objects as function-local constants

Nick Coghlan ncoghlan at gmail.com
Mon Jun 13 13:57:06 CEST 2011


On Mon, Jun 13, 2011 at 6:05 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> All a "persistent state" proposal would do is create an alternative to
> the default argument hack that doesn't suffer from the same problems:
>
>       def do_and_remember(val, verbose=False, **, mem=collections.Counter()):
>           result = do_something(val)
>           mem[val] += 1
>           if verbose:
>               print('Done {} times for {!r}'.format(_mem[val], val))

As yet another shade for this particular bikeshed, this one just occurred to me:

    def do_and_remember(val, verbose=False):
          @def mem=collections.Counter()
          result = do_something(val)
          mem[val] += 1
          if verbose:
              print('Done {} times for {!r}'.format(_mem[val], val))

The @def ("at def") statement is just a new flavour of the same
proposal that has been made many times before: a way to indicate that
a simple assignment statement should be executed once at function
definition time rather than repeatedly on every call to the function.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list