Suppose I’m writing a simple parser. It has a dispatcher, which calls the corresponding parsing functions depending on the type of the input expression.
def dispatcher(expression):
m = pattern1.match(expression):
if m is not None:
handle_type1(expression, m)
# ... other types
My question is, is there anyway to combine the matching and checking for None? I mean, something like the following C code:
void dispatcher(char *expression)
{
if ((m = pattern1.match(expression)) != NULL) {
// ... handle expression type 1
}
else if ((m = pattern2.match(expression)) != NULL) {
// ... handle expression type 2
}
// ... other cases
}
Thanks!
This isn’t really about combining pattern matching with checking for none, it’s about whether you can assign to a variable and evaluate the result of that assignment in one expression, because pattern.match() call could be any function returning a value.
And the answer in general is no, because in Python assignment is a statement, not an expression as it is in C.
The only difference I can see in this case is that you save yourself an extra carriage return, which isn’t so useful. The assign-and-compare idiom is more useful in loops, but in Python you just have to do it over two lines (using break if necessary).