[Python-ideas] Attribute-Getter Syntax Proposal
Chris Angelico
rosuav at gmail.com
Fri Mar 8 17:12:41 EST 2019
On Sat, Mar 9, 2019 at 9:09 AM Benedikt Werner
<1benediktwerner at gmail.com> wrote:
>
> 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.
Rather than using map in this way, I would recommend a list comprehension:
print([x.upper() for x in ["abc", "def"]])
print([x.real for x in [1j, 2, 3+4j]])
print([x[0] for x in ["abc", "def"]])
No magic needed.
ChrisA
More information about the Python-ideas
mailing list