Saturday, 10 April 2021

Dealing with lack of non-null assertion operator in Python

I would like to allow Mypy' strict_optional flag. However, consider this:

emails = [get_user(uuid).email for uuid in user_uuids]

where get_user could return None in theory, but in this use case, I know it can't (and am fine with getting an exception if it did). This would have to become:

emails = []
for uuid in user_uuids:
    user = get_user(uuid)
    assert user is not None
    emails.append(user.email)

In TypeScript, there's a non-null assertion operator which would allows you to just add a ! (as in getUser(uuid)!.email).

Is there any better or more elegant way to handle this problem?



from Dealing with lack of non-null assertion operator in Python

No comments:

Post a Comment