You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
JimZhang 204518c406 feat: python traits 2 months ago
src/pytraits feat: python traits 2 months ago
tests feat: python traits 2 months ago
.gitignore feat: python traits 2 months ago feat: python traits 2 months ago feat: python traits 2 months ago
pyproject.toml feat: python traits 2 months ago



PyTraits is a Python library that provides functionality similar to Rust traits. It allows you to define protocols using impl or trait annotations to specify the behavior that classes should implement.


You can install PyTraits using pip:

pip install pytraits


To use PyTraits, first, you need to define a protocol using the runtime_checkable annotation:

from typing import runtime_checkable

class Printable:
    def print(self):

Then, you can use the impl annotation to implement the protocol for a class:

from pytraits import impl, trait

class MyClass1: pass

class MyClassImplPrintable(MyClass1):
    def print(self):
        print("从 MyClass 打印")

class MyClass2: pass

class MyClassTraitPrintable(MyClass2, Printable):
    def print(self):
        print("从 MyClass2 打印")

mc1: MyClass1 | Printable = MyClass1()
mc2: MyClass2 | Printable = MyClass2()

Now, MyClass implements the Printable protocol and can be used accordingly.


Contributions are welcome! If you find any issues or have suggestions for improvement, please open an issue or submit a pull request on GitHub.


This project is licensed under the MIT License - see the LICENSE file for details.