Skip to content

Instantly share code, notes, and snippets.

@JustinSDK
Last active August 1, 2018 01:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinSDK/869369b5da1ce55c5457135c5bfbe50e to your computer and use it in GitHub Desktop.
Save JustinSDK/869369b5da1ce55c5457135c5bfbe50e to your computer and use it in GitHub Desktop.
simple_type_checking.py
import sys, re, ast
type_hints_re = re.compile(r'([a-zA-Z]+):\s*([a-zA-Z]+)')
code = '''
"""x: int"""
x = 2
'''
node = ast.parse(code)
class AssignVisitor(ast.NodeVisitor):
def __init__(self):
self.types = {}
def visit_Str(self, node):
# parse node.s
matcher = type_hints_re.search(node.s)
name = matcher.group(1)
tpe = matcher.group(2)
self.types[name] = getattr(sys.modules['builtins'], tpe)
def visit_Assign(self, node):
target = node.targets[0]
value = node.value
t = self.types[target.id]
if not (hasattr(value, 'n') and isinstance(value.n, t)):
raise TypeError('type...XD')
AssignVisitor().visit(node)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment