gtalarico / pyairtable

Python Api Client for Airtable
https://pyairtable.readthedocs.io
MIT License
784 stars 138 forks source link

Add `orm.fields.RequiredTextField`, etc. for fields which cannot be null #363

Closed mesozoic closed 6 months ago

mesozoic commented 7 months ago

We have several use cases where we want to

  1. ensure we do not store a null value to Airtable,
  2. squawk loudly if a field value in Airtable happens to be null, and
  3. assume a non-null value for type checking.

Our code winds up being peppered with "if value is None, do something, else ..." conditions, and it would be easier if we could declare that as a type checked property of the field. This branch adds support for that.

For example, given this code:

from pyairtable.orm import Model, fields as F

class User(Model):
    class Meta:
        ...
    user_id = F.RequiredNumberField("ID")

The following will all raise an exception:

>>> User(user_id=None)
Traceback (most recent call last):
  ...
MissingValue: User.user_id does not accept empty values

>>> r = User.from_record(fake_record(ID=123))
>>> r.user_id
123
>>> r.user_id = None
Traceback (most recent call last):
  ...
MissingValue: User.user_id does not accept empty values

>>> r = User.from_record(fake_record(ID=None))
>>> r.user_id
Traceback (most recent call last):
  ...
MissingValue: User.user_id received an empty value

It would have been simpler to implement this as a flag on the field's constructor, but with that approach I couldn't find a way to get mypy to understand that the type of r.user_id is int and not Optional[int].

codecov[bot] commented 7 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 100.00%. Comparing base (1040512) to head (e969df6).

Additional details and impacted files ```diff @@ Coverage Diff @@ ## main #363 +/- ## ========================================= Coverage 100.00% 100.00% ========================================= Files 24 24 Lines 2379 2406 +27 ========================================= + Hits 2379 2406 +27 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.