Rewriting this in Python