[Python-ideas] Attribute-Getter Syntax Proposal
Benedikt Werner
1benediktwerner at gmail.com
Fri Mar 8 17:21:56 EST 2019
I just realized it doesn't work properly if the method takes some arguments,
so you would actually have to use two different magic objects or
something like that,
but I guess the point is clear.
Am 08.03.2019 um 23:08 schrieb Benedikt Werner:
> This was actually quite interesting to code, thanks for the idea
> Jonathan!
>
> You can even support "magic.upper()" and "magic.real" at the same time
> as well as "magic[0]":
>
> class MagicClass:
> NO_ARG = object()
>
> @staticmethod
> def __getattribute__(attr):
> def method(x=MagicClass.NO_ARG):
> if x is MagicClass.NO_ARG:
> return lambda x: getattr(x, attr)()
> return getattr(x, attr)
> return method
>
> @staticmethod
> def __getitem__(attr):
> return lambda x: x[attr]
>
> magic = MagicClass()
>
> print(list(map(magic.upper(), ["abc", "def"]))) # ['ABC', 'DEF']
> print(list(map(magic.real, [1j, 2, 3+4j]))) # [0.0, 2, 3.0]
> print(list(map(magic[0], ["abc", "def"]))) # ['a', 'd']
>
> You could also use None instead of that NO_ARG thingy, because you
> most likely won't want to get any attributes of None objects, but that
> wouldn't produce proper errors incase you do anyways.
>
> With metaclasses you propably could also make it work directly on the
> class without the need of a magic instance.
>
> Benedikt
>
> Am 08.03.2019 um 19:07 schrieb Jonathan Fine:
>> Hi Samuel
>>
>> Interesting idea, and certainly addresses a real problem, if you find
>> yourself creating lots of lambda expressions. But in my first opinion,
>> not so useful that it merits adding to the syntax of Python.
>>
>> (Even if I never use it, it puts an extra burden on me when scanning
>> Python code. Something that used to look like a syntax error is now
>> valid. That's more work for me.)
>>
>> However, you can already achieve something similar, and perhaps more
>> expressive. It is possible to define an object 'magic' such that
>> fn = magic.upper
>> fn = lambda x: x.upper()
>> are effectively equivalent.
>>
>> And this can be done now. No need for a PEP and a new version of
>> Python. And available for those who have to use some fixed already
>> existing Python versions.
>>
>> I hope you'd be interesting in coding this up yourself. I'd have a
>> limited amount of time to help you, but it would put you on a good
>> learning curve, for fundamentals of the Python object model.
>>
More information about the Python-ideas
mailing list