Skip to content

Instantly share code, notes, and snippets.

@borman
Created October 26, 2014 21:28
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 borman/0b42f213a717c7b55557 to your computer and use it in GitHub Desktop.
Save borman/0b42f213a717c7b55557 to your computer and use it in GitHub Desktop.
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