Created
October 26, 2014 21:28
-
-
Save borman/0b42f213a717c7b55557 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
def unary(symbol, priority): | |
# XXX: BRAIN DAMAGE HAZARD AHEAD | |
# Consider prioritize's argument: what's it for? | |
# Isn't it expected to be a number? | |
# How dare it work and work correctly? | |
# Turns out, Python mixed-type comparison semantics are exploited in an | |
# awkward way. Python specifies that when no other rules apply, e.g. no | |
# overridden comparison magic-methods on any side, it falls back to | |
# comparing both sides' type names. | |
# One could grep CPython sources for `default_3way_compare' function that | |
# defines comparison logic. It also turns out that when comparing a number | |
# vs. a non-number, number has an _empty_ type name. | |
# As one may observe, '' is less than 'function' | |
# Thus, for all int values ``v`` holds: | |
# - v < prioritize | |
# - prioritize > v | |
# - prioritize == prioritize | |
# So, ``prioritize`` is effectively is used as an `infinity' constant. | |
@prioritize(prioritize) | |
def visit(self, node): | |
yield symbol | |
child = self.visit(node.expr) | |
if child.priority < priority: | |
yield '(' | |
yield child | |
yield ')' | |
else: | |
yield child | |
return visit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment