feat: python traits

master
JimZhang 1 month ago
commit 204518c406

163
.gitignore vendored

@ -0,0 +1,163 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm-project.org/#use-with-ide
.pdm.toml
.pdm-python
.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
.idea

@ -0,0 +1,70 @@
# PyTraits
## Introduction
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.
## Installation
You can install PyTraits using pip:
```bash
pip install pytraits
```
## Usage
To use PyTraits, first, you need to define a protocol using the `runtime_checkable` annotation:
```python
from typing import runtime_checkable
@runtime_checkable
class Printable:
def print(self):
pass
```
Then, you can use the `impl` annotation to implement the protocol for a class:
```python
from pytraits import impl, trait
class MyClass1: pass
@impl(Printable)
class MyClassImplPrintable(MyClass1):
def print(self):
print("从 MyClass 打印")
class MyClass2: pass
@trait
class MyClassTraitPrintable(MyClass2, Printable):
def print(self):
print("从 MyClass2 打印")
mc1: MyClass1 | Printable = MyClass1()
mc2: MyClass2 | Printable = MyClass2()
mc1.print()
mc2.print()
```
Now, `MyClass` implements the `Printable` protocol and can be used accordingly.
## Contributing
Contributions are welcome! If you find any issues or have suggestions for improvement, please open an issue or submit a pull request on GitHub.
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

@ -0,0 +1,67 @@
# PyTraits
## Introduction
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.
## Installation
You can install PyTraits using pip:
```bash
pip install pytraits
```
## Usage
使用 PyTraits首先需要使用 `trait` 注解定义一个协议:
```python
from typing import runtime_checkable
@runtime_checkable
class Printable:
def print(self):
pass
```
然后,可以使用`impl`或`trait`装饰器为已定义的类实现该协议:
```python
from pytraits import impl, trait
class MyClass1: pass
@impl(Printable)
class MyClassImplPrintable(MyClass1):
def print(self):
print("从 MyClass 打印")
class MyClass2: pass
@trait
class MyClassTraitPrintable(MyClass2, Printable):
def print(self):
print("从 MyClass2 打印")
mc1: MyClass1 | Printable = MyClass1()
mc2: MyClass2 | Printable = MyClass2()
mc1.print()
mc2.print()
```
现在,`MyClass` 实现了 `Printable` 协议,可以相应地使用。
## Contributing
Contributions are welcome! If you find any issues or have suggestions for improvement, please open an issue or submit a pull request on GitHub.
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

@ -0,0 +1,41 @@
[project]
name = "pytraits"
version = "0.1.0"
description = "python trait like rust"
authors = [
{name = "JimZhang", email = "zzl22100048@gmail.com"},
]
dependencies = []
requires-python = ">=3.10"
readme = "README.md"
license = {text = "MIT"}
[build-system]
requires = ["pdm-backend"]
build-backend = "pdm.backend"
[tool.pdm]
distribution = true
[tool.ruff]
exclude = [
"tests",
]
line-length = 120
select = [
"E",
"F",
"W",
"I"
]
target-version = "py310"
[tool.ruff.isort]
combine-as-imports = true
[tool.pdm.dev-dependencies]
dev = [
"setuptools>=69.0.3",
]

@ -0,0 +1,51 @@
import inspect
class TraitImplementError(RuntimeError):
def __init__(self, message):
super().__init__(message)
self.message = message
def check_is_subclass(implementor, protocol):
if not issubclass(implementor, protocol):
raise TraitImplementError(
f'implementor {implementor.__name__} is not a subclass of {protocol.__name__}')
def impl(protocol: type):
"""
Decorate a class to make it a trait implementation.
:param protocol: Protocol class to be decorated.
:return: decorator function
"""
def decorator(implementor: type):
implemented = implementor.__bases__[0]
implementor_methods = []
check_is_subclass(implementor, protocol)
p_module = protocol.__module__
for name, method in inspect.getmembers(protocol, inspect.isfunction):
if p_module == method.__module__:
implementor_methods.append((name, getattr(implementor, name)))
for name, method in implementor_methods:
setattr(implemented, name, method)
return decorator
def trait(implementor):
"""
Decorate a class to make it a trait implementation.
:param implementor: trait class to be decorated.
:return: None. Shadowing subclass
"""
implemented, protocol = implementor.__bases__
implementor_methods = []
check_is_subclass(implementor, protocol)
p_module = protocol.__module__
for name, method in inspect.getmembers(protocol, inspect.isfunction):
if p_module == method.__module__:
implementor_methods.append((name, getattr(implementor, name)))
for name, method in implementor_methods:
setattr(implemented, name, method)

@ -0,0 +1,65 @@
from typing import Protocol, runtime_checkable
from pytraits import trait, impl
from traits import ShortUrl
class MyUrl:
def __init__(self, url):
self.url = url
def url(self):
return self.url
@trait
class ShortUrlForMyUrl(MyUrl, ShortUrl):
def short_url(self):
return self.url[0]
class Ab:
def __init__(self, msg: str):
self.msg = msg
self.m0 = msg[0]
def foo(self):
print('foo', self.msg)
class Abc(Ab):
pass
@runtime_checkable
class BProtocol(Protocol):
def print_m0(self):
pass
@runtime_checkable
class DProtocol(Protocol):
def print_1(self):
pass
@impl(BProtocol)
class C(Abc):
def print_m0(self):
print('show', self.m0)
@trait
class D(Abc, DProtocol):
def print_1(self):
print('show', self.m0)
self.foo()
if __name__ == '__main__':
a: Ab | DProtocol = Abc('acb')
a.print_1()
my_url: MyUrl | ShortUrl = MyUrl('http://acb.com')
print(my_url.short_url())

@ -0,0 +1,7 @@
from typing import Protocol, runtime_checkable
@runtime_checkable
class ShortUrl(Protocol):
def short_url(self):
...
Loading…
Cancel
Save