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

Nick Coghlan ncoghlan at gmail.com
Fri Jun 17 06:39:50 CEST 2011

On Fri, Jun 17, 2011 at 3:15 AM, Jan Kaliszewski <zuo at chopin.edu.pl> wrote:
> or even (to stress that it is a language syntax construct:
>    @inject mem=collections.Counter(), MAX_MEM=1000
>    def do_and_remember(val, verbose=False):

While that would require the from__future__ dance to make "inject" a
new keyword, I like it much better than the
looks-like-a-decorator-but-isn't syntax.

The '@def' keyword would also technically work with that positioning,
but @inject provides a better mnemonic for what is going on when the
assignments are positioned outside the function.

> Also, such placement is imho more appropriate for @-that-starts-a-line-
> -syntax (because it would *resemble* decorating syntax anyway -- and
> what's wrong with that?) + we avoid misleading clusters such as:
>    def do_something(func):
>        @def mem=colletions.Counter  # <- looks a bit like another
>        @wraps(func)                 #    decorator for wrapper_func()
>        @my_decorator(mem)
>        def wrapper_func():
>            ...

The advantage of putting the '@def' lines *inside* the function is
that it makes it clearer which namespace they're affecting. Examples
like the above are readily addressed via style rules that say "don't
do that, it's hard to read - leave a blank line between the @def code
and the subsequent function decorators"


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

More information about the Python-ideas mailing list