Search code examples
pythonpycharmnonetype

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?


Solution

  • 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.