Python initialize var to None?

Viewed 3399

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?

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

A name with just an annotation is syntactically legal, but doesn't actually create a variable.

>>> foo: int
>>> foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined

The correct type for myVar would be Union[myCustomClassType,None] or its equivalent Optional[myCustomClassType], to allow for the assignment of None.

from typing import Optional

myVar: Optional[myCustomClassType] = None

Somewhat related, if you define a function like

def foo(bar: int = None):
    ...

mypy will silently "promote" the type of bar to Optional[int] based on the assigned default value. It doesn't appear to do the same in the case of a variable annotation, though. PyCharm appears to follow suit.

You need to do

myVar = None

without the type annotation. You can assign a myCustomerClassType instance later.

Related