[Python-ideas] The "in"-statement

Masklinn masklinn at masklinn.net
Mon Nov 5 21:44:26 CET 2012


On 2012-11-05, at 20:47 , Bruce Leban wrote:

> On Mon, Nov 5, 2012 at 11:28 AM, Markus Unterwaditzer <
> markus at unterwaditzer.net> wrote:
> 
>> While mocking objects, i got annoyed by the following code pattern i had to
>> use when modifying multiple attributes on a single object::
>> 
>>    obj.first_attr = "value"
>>    obj.second_attr = "value2"
>> 
>>    some_other = "lel"
>> 
>> 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
>> 
> 
> Hard to read, error-prone and ill-defined. Does it create new attributes or
> only change existing ones? What about identifiers on right hand sides? What
> would
>    third_attr = lambda: first_attr
> do?

Even well-defined, it sounds like a shortcut creating more issues than
it solves. Javascript has something which sounds very, very similar in
`with` and apart from being hell on performances and having very broken
semantics[0] its one and only non-hacky use case is for `eval` (because
javascript's eval doesn't have `locals` and `globals` parameters).

[0] `with` uses the object it is provided as an internal scope, which
     means this:

    with (a) {
        b = 3;
    }

    will result in `a.b` being set to 3 if `a` already has a `b`
    attribute, otherwise it may clobber an existing `b` in a higher
    lexical scope, and if none exists it will just create a brand new
    global `b`.


More information about the Python-ideas mailing list