connor-makowski / type_enforced

A pure python type enforcer for annotations. Enforce types in python functions and methods.
MIT License
45 stars 2 forks source link

Explicitly document + test dataclass support #40

Closed duckinator closed 2 days ago

duckinator commented 3 months ago

Hi!

I recently tried this with a dataclass, even though it wasn't documented, and it works.

It might make sense to document that, and add a test so it doesn't get unintentionally broken. :slightly_smiling_face:

Here's the example code I tried that wound up working:

from datetime import datetime
from typing import Tuple

from dataclasses import dataclass

import type_enforced

@type_enforced.Enforcer
@dataclass
class Delivery:
    timestamp: datetime
    dimensions: Tuple[int, int]

m = Delivery(timestamp=datetime.fromisoformat('2020-01-02T03:04:05Z'), dimensions=(10, 20))
print(repr(m.timestamp))
#=> datetime.datetime(2020, 1, 2, 3, 4, 5, tzinfo=datetime.timezone.utc)

print(m.dimensions)
#=> (10, 20)

m2 = Delivery(timestamp=datetime.fromisoformat('2020-01-02T03:04:05Z'), dimensions=['10', '20'])
# => [...]
# TypeError: (Delivery.__init__): Type mismatch for typed variable `dimensions`. Expected one of the following `[<class 'tuple'>]` but got `<class 'list'>` instead.
connor-makowski commented 2 days ago

Makes sense:

Closing with: dd5e91f5deae447f6fc37e1d69ebdcf5054d70ae 90f7f5e2e077cd79164621233a9da515a6072cb1