I love the typechecker in Pylance (VS Code), but there seems to be a situation that I must choose between ignoring a Pylance warning and best practice for class variable declaration.
Many times, class variables are initialized using a None
type in the class constructor, and the variable is set later. For example:
class Person:
def __init__(self) -> None:
self.name:str = None
def setName(self, name:str) -> None:
self.name = name
In this case, Pylance gives the following error on the assignment self.name:str = None
:
Cannot assign member "name" for type "Person"
Expression of type "None" cannot be assigned to member "name" of class "Person"
Type "None" cannot be assigned to type "str"
Is there any way to declare self.name
in the constructor in such a way that a value is not needed and Pylance is happy?
EDIT: Several have suggested the use of typing.Optional
to suppress this Pylance warning. However, if another member function is created to return self.name
and guarantee that it is returning an instance of str
, another Pylance error is generated. See the following example:
class Person:
def __init__(self) -> None:
self._name:Optional[str] = None
@property
def name(self) -> str:
return self._name
@name.setter
def name(self, name:str) -> None:
self._name = name
In this case, Pylance generates the error:
(variable) _name: str | None
Expression of type "str | None" cannot be assigned to return type "str"
Type "str | None" cannot be assigned to type "str"
Type "None" cannot be assigned to type "str"
Ideally, there would be some way to initially "allocate" self._name
in the constructor in such a way that its only allowed type is str
but is not given any value. Is this possible?