Skip to content

Instantly share code, notes, and snippets.

@sonnyksimon
Last active December 31, 2019 18:12
Show Gist options
  • Save sonnyksimon/99c363d232b51aee0e14ab913cef0491 to your computer and use it in GitHub Desktop.
Save sonnyksimon/99c363d232b51aee0e14ab913cef0491 to your computer and use it in GitHub Desktop.
HOWTO: coding for python 2 and 3

print

from __future__ import print_function    # (at top of module)

print('Hello', 'Guido')

print('Hello', file=sys.stderr)

print('Hello', end='')

raising exceptions

raise ValueError("dodgy value")

# Raising exceptions with a traceback:
from future.utils import raise_with_traceback
raise_with_traceback(ValueError("dodgy value"))

# Exception chaining
from future.utils import raise_from
class FileDatabase:
    def __init__(self, filename):
        try:
            self.file = open(filename)
        except IOError as exc:
            raise_from(DatabaseError('failed to open'), exc)
# Testing the above:
try:
    fd = FileDatabase('non_existent_file.txt')
except Exception as e:
    assert isinstance(e.__cause__, IOError)    # FileNotFoundError on Py3.3+ inherits from IOError

catching exceptions

try:
    ...
except ValueError as e:
    ...

integer division

assert 2 // 3 == 0

true/float division

from __future__ import division    # (at top of module)

assert 3 / 2 == 1.5

old py2 division

from past.utils import old_div

a = old_div(b, c)    # always same as / on Py2

long integers

k = 9223372036854775808 # instead of 9223372036854775808L

from builtins import int
bigint = int(1) # instead of 1L

test if value is integer (of any kind)

# Python 2 and 3: option 2
from past.builtins import long

if isinstance(x, (int, long)):
    ...

octal constants

0o644    # instead of 0644

backtick repr

repr(x) # backtick deprecated

metaclasses

class BaseForm(object):
    pass

class FormType(type):
    pass

...

# Python 2 only:
class Form(BaseForm):
    __metaclass__ = FormType
    pass

# Python 3 only:
class Form(BaseForm, metaclass=FormType):
    pass

# Python 2 and 3:
from six import with_metaclass
# or
from future.utils import with_metaclass

class Form(with_metaclass(FormType, BaseForm)):
    pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment