Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

How would you do traits in Python?


Python has a trait-like system. It's called "abstract base classes": 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.


Protocols, too (they are defined on top of ABCs)

https://typing.python.org/en/latest/spec/protocol.html#proto...


Protocols are definitely the closest thing to traits in Python. ABC are pretty much OoO interfaces.


I'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.


there were "traits" in python :/ . Search for pyprotocols.

(searching myself.. not much left of it)

2004 - https://simonwillison.net/2004/Mar/23/pyprotocols/

some related rejected PEP .. 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..


Possibly Guido, in that rejection, was talking about what ended up as ABCs, original PEP: 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/




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: