[Python-ideas] Assignment decorators (Re: The Descriptor Protocol...)

MRAB python at mrabarnett.plus.com
Fri Mar 11 04:33:43 CET 2011

On 10/03/2011 19:02, Guido van Rossum wrote:
> On Thu, Mar 10, 2011 at 11:41 AM, Paul Moore<p.f.moore at gmail.com>  wrote:
>> On 10 March 2011 12:49, Nick Coghlan<ncoghlan at gmail.com>  wrote:
>>> I actually agree it is a major weakness of the syntax. You can play
>>> games with "from" to rearrange the line. For example:
>>> def name from builder(param_spec):
>>>   code_block
>>> as sugar for:
>>> name = builder("name", param_spec_obj, code_obj)
>> Yes, I like that better...
> I'd like it better if it came with a default builder implementation
> that would create regular functions, so that
> def name(<params>):
>    <block>
> was equivalent to
> def name from<defaultbuilder>(<params>):
>    <block>
> But I don't see a reasonable way to do that.
> Also I think it's confusing to have both
> @some_magic
> def name(<params>): ...
> and
> def name from some_magic(<params): ...
> with different semantics.
Talking about different semantics, I had an (admittedly vague) idea
about passing the body of a def statement to a builder as a string at
runtime, allowing 'foreign' code to be embedded more easily.

In a statement of the form:

     def name(...) from builder:

the body of the def wouldn't be parsed by Python at compile time, but
would, as I said, be passed to the builder as a string at runtime. The
builder would be able to parse the string, compiling it to a callable
object with hooks into Python so that it could access variables, call
functions, etc, when it was actually executed.

For example, this:

     c.execute("""insert into stocks values (?, ?, ?, ?, ?)""", 
('2006-01-05', 'BUY', 'RHAT',100, 35.14))

could become (assuming that sqlite3 had a magic __compile__ function):

     def insert(date, trans, symbol, qty, price) from sqlite3:
         insert into stocks values (date, trans, symbol, qty, price)

     insert('2006-01-05', 'BUY', 'RHAT',100, 35.14)

When run, the SQL code would fetch the values of the parameters as

Actually, a closer match to the original code would be:

     c.insert('2006-01-05', 'BUY', 'RHAT',100, 35.14)

Clearly it's a method, so the instance would be passed as 'self',
something like this:

     def insert(self, date, trans, symbol, qty, price) from sqlite3:
         insert into stocks values (date, trans, symbol, qty, price)

but what happens to 'self' within the definition? It's not referred to
in the SQL statement itself.

More information about the Python-ideas mailing list