Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python initialize var to None?

What's the difference?

myVar: myCustomClassType 

vs.

myVar: myCustomClassType = None

I ask because Pycharm inspector squawks w/ the latter:

Expected type 'myCustomClassType', got 'None' instead

I understand that None is an object too and so therefore this inspection is stating that there is a type clash. My question is which is better form?

like image 856
JDOaktown Avatar asked Dec 18 '22 17:12

JDOaktown


1 Answers

The first is an example of Variable Annotation, where you use type hints to let type checkers know to associate an identifier (in a particular scope) with some type.

The difference between the two is that

myVar: myCustomClassType 

does not assign any value to myVar, while the second does. If you intend for myVar to have either a None value or a myCustomClassType value, you should use the Optional generic type from the typing module:

from typing import Optional 

myVar: Optional[myCustomClassType]

If your variable should only hold myCustomClassType values, then you should use the first variant and be sure to assign a value before using it.

like image 157
Patrick Haugh Avatar answered Dec 22 '22 17:12

Patrick Haugh