5

Having moved from Perl to Python one of the things I miss is "Deparse". It not only reformats perl code, but it reduces the number of parens and even changes older features to equivalent newer features.

For example:

$ perl -MO=Deparse -e 'if (($x == $b) || ($foo == $bar )) { &thing };'
if ($x == $b or $foo == $bar) {
    &thing;
}
-e syntax OK

Notice that it not just formats it, it removed unnecessary parens and turned older syntax (||) to newer syntax (or).

Is there anything similar for Python?

brian d foy
  • 129,424
  • 31
  • 207
  • 592
TomOnTime
  • 4,175
  • 4
  • 36
  • 39
  • 2
    [This](http://stackoverflow.com/questions/2625294/how-do-i-autoformat-some-python-code-to-be-correctly-formatted) might help. – devnull Apr 29 '14 at 06:25
  • 1
    There's also [2to3](https://docs.python.org/2/library/2to3.html) which updates 2.x code to be compliant with 3.x, but I'm not aware of anything similar which works across minor versions. – Matthew Trevor Apr 29 '14 at 06:56
  • 1
    Does this answer your question? [How do I autoformat some Python code to be correctly formatted?](https://stackoverflow.com/questions/2625294/how-do-i-autoformat-some-python-code-to-be-correctly-formatted) – knittl Oct 30 '22 at 20:19
  • `||` isn't "old" and `or` isn't "new". They just have different precedence. Deparse prints out the parse tree that the original code is internally compiled to... at some point in that process, converting from high-precedence `||` + parens to low-precedence `or` was done. – Shawn Nov 05 '22 at 23:07
  • Correct. The replacement was done to take advantage of the precedence of `or`, thus eliminating many parens. Excellent point. I was sloppy in my language and you are absolutely correct. (That said... I should point out that the code in the example was written back before Perl had the `or` operator and I used Deparse to upgrade to the newer and better way of doing things. However, it is likely that a large fraction of the people reading this page weren't born when Perl didn't have `or`.) – TomOnTime Nov 07 '22 at 14:38

0 Answers0