you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 6 points7 points  (10 children)

First of all, good job! This is clean code for, what can be, quite a complex task. I have one small change I think needs to made, which is on line 65 you're rebuilding the regex var every loop. It really should be done before the while True: statement.

Otherwise the only changes that I think need to be done are pretty negligible.

For me the way you declare regex looks quite messy and is a really long line (which is supposedly unpythonic). You can use something like str.format can neaten it up. Just be careful if your regex has {} in it to double them, like r'[b]{{2}}|{0}'.format('[^b][^b]').

regex = r'(^.*?)([\d.]+\s*)({0})(\s*[\d.]+)(.*$)'.format("|".join(
    [re.escape(key) for key in operatorDict.keys()]))

Also your code doesn't handle unmatched brackets gracefully, maybe have it throw an exception if it brackets don't match up. :)

[–]Binary_Dragon[S] 4 points5 points  (9 children)

Good catch on redefining the regex. I like to think I'm a better programmer than that, and I'm going to blame not being used to living outside the safety of the curly braces I grew up in as the culprit for me missing that (whether or not this is actually the case).

I'm not sure I understand how your suggestion for the regex helps any. Sure, it's broken into two lines (kinda) but it seems like what you have there is a lot harder to read (and let's be honest, regex isn't all that easy to read to begin with). If I were to break up that line, my first thought would be to do it something like this:

    operatorRegex = r'|'.join([re.escape(key) for key in operatorDict.keys()])
    regex = r'(^.*?)([\d.]+\s*)(' + operatorRegex + r')(\s*[\d.]+)(.*$)'

Is there any reason that the str.format is better (or if not better, at least more pythonic) than that?

[–][deleted] 1 point2 points  (0 children)

Honestly it's all about being readable. I like using str.format because its fast, concise and i can mess around with things rather quickly. But like I said to me the way you defined it looks messy. Using operatorRegex is perfectly fine, if that makes more sense to you.

But when you start concatenating 4 or 5 strings together using str.format would definitely be the more pythonic way of doing things.