Created
February 6, 2019 21:10
-
-
Save mmajewsk/f076f9a8b1edc8d14a01c69b477411ec to your computer and use it in GitHub Desktop.
Dynamic type hinting in python
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
import random | |
from typing import get_type_hints | |
class Bar: | |
def foo(self, a: str) -> int: | |
return 1 | |
class fakedict(dict): | |
def __getattribute__(self, *args, **kwargs): | |
if random.randint(0,1) == 1: | |
dict.__setitem__(self,'a', int) | |
else: | |
dict.__setitem__(self, 'a', str) | |
return dict.__getattribute__(self, *args, **kwargs) | |
setattr(Bar.foo, '__annotations__', fakedict({'a': str, 'return': int})) | |
print(get_type_hints(Bar.foo)) | |
print(get_type_hints(Bar.foo)) | |
print(get_type_hints(Bar.foo)) | |
print(get_type_hints(Bar.foo)) | |
print(get_type_hints(Bar.foo)) | |
print(get_type_hints(Bar.foo)) | |
print(get_type_hints(Bar.foo)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment