ASEM000 / pytreeclass

Visualize, create, and operate on pytrees in the most intuitive way possible.
https://pytreeclass.rtfd.io/en/latest
Apache License 2.0
42 stars 2 forks source link

Annotated callbacks #62

Closed ASEM000 closed 1 year ago

ASEM000 commented 1 year ago

move callbacks to inside typing.Annotated instead of field(...callbacks=[...]) use field_name: Annotated[type, *callbacks]. check PEP 593 and https://github.com/annotated-types/annotated-types for motivation.

import jax
import pytreeclass as pytc
# python 3.9 and above
from typing import Annotated
# python 3.8
# from typing_extensions import Annotated

class PositiveInt:
    def __call__(self,value):
        if not isinstance(value, int):
            raise TypeError("Value must be an integer")
        if value <= 0:
            raise ValueError("Value must be positive")
        return value

class Tree(pytc.TreeClass):
    in_features: Annotated[int, PositiveInt()]

tree = Tree(1)
# no error

try:
    tree = Tree(0)
except ValueError as e:
    print(e)
# Error for field=`in_features`:
# Value must be positive

try:
    tree = Tree(1.0)
except TypeError as e:
    print(e)
# Error for field=`in_features`:
# Value must be an integer
codecov[bot] commented 1 year ago

Codecov Report

Patch coverage: 100.00% and project coverage change: -0.01 :warning:

Comparison is base (d399e78) 98.44% compared to head (44db470) 98.44%.

Additional details and impacted files ```diff @@ Coverage Diff @@ ## main #62 +/- ## ========================================== - Coverage 98.44% 98.44% -0.01% ========================================== Files 13 13 Lines 2378 2373 -5 ========================================== - Hits 2341 2336 -5 Misses 37 37 ``` | [Impacted Files](https://app.codecov.io/gh/ASEM000/PyTreeClass/pull/62?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Mahmoud+Asem) | Coverage Δ | | |---|---|---| | [pytreeclass/\_\_init\_\_.py](https://app.codecov.io/gh/ASEM000/PyTreeClass/pull/62?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Mahmoud+Asem#diff-cHl0cmVlY2xhc3MvX19pbml0X18ucHk=) | `100.00% <100.00%> (ø)` | | | [pytreeclass/\_src/code\_build.py](https://app.codecov.io/gh/ASEM000/PyTreeClass/pull/62?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Mahmoud+Asem#diff-cHl0cmVlY2xhc3MvX3NyYy9jb2RlX2J1aWxkLnB5) | `100.00% <100.00%> (ø)` | | | [tests/test\_treeclass.py](https://app.codecov.io/gh/ASEM000/PyTreeClass/pull/62?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Mahmoud+Asem#diff-dGVzdHMvdGVzdF90cmVlY2xhc3MucHk=) | `99.07% <100.00%> (-0.02%)` | :arrow_down: |

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Do you have feedback about the report comment? Let us know in this issue.