Wrangling the typing PEPs
Wrangling the typing PEPs
Posted Dec 16, 2021 21:44 UTC (Thu) by NYKevin (subscriber, #129325)In reply to: Wrangling the typing PEPs by atnot
Parent article: Wrangling the typing PEPs
If you are writing Y yourself, you can fix this by using whatever annotation you used on Y's constructor, and you can even set up a convenient TypeAlias for it if desired.
Posted Dec 16, 2021 23:23 UTC (Thu)
by atnot (subscriber, #124910)
[Link] (2 responses)
So for example, you could have Into<String> implemented for Paths, or From<Path> implemented for Strings, it works exactly the same either way. There is no common way to do this in python right now. Although it could probably be built from two existing features:
- The constructor/dunder pair I mentioned previously. Functions like float() will attempt to convert the object into bytes using predefined conversions. If that fails it will ask the object to convert itself using __float__.
Posted Dec 17, 2021 6:34 UTC (Fri)
by NYKevin (subscriber, #129325)
[Link] (1 responses)
However, classes are first class in Python, so you can absolutely do this already without using dunder names. Just write a.into(MyType), and it will pass the class object. Now the only hard part is convincing everyone that .into() should be spelled like that (more common is .as_foo() where the type is hard-coded into the method name).
Posted Dec 17, 2021 10:28 UTC (Fri)
by atnot (subscriber, #124910)
[Link]
Wrangling the typing PEPs
- Operators, where a + b will attempt to call a.__add__(b) and if that fails b.__radd__(a). Similarly, it could call a.__into__(MyType) and MyType.__from__(a) or even MyType(a) as you mentioned.
Wrangling the typing PEPs
Wrangling the typing PEPs