Last active
August 1, 2018 01:32
-
-
Save JustinSDK/869369b5da1ce55c5457135c5bfbe50e to your computer and use it in GitHub Desktop.
simple_type_checking.py
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 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