[Python-ideas] Before and after the colon in funciton defs.

Ron Adam ron3200 at gmail.com
Sat Sep 17 07:47:26 CEST 2011

On Sat, 2011-09-17 at 11:01 +1000, Nick Coghlan wrote:
> On Sat, Sep 17, 2011 at 7:30 AM, Ron Adam <ron3200 at gmail.com> wrote:
> > (This idea may have been suggested before, because it seems too obvious
> > to me.)
> >
> > How about if we remove the requirement that the colon be on the same
> > line as the function name.
> I don't see any benefit in offering a second way to spell docstrings
> or decorators (the existing spellings are easy enough to remember),
> but this suggestion did prompt an idea for potentially replacing uses
> of the default argument hack: allow a sequence of 'implicit locals' to
> be defined within square brackets after the parameter list. (This idea
> may have come up before, but if it has, I don't recall the arguments
> against it).

I almost included an example similar to this.  Using your adder example,
it would have looked something like this.

    adders = []
    for i in range(10):
       def f(x)            # Real calling signature is clear
           f.initial_values(i=i)     # done at def time
           return x + i

Of course there is no way to preinitialize a functions name space. Your
[i=i] notation would do something like that behind the scenes.

I was thinking it would be good if the parts in front of the colon were
valid python statements except in the case of the already special
docstrings and decorators.  It could be limited to only valid python
commands.  If it turns out that a particular command becomes very
common, a special syntax could be considered.  Having the colon on a
separate line would be optional, so it wouldn't change existing code at

I tried to find a way to use a decorator to do this and didn't find
anything that worked nicely.  It can be done nicely with class's, but
the point of using a function is it would be more efficient.

I think this also starts to get into the area of meta programming.

In python library there are a number of functions of the form.

   def foo(*args, **kwds):
       return _foo(*args, **kwds)

I presume there is a reason why they didn't just do foo = _foo.

currently you can swap out the __code__ part of a function, but not the
signature part.  If you could, then this might be possible.

   def foo()                     # Using _foo's signature. 
       foo.signature = _foo.signature
       foo.__code__ = _foo.__code__
       pass      # using _foo.__code__

Cheers, Ron

More information about the Python-ideas mailing list