Error: "get" is not a known attribute of "None" (reportOptionalMemberAccess)

I use PyRight to check my Django code. It complains about that


class FooForm(ModelForm):

    def clean(self):
        cleaned_data = super().clean()
        start = cleaned_data.get("start_date")  # <------- here

error: "get" is not a known attribute of "None" (reportOptionalMemberAccess)

I installed django-stubs.

How to make PyRight aware that cleaned_data is a dictionary?

Or is something wrong with my setup?

The clean() method of a ModelForm is expected to return a dictionary, from the perspective of a type checker like Pyright, the base class super().clean() is (probably, in general) not guaranteed to do so.

You can try to explicitly type-hint the cleaned_data variable.

class FooForm(ModelForm):

def clean(self) -> Dict[str, Any]:
    cleaned_data: Dict[str, Any] = super().clean()
    start = cleaned_data.get("start_date")

The django-stub annotates it with an optional, as we can see in the source code:

class BaseForm(RenderableFormMixin):
    # ...
    def clean(self) -> dict[str, Any] | None: ...

The issue is discussed in issue #1403:

Form subclasses are allowed to skip returning the dictionary, so the type in form needs to allow none. See previous issue #954. Please search the issue tracker before opening issues.

So you are allowed to override def clean() and return None, in fact a FormSet does that. Perhaps the programmer then should annotate it, but probably from a type-check point of view, it makes sense to make it optional.

Вернуться на верх