jgoenetxea
11/15/2017 - 10:38 AM

Print function mutli-version compatibility

How to define the print function to be used i python 2.x and 3.x in the same way.

from __future__ import print_function
import sys

# Re-declare the print function 
if sys.version_info[:2] < (3, 3):
    old_print = print
    def print(*args, **kwargs):
        flush = kwargs.pop('flush', False)
        old_print(*args, **kwargs)
        if flush:
            file = kwargs.get('file', sys.stdout)
            # Why might file=None? IDK, but it works for print(i, file=None)
            file.flush() if file is not None else sys.stdout.flush()