Know what’s cool? Nested functions.
The other day, as I was making this craaaazy dance parser (that’s getting more and more convoluted by the minute), Alan suggested a really baller way of organizing it: using a bunch of little mini-parser functions that all look for something specific in your text, and smooshing related parsers together into one macro-parser that runs all of them in turn until one returns something. In Alan’s lovely mock-up code that I’m shamelessly copying over here, that might look like this:
def contains_an_a(input):
return input.find("a") > -1
def contains_a_b(input):
return input.find("b") > -1
def one_of(parsers):
def parser(input):
for p in parsers:
result = p(input)
if result:
return result
return parser
contains_an_a_or_a_b = one_of([contains_an_a, contains_a_b])
The handy thing about having all of these bite-size functions is that none of them gets too crazy bulky, and also, since they’re functions (and not dicts like I was using earlier), I can use regexes in them! I’m also jamming on the idea of passing functions to other functions, so I made an even bigger function called use_parser
that takes a parser, a default value, and an ‘ask’, which it uses to ask the user (via raw_input) what the value should be. This way, I can take a single parser and customize it in a variety of ways. Say for example I have a distance parser: for do-si-dos and gypsies it should default to False (because those moves don’t necessarily need to take a distance) and for allemandes it should ask the user, “what’s the value of ‘dist’ here?”