Last active
January 17, 2018 00:07
-
-
Save llllllllll/394a7bce91a9ccab66d700dd808783be to your computer and use it in GitHub Desktop.
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
""" | |
In [1]: from the_worst_way import why_though | |
In [2]: import ast | |
In [3]: code = ''' | |
...: if a == 1 and a == 2 and a == 3: | |
...: print('ayy') | |
...: else: | |
...: print('lmao') | |
...: ''' | |
In [4]: exec(compile(why_though.visit(ast.parse(code)), '<string>', 'exec')) | |
ayy | |
""" | |
import ast | |
@object.__new__ | |
class why_though(ast.NodeTransformer): | |
@staticmethod | |
def _matches(node): | |
if not isinstance(node.op, ast.And): | |
return False | |
try: | |
a, b, c = node.values | |
except ValueError: | |
return False | |
for n, subnode in enumerate(node.values, 1): | |
if not (isinstance(subnode, ast.Compare) and | |
isinstance(subnode.left, ast.Name) and | |
subnode.left.id == 'a' and | |
len(subnode.ops) == 1 and | |
isinstance(subnode.ops[0], ast.Eq) and | |
len(subnode.comparators) == 1 and | |
isinstance(subnode.comparators[0], ast.Num) and | |
subnode.comparators[0].n == n): | |
return False | |
return True | |
def visit_BoolOp(self, node): | |
return ( | |
ast.copy_location(ast.NameConstant(value=True), node) | |
if self._matches(node) else | |
node | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment