summaryrefslogtreecommitdiff
path: root/lib/sly/ast.py
blob: 05802bd4c0c53046914bffed10b23e53e10575d1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# sly/ast.py
import sys


class AST(object):
    @classmethod
    def __init_subclass__(cls, **kwargs):
        mod = sys.modules[cls.__module__]
        if not hasattr(cls, "__annotations__"):
            return

        hints = list(cls.__annotations__.items())

        def __init__(self, *args, **kwargs):
            if len(hints) != len(args):
                raise TypeError(f"Expected {len(hints)} arguments")
            for arg, (name, val) in zip(args, hints):
                if isinstance(val, str):
                    val = getattr(mod, val)
                if not isinstance(arg, val):
                    raise TypeError(f"{name} argument must be {val}")
                setattr(self, name, arg)

        cls.__init__ = __init__