Sunday, July 28, 2019

Porting python 2 to python 3 (2to3) without unit tests.

The existing guides for porting python 2 to python 3 generally say "...then you run your unit tests and fix any problems you find." This is awkward if you don't have unit tests. While, you will not escape without testing, (perhaps by your angry users in production), you can save little time by:

  1. Before the conversion, compile your code to python 2 , to establish it isn't already broken 
  2. After the conversion, see if you can compile your code to python 3 
  3. After the conversion, run pylint --py3k 

This snippet will compile your code as python2 , it is meant to be called with from a larger python 3 script with something like subprocess.check_output. This snippet will not catch run time errors like “undefined variable” . It will catch compile time errors like “bad indent”

#!/usr/bin/env python
import py_compile, sys
print("compiling for python 2 %s"%(sys.argv[1]))
py_compile.compile(sys.argv[1], doraise=True)

This sub-routine will compile your code as python3

def compile_python3_ok(file):
        py_compile.compile(file, doraise=True)
    except py_compile.PyCompileError as the_exception:
        msg = "\nERROR FAIL python3 compile %s\n"%(file)
        sys.stderr.write("\n"+ str(the_exception))

You can install pylint with

sudo apt install python3-pip
pip3 install pylint
export PATH=/home/$USER/.local/bin:$PATH

This snippit will run pylint with python 3 checkers

import subprocess,sys

def run_(cmd): 
        log_me = subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as the_exception:
        msg = "ERROR FAIL %s\n"%(cmd)
run_("pylint --py3k --disable=%s %s"%(CHECKS_TO_SKIP,file))

Pylint is kinda like having unit tests, in that you should understand the problems it calls out and either fix them or skip the checks and kinda not in that unlike 100% test coverage, you will miss some problems.



For simplicity, the code examples here are stripped of useful but distracting bits like logging and conversions that 2to3 doesn't handle. Eventually, I'll strip out my employer's proprietary things and put the full script on GitHub. Sooner rather than later, if somebody shows an interest in the fuller code.

No comments:

Post a Comment