diff --git a/jam/__init__.py b/jam/__init__.py index 7d54202..a64730b 100644 --- a/jam/__init__.py +++ b/jam/__init__.py @@ -59,7 +59,7 @@ def is_optional(annotation: typing.Type) -> bool: def unpack_optional_type(annotation: typing.Union) -> typing.Type: """Optional[Type] -> Type""" - return [t for t in annotation.__args__ if t is not NoneType][0] + return next(t for t in annotation.__args__ if t is not NoneType) def get_marshmallow_field(annotation): @@ -102,14 +102,19 @@ def get_fields_from_annotations(annotations): } +def _skip_fields_from_annotations(annotations, attrs): + return {attr_name: attr_value for attr_name, attr_value in attrs.items() + if attr_name not in annotations or attr_value is not None} + + class SchemaMeta(BaseSchemaMeta): def __new__(mcs, name, bases, attrs): - new_class = super().__new__( - mcs, - name, - bases, - {**attrs, **get_fields_from_annotations(attrs.get("__annotations__", {}))}, - ) + annotations = attrs.get("__annotations__", {}) + + attrs = _skip_fields_from_annotations(annotations, attrs) + attrs = {**get_fields_from_annotations(annotations), **attrs} + + new_class = super().__new__(mcs, name, bases, attrs) setattr(new_class, "_dataclass", dataclass(type(name, (), attrs))) return new_class diff --git a/jam/tests/test_annotation_mapping.py b/jam/tests/test_annotation_mapping.py index a26fb5d..71ed87e 100644 --- a/jam/tests/test_annotation_mapping.py +++ b/jam/tests/test_annotation_mapping.py @@ -61,3 +61,12 @@ class Response(Schema): optional_field: t.Optional[int] = None assert repr(Response().declared_fields["optional_field"]) == repr(fields.Integer()) + + +def test_strict_marshmallow_field(): + class Response(Schema): + basic_field: int + email_field: str = fields.Email(required=True) + + assert repr(Response().declared_fields["basic_field"]) == repr(fields.Integer(required=True)) + assert repr(Response().declared_fields["email_field"]) == repr(fields.Email(required=True)) diff --git a/project.ini b/project.ini index 8da9a4d..464abf5 100644 --- a/project.ini +++ b/project.ini @@ -1,5 +1,5 @@ [project] url = https://github.com/nonamenix/marshmallow-jam -version = 1.0.1 +version = 1.1.0 name = marshmallow-jam description = Some extra sweets for marshmallow. \ No newline at end of file