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

With Literal you can also do this:

    @dataclass
    class Message:
        event: Literal['message']
        msg: str
    
    @dataclass
    class File:
        event: Literal['file']
        url: str
    
    typedload.load(data, File | Message)
Where data is something like `{'event': 'message', 'msg': 'bla'}`.

After the load, you can trust that your objects are well formed and let mypy do its thing.

So types can be useful at runtime as well. Otherwise the alternative would be to use raw dictionary, which mypy can't check.

pydantic does a similar thing but it uses its own different typing, so it needs a mypy plugin or it flags everything as wrong.



For those who aren't familiar, typedload is a third party library: https://pypi.org/project/typedload/


You can also use TypedDict if you would normally use a raw dictionary but want the type checking.


Yes, but you still need a module like typedload to do the runtime checking.

TypedDict performs no checking by itself at runtime.

    class A(TypedDict):
        a: int


    A(d=32)
    # Returns {'d': 32}
    typedload.load({'d': 32}, A)
    # TypedloadValueError: Value does not contain fields: {'a'} which are necessary for type A


unlike fixed records, dictionaries access is impossible to optimise via JIT like PyPy




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

Search: