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

Eric Snow ericsnowcurrently at gmail.com
Fri Jun 17 07:48:25 CEST 2011

On Thu, Jun 16, 2011 at 10:39 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> 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.

Even still, at first glance that looks like a decorator.  Also, going
multiline makes it worse:

    @inject (mem=collections.Counter(),
    def do_and_remember(val, verbose=False):

> 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"

In my mind, putting it inside the function is similar to docstrings
being inside, especially if the simple statements are evaluated at
definition time.  Also, I kind of like the idea of combing @ with the
keyword since it distinguishes the context.

What about when you have several of these and they get long?  Could
you use parentheses?  With the def keyword and parentheses it looks
different enough from a function that I don't mind it, but maybe the
keyword could be different (I do like that it reuses a keyword):

  def f(a,b):
      """Do something...

      @def (x=[name for name in names if name != None],

      print(a, b)
      print([y(name) for name in x])

(And a given statement would fit in nicely instead of those parentheses. ;)


> Cheers,
> Nick.
> --
> Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas

More information about the Python-ideas mailing list