Sunday, 7 September 2025

Python 2.7 vs Python 3

What changed, why it matters, and how to migrate safely.

Quick Summary Table

Topic Python 2.7 Python 3.x Notes
Lifecycle End-of-life (EOL) Jan 1, 2020 Actively maintained Security and new features only in Python 3.
Print print "hi" print("hi") (function) Use parentheses in Py3; enables redirection like any function.
Integer Division 5/2 == 2 5/2 == 2.5 Use // for floor division consistently.
Text vs Bytes str = bytes; unicode = text str = text (Unicode); bytes = binary Explicit encodes/decodes in Py3 when crossing boundaries.
Input raw_input() (text), input() evals input() returns text Safer and simpler in Py3.
Range & Iterators xrange() (lazy), range() (list) range() is lazy No xrange in Py3.
Exceptions except ValueError, e: except ValueError as e: New syntax only in Py3.
Libraries Many packages dropped support Full ecosystem support Modern libs target Py3.8+.
Strings Literals "abc" is bytes; u"abc" unicode "abc" is Unicode; b"abc" bytes Prefer Unicode text, bytes for I/O.
F-Strings Not available f"Hello {name}" Fast, readable formatting (Py3.6+).
Type Hints 3rd-party stubs only Built-in typing Better tooling & readability.
Dict Views .keys()/.items() return lists Return dynamic views (iterable) Wrap with list(...) if you need a list.
Unicode I/O Implicit conversions common Explicit, consistent Open files with encoding="utf-8".
Metaclass Syntax __metaclass__ = M class C(metaclass=M): Cleaner and explicit in Py3.
Standard Library Old module names/locations Reorganized (e.g., urllib) Use modern imports or compatibility layers.

Why Python 3 Happened

Python 3 fixed long-standing design issues—especially the confusing split between text and bytes, integer division, and a few syntax inconsistencies. The result is a cleaner language that’s easier to teach, localize, and maintain.

Common Code Differences

Print & Division

# Python 2.7
print "Hello"
print 5/2        # 2
from __future__ import division
print 5/2        # 2.5 with future import
# Python 3.x
print("Hello")
print(5/2)       # 2.5
print(5//2)      # 2  (floor division)

Unicode vs Bytes

# Python 2.7
u_text = u"café"
b_data = "café"              # bytes
print(type(u_text)), print(type(b_data))
# Python 3.x
text = "café"                # str (Unicode)
data = "café".encode("utf-8")# bytes
with open("out.txt", "w", encoding="utf-8") as f:
    f.write(text)

Ranges & Iteration

# Python 2.7
for i in xrange(3):
    pass
# Python 3.x
for i in range(3):  # lazy like xrange
    pass

Exceptions & Input

# Python 2.7
try:
    1/0
except ZeroDivisionError, e:
    print e
name = raw_input("Name: ")
# Python 3.x
try:
    1/0
except ZeroDivisionError as e:
    print(e)
name = input("Name: ")

Standard Library Reorg Highlights

URLs

# Python 2.7
import urllib2
data = urllib2.urlopen("https://example.com").read()
# Python 3.x
from urllib.request import urlopen
data = urlopen("https://example.com").read()

Itertools / Dicts

# Python 2.7
d = {"a":1}
d.keys()    # list
# Python 3.x
d = {"a":1}
list(d.keys())   # materialize if needed

Migration Tips (2.7 → 3)

  • Target a modern Python 3 (3.10+ recommended) for long-term support and features (pattern matching, better typing, speedups).
  • Run python3 -m venv .venv and port code inside an isolated environment.
  • Use 2to3 or python-modernize/futurize for a first pass; then hand-tune text/bytes boundaries.
  • Adopt from __future__ import print_function and unicode_literals in 2.7 to reduce diffs before switching.
  • Replace xrangerange, iteritems()items(), raw_inputinput.
  • Open files explicitly with encodings: open(..., encoding="utf-8").
  • Pin and upgrade dependencies that still assume Py2; most modern versions are Py3-only.
  • Add tests (e.g., pytest), run type checks (mypy), and format (black) once on Py3.
Rule of thumb: Treat all in-memory text as Unicode (str) and only encode/decode at I/O boundaries (files, sockets, HTTP).

Which Should You Use in 2025?

Use Python 3 for everything new. Python 2.7 is unmaintained and unsupported by the modern ecosystem. If you maintain legacy 2.7 code, prioritize a staged migration to Python 3 with automated tests and incremental refactors.

No comments:

Post a Comment