Home > Net >  Why does Pydantic evaluate Optional values after or as None?
Why does Pydantic evaluate Optional values after or as None?

Time:01-12

I have a method which returns an instance of a class depending on a user's successful authentication.

account: Optional[Account] = await Account.authenticate(email, password)
return account or account.dict()

From my understanding, since None type is Falsey any occurance of account after the or keyword should be of type Account.

Any insight into why this is reporting an error would be greatly appreciated.

I have already looked for other instances in Pylance's GitHub issues for values after or being reported as None.

CodePudding user response:

Your IDE is correct.

Consider what happens when the authenticate() method returns None. You return:

account or account.dict()

It doesn't return account, as you state, because account is falsy. However, you then call None.dict(), which would be a typing error.

You should change account.dict() to some value that doesn't invoke an instance method of None, but what that value is depends on context that isn't provided in the question.

  • Related