[Python-ideas] The "in"-statement

Masklinn masklinn at masklinn.net
Tue Nov 6 09:49:36 CET 2012


On 2012-11-05, at 23:36 , Steven D'Aprano wrote:

> On 06/11/12 06:28, Markus Unterwaditzer wrote:
> 
>> I thought it would be neat if i could do::
>> 
>>     in obj:
>>         first_attr = "value"
>>         second_attr = "value2"
>> 
>>     some_other = "lel"  # indenting this would cause it to appear as an attribute of obj
>> 
>> Just a vague idea. Tell me what you think.
> 
> 
> This is Pascal's old "with" block. It works well for static languages like
> Pascal, where the compiler can tell ahead of time which names belong to what,
> but less well for dynamic languages like Python. Non-trivial examples of this
> design feature will be ambiguous and error-prone.

A possible alternative (though I'm not sure how integration in Python
would work, syntactically) which might be a better fit for dynamically
typed languages would be Smalltalk's "message cascading" with allowances
for assignment.

Using `|` as the cascading operator (as Smalltalk's ";" is already used
in Python) for the example,

    obj| first_attr = "value"
       | second_attr = "value2"
       | some_method()
       | some_other_method(2)

this would essentially desugar to:

    obj.first_attr = "value"
    obj.second_attr = "value2"
    obj.some_method()
    obj.some_other_method(2)

but as a single expression, and returning the value of the last call. I
see most of the value of cascading in the "chaining" of method calls
which can't be chained, but extending it to attribute access (get/set)
could be neat-ish.

Of course this might also need a new self/yourself attribute on
``object`` to top up the cascade.


More information about the Python-ideas mailing list