Skip to content

Instantly share code, notes, and snippets.

@mitsuse
Last active September 29, 2016 14:52
Show Gist options
  • Save mitsuse/93eddc1d14e4621066a1337ca63c86f9 to your computer and use it in GitHub Desktop.
Save mitsuse/93eddc1d14e4621066a1337ca63c86f9 to your computer and use it in GitHub Desktop.
An example of forward reference in mypy.
#!/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)
@mitsuse
Copy link
Author

mitsuse commented Sep 29, 2016

Error when referencing a class within its init method · Issue #2020 · python/mypy python/mypy#2020

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