Skip to content

Instantly share code, notes, and snippets.

@mitsuse
Last active October 1, 2016 07:48
Show Gist options
  • Save mitsuse/6adab0e27975db419ab470d795531139 to your computer and use it in GitHub Desktop.
Save mitsuse/6adab0e27975db419ab470d795531139 to your computer and use it in GitHub Desktop.
Failure in type checking for `__new__` with mypy.
#!/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.
#!/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)
@mitsuse
Copy link
Author

mitsuse commented Oct 1, 2016

mypy --strict-optional --disallow-untyped-defs uint.py with mypy 0.4.4.

@mitsuse
Copy link
Author

mitsuse commented Oct 1, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment