[Python-ideas] Attribute-Getter Syntax Proposal
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":
> class MagicClass:
> NO_ARG = object()
> 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
> 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, ["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 for x in ["abc", "def"]])
No magic needed.
More information about the Python-ideas