Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nullable MultiCollationTextField type-checking #152

Open
kdmccormick opened this issue Feb 6, 2024 · 0 comments · May be fixed by #249
Open

Nullable MultiCollationTextField type-checking #152

kdmccormick opened this issue Feb 6, 2024 · 0 comments · May be fixed by #249
Assignees

Comments

@kdmccormick
Copy link
Member

kdmccormick commented Feb 6, 2024

Context: #149 (comment)

Setting null=True on a Django TextField or CharField successfully tells mypy that the field's value can be None:

class MyModel(models.Model):
    text = TextField(..., null=True)

foo = MyModel(text=None)  # all good

But setting null=True this repo's custom MultiCollation(Text|Char)Field, which is a subclass of Django's (Text|Char)Field, does not lead mypy to the same conclusion:

class MyModel(models.Model):
    text = MultiCollationTextField(..., null=True)

foo = MyModel(text=None)  # error: Incompatible type for "text" of "Content" (got "None", expected "Union[str, Combinable]") [misc]

It's ugly, but we can work around this currently by explicitly annotating the type of text:

class MyModel(models.Model):
    text: models.TextField[str | None, str | None] = MultiCollationTextField(..., null=True)

foo = MyModel(text=None)  # all good

Side note: We could work around this now using # type: ignore wherever we set text=None, but it's not great, because .text should in fact have the type str|None, and thus it'd be valuable for mypy to yell at us if we try to use it as if it's type is just str.

I believe that the solution involves some wrangling of generic type arguments between MultiCollationTextField and TextField. We also might end up needing two separate sets of classes: MultiCollation(Text|Char)Field and NullableMultiCollation(Text|Char)Field.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant