5 ms·
How would you do traits in Python?
by fouronnes3 1y ago
How would you do traits in Python?
- echelon 1y agoI'd really need to think long and hard about it, but my initial feeling is that we'd attach them to data classes or a similar new construct. I don't think you'd want to reason about the blast radius with ordinary classes. Granted, that's more language complexity, creates two unequal systems, and makes much more to reason about. There's a lot to juggle. As much fun as putting a PEP together might be, I don't think I have the bandwidth to do so. I would really like to see traits in Python, though.
- svilen_dobrev 1y agothere were "traits" in python :/ . Search for pyprotocols. (searching myself.. not much left of it) 2004 - https://simonwillison.net/2004/Mar/23/pyprotocols/ https://simonwillison.net/2004/Mar/23/pyprotocols/ some related rejected PEP .. https://peps.python.org/pep-0246/ https://peps.python.org/pep-0246/ talking about something new to be expected.. in 2001?2005? no idea did it happen and which one would that be..
- dragonwriter 1y agoPossibly Guido, in that rejection, was talking about what ended up as ABCs, original PEP: https://peps.python.org/pep-3119/ https://peps.python.org/pep-3119/ Further work was done in this area, building on ABCs, with Protocols, original PEP: https://peps.python.org/pep-0544/ https://peps.python.org/pep-0544/
- vaylian 1y agoPython has a trait-like system. It's called "abstract base classes": https://docs.python.org/3/library/abc.html https://docs.python.org/3/library/abc.html The abstract base class should use the @abstractmethod decorator for methods that the implementing class needs to implement itself. Obviously, you can also use abstract base classes in other ways, but they can be used as a way to define traits/interfaces for classes.
- dragonwriter 1y agoProtocols, too (they are defined on top of ABCs) https://typing.python.org/en/latest/spec/protocol.html#protocols https://typing.python.org/en/latest/spec/protocol.html#proto...
- gpderetta 1y agoProtocols are definitely the closest thing to traits in Python. ABC are pretty much OoO interfaces.