Skip to content

Enfoced null checks for `SchemaField`

Pre-release
Pre-release

Choose a tag to compare

@surenkov surenkov released this 14 Sep 14:42
· 190 commits to master since this release

Enforced null checks for SchemaField

In the example below, typing linters should enforce type compatibility:

class BuildingMeta(pydantic.BaseModel):
    type: Optional[BuildingTypes]

class Building(models.Model):
    opt_meta: BuildingMeta = SchemaField(default={"type": "frame"}, null=True)
    meta: Optional[BuildingMeta] = SchemaField(default={"type": "frame"})

Pyright will complain on both fields:

sample_app/models.py:5:32 - error: Expression of type "BuildingMeta | None" cannot be assigned to declared type "BuildingMeta"
sample_app/models.py:6:40 - error: Expression of type "ST@SchemaField" cannot be assigned to declared type "BuildingMeta | None"

Mypy has more broaden resolution for latter check, but still be able to recognise first one:

sample_app/models.py:5: error: Incompatible types in assignment (expression has type "Optional[BuildingMeta]", variable has type "BuildingMeta")

Fixing field annotations will resolve issues on both checkers:

class Building(models.Model):
    opt_meta: Optional[BuildingMeta] = SchemaField(default={"type": "frame"}, null=True)
    meta: BuildingMeta = SchemaField(default={"type": "frame"})

The check also enforces default=None to have null=True param.

Relaxed restrictions on default= argument

In addition to null enforcement, typing checks allow arbitrary values for default= argument, as long as they are acceptable for pydantic's BaseModel.parse_obj method. Callables are also accepted, mimicking Django's field semantics.

Full Changelog: v0.1.10...v0.1.11