I am trying to specify the type for an instance variable using PEP 484's python 2 syntax. However, I haven't found any way to add types without initializing the variable in python 2, equivalent to the following python 3:
value: int
My normal work around for this is to declare the type of the variable in __init__ when instantiating the variable. However, this doesn't work for Protocols where the type of the instance variable should be part of the Protocol (types in __init__ seem to not count). Here's an example in Python 3 where I use a default implementation:
from typing_extensions import Protocol
class A(Protocol):
value: int
def get_value(self) -> int:
return self.value
This would then highlight errors if value isn't initialized properly:
class B(A):
pass
B() # error: Cannot instantiate abstract class 'B' with abstract attribute 'value'
However, converting this to python 2 type comments fails to pass mypy. It gives the same error with or without the __init__ declaration.
class A(Protocol):
def __init__(self):
# type: () -> None
self.value = 0 # type: int
def get_value(self):
# type: () -> int
return self.value # error: "A" has no attribute "value"
Is there some special syntax for declaring variable types without initializing them in python 2?
typing_extensionsin 2.7 rather thantyping.