Last active
September 29, 2016 14:52
-
-
Save mitsuse/93eddc1d14e4621066a1337ca63c86f9 to your computer and use it in GitHub Desktop.
An example of forward reference in 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 Generic | |
from typing import Optional | |
from typing import TypeVar | |
T = TypeVar('T') | |
class Box(Generic[T]): | |
def __init__(self, value: Optional[T]) -> None: | |
self.__value = value | |
# @classmethod | |
# def empty(c) -> Box[T]: # NG in Python 3.5.2: NameError: name 'Box' is not defined | |
# return c(None) | |
@classmethod | |
def empty(c) -> 'Box[T]': # OK: python/mypy #2020 | |
return c(None) | |
# @classmethod | |
# def empty(c) -> 'Box[T]': | |
# return 1 # NG in mypy: Incompatible return value type (got "int", expected Box[T]) | |
@property | |
def value(self) -> Optional[T]: | |
return self.__value | |
b = Box(10) | |
print(b.value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Error when referencing a class within its init method · Issue #2020 · python/mypy python/mypy#2020