[Python-ideas] Syntax for easy binding __name__, __module__, __qualname__ to arbitrary objects

Piotr Duda duda.piotr at gmail.com
Thu May 9 13:52:01 CEST 2013


2013/5/9 Paul Moore <p.f.moore at gmail.com>:
> On 9 May 2013 11:29, Piotr Duda <duda.piotr at gmail.com> wrote:
>>
>>
>> To solve these problems I propose to add simple syntax that assigns
>> these attributes to arbitrary object:
>> def name = expression
>> other possible forms may be:
>> def name from expression
>> class name = expression
>> class name from expression
>> name := expression # new operator
>>
>>
>> which would be equivalent for:
>> _tmp = expression
>> _tmp.__name__ = 'name'
>> _tmp.__qualname__ = ... # corresponding qualname
>> _tmp.__module__ = __name__
>> # apply decorators if present
>> name = _tmp
>
>
> Just for clarification, if you used this syntax with an expression which
> returned an object which *didn't* allow attributes to be set, I assume it
> would simply fail at runtime with an AttributeError? For example,
>
> def x = 12

Yes, it fails, I thought about ignoring exceptions on attribute
assignment, but then the syntax wouldn't provide any guarantees and in
those cases it will be equivalent of simple assignment.

>
> This isn't a point against the syntax, I just think it's worth being
> explicit that this is what would happen.
>
> Overall, I'm somewhat indifferent. The use case seems fairly specialised to
> me, and yet the syntax "def name = value" seems like it's worth reserving
> for something a bit more generally useful.
>
> Maybe the def name=value syntax should implement a protocol, that objects
> like enum and namedtuple subclasses can hook into (in the same way that the
> context manager and iterator protocols work, or indeed the whole class
> definition mechanism).

This may be good idea.


--
闇に隠れた黒い力
弱い心を操る



More information about the Python-ideas mailing list