Skip to content

Instantly share code, notes, and snippets.

@mmajewsk
Created February 6, 2019 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmajewsk/f076f9a8b1edc8d14a01c69b477411ec to your computer and use it in GitHub Desktop.
Save mmajewsk/f076f9a8b1edc8d14a01c69b477411ec to your computer and use it in GitHub Desktop.
Dynamic type hinting in python
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