Martin Melka
Martin Melka

Reputation: 7789

How to typehint 'return type or no return' in Pycharm

How do I typehint that a function may either return a value or not return anything? What seems to be correct to me is being reported by PyCharm.

def func() -> Optional[Dict]:

This results in a warning on the return type when the function does not return anything:

Expected to return 'Optional[dict]', got no return

But explicitly returning None works:

def func() -> Optional[Dict]:
    return None

This is all fine with PyCharm. It seems that "no return" is treated differently from return None even though to my understanding those two should be the same.

See the image for all three variants:

enter image description here

What is the correct way to do this? In my use case the function is a class method and its implementations in subclasses will either return None or a value. Having to write return None in all the subclasses that don't need it is redundant and I want to avoid that.

Upvotes: 0

Views: 775

Answers (1)

Hirsch Alter
Hirsch Alter

Reputation: 47

What is the correct way to do this?

IMHO, if your function sometimes returns data (which is implied by the Optional[Dict], then when your function returns nothing, explicitly indicating that with return None clearly communicates that you didn't forget (remember: explicit is better than implicit).

I think PyCharm assumes that if you indicate a (sometimes) not None return type and you have a branch without an explicit return, then you probably made a mistake. Unfortunately, I cannot back that up with PyCharm documentation.

Upvotes: 2

Related Questions