Last active
October 1, 2016 07:48
-
-
Save mitsuse/6adab0e27975db419ab470d795531139 to your computer and use it in GitHub Desktop.
Failure in type checking for `__new__` with mypy.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# coding: utf-8 | |
from typing import Optional | |
class Uint(object): | |
def __new__(c, value: int) -> 'Optional[Uint]': | |
if value < 0: | |
return None | |
else: | |
return super().__new__(c) | |
def __init__(self, value: int) -> None: | |
self.__value = value | |
@property | |
def value(self) -> int: | |
return self.__value | |
x = Uint(10) # An instance of `Uint` | |
y = Uint(-10) # None | |
print(x.value) | |
print(y.value) # This causes AttributeError, but mypy cannot detect. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# coding: utf-8 | |
from typing import Optional | |
class Uint(object): | |
def __init__(self, value: int) -> None: | |
if value < 0: | |
raise ValueError | |
self.__value = value | |
@staticmethod | |
def new(value: int) -> Optional[Uint]: | |
try: | |
return Uint(value) | |
except: | |
return None | |
@property | |
def value(self) -> int: | |
return self.__value | |
x = Uint.new(10) # An instance of `Uint` | |
y = Uint.new(-10) # None | |
# print(x.value) # mypy: error | |
# print(y.value) # mypy: error | |
if x is not None: print(x.value) | |
if y is not None: print(y.value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
mypy --strict-optional --disallow-untyped-defs uint.py
with mypy 0.4.4.