Created
August 14, 2016 07:24
-
-
Save HerringtonDarkholme/3c821ba02ac0c1ddfb9300d08cbe8a2c to your computer and use it in GitHub Desktop.
literal style type annotation experiment in Python3
This file contains hidden or 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
from typing import Union, TypeVar, _type_check, TypingMeta | |
import builtins | |
class MyTypingMeta(type): | |
def __or__(self, tpe): | |
return Union[self, tpe] | |
class MyTypeVar(TypeVar, metaclass=TypingMeta, _root=True): | |
def __pos__(self): | |
self.__covariant__ = True | |
return self | |
def __neg__(self): | |
self.__contravariant__ = True | |
return self | |
def __lt__(self, bound): | |
self.__bound__ = _type_check(bound, 'Bound must be a type') | |
return self | |
class ShortCut: | |
def __getattr__(self, name): | |
return MyTypeVar(name) | |
s = ShortCut() | |
class mystr(str, metaclass=MyTypingMeta): pass | |
class myint(int, metaclass=MyTypingMeta): pass | |
class myfloat(float, metaclass=MyTypingMeta): pass | |
# class mybool(bool, metaclass=MyTypingMeta): pass | |
class mybytes(bytes, metaclass=MyTypingMeta): pass | |
class myobject(object, metaclass=MyTypingMeta): pass | |
builtins.str = mystr | |
builtins.int = myint | |
builtins.float = myfloat | |
# builtins.bool = mybool | |
builtins.bytes = mybytes | |
builtins.object = myobject | |
# literal style union type | |
def print_int_or_str(a: int | str) -> None: | |
print(a) | |
class User(object): pass | |
# literal style type variable | |
T = +s.T < User | |
print(repr(T)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment