SlideShare a Scribd company logo
1 of 53
Porting to Python 3

        Lennart Regebro
   EuroPython 2010, Birmingham
Python 3 is here
Loads of goodies!
● print is a function
● All strings are unicode


● Binary data handled by new bytes type


● dict.keys/items/values() are generators


● Integers are all long


● 3/2 == 1.5


● The standard library is reorganized


● New easter egg
Choosing a strategy
Only support Python 3
● For end-user software and systems
● Run 2to3 once


● Then fix the code until it works.


● Done!
Separate branches
● For stable python modules
● If you only do bugfixes


● Make a branch for the old version


● Run 2to3 once


● Fix until it works


● Bug fix both branches
How to distribute
● Separate package names on pypi
● Add a warning and error in the setup.py:


  “For Python 2 support, please use version
  3.x of MyCoolModule”
● Only release binary eggs (bdist_egg)


● Include both src2/ and src3/ and have

  different setup() parameters for different
  Python versions.
Continuous conversion with 2to3
● If you need to support Python 2 and Python
  3 and the code is changing a lot
● Keep developing in Python 2


● Convert to Python 3 for testing and install


● Only one source distribution


● Compatibility hacks may be needed
Solution: Distribute!
● Very little work to set up 2to3 support
● Runs 2to3 on testing and installing:


     – Only one source tree
     – Only one distribution
Using Distribute


setup(name='py3examples',
    ...
    test_suite='py3example.tests.test_suite',
    use_2to3=True,
    convert_2to3_doctests=['py3example/README.txt'],
)
Single code base; no conversion
● If 2to3 for some reason is infeasible
● Support Python 2 and Python 3 from the

  same code without 2to3
● No distribution worries!


● Loads of compatibility hacks


● Fun, but ugly!
When?
● For end-user systems: When you feel like it
● For modules: As soon as you can


● I.e. when your dependencies do
Preparing for the port
Get rid of warnings
● Run under Python 2.6 with -3
● Fix all deprecation warnings
Use // instead of /
In Python 2:
  >>> 3/2
  1
In Python 3:
  >>> 3/2
  1.5
In Python 2.2 and later:
  >>> 3//2
  1
Prepare for bytes
● Use separate variables for binary data
● Add 'b' and 't' to file flags
Write tests


Increasing your test coverage will
   simplify porting and increase
      confidence in the port
Porting
Porting with 2to3



2to3 -w .
2to3 -w -d .
2to3 -w -d README.txt
Common Problems
Comparisons
● cmp() is gone
● cmp = lambda a, b: (a > b) - (a < b)
Bytes vs Strings vs Unicode


 The unicode type is now called string

        The string type is gone

  The bytes type handles binary data
Bytes:
● Used for binary data
>>> file = open('maybe_a.gif', 'rb')
>>> file.read(6)
b'GIF89'

>>> b'GIF89'[2]
70
Solutions
>>> import sys
>>> if sys.version < '3':
... def b(x):
...        return x
... else:
... import codecs
... def b(x):
...       return codecs.latin_1_encode(x)[0]

>>> b('binaryx67data')
Still behaves differently
>>> data = open('a.gif', 'rb').read()
>>> data[2]

Python 2: 'F'
Python 3: 70
Wrapper class for Python 2
class bites(str):
   def __new__(cls, value):
      if isinstance(value[0], int):
          # It's a list of integers
          value = ''.join([chr(x) for x in value])
      return super(bites, cls).__new__(cls, value)

   def itemint(self, index):
      return ord(self[index])

   def iterint(self):
      for x in self:
          yield ord(x)
Wrapper class for Python 3
class bites(bytes):
   def __new__(cls, value):
      if isinstance(value, str):
          # It's a unicode string:
          value = value.encode('ISO-8859-1')
      return super(bites, cls).__new__(cls, value)

   def itemint(self, x):
      return self[x]

   def iterint(self):
      for x in self:
          yield x
Usage
>>> from bites import bites
>>> bites('GIF89a').itemint(2)
70

>>> for x in bites('GIF89a').iterint():
... print(x),
71 73 70 56 57 97
Mixed/unknown files
●   Open in binary mode, and decode


    >>> data = open('maybe_a.gif', 'rb').read()
    >>> if data[:6] != bites('GIF89a'):
    ... str = data.decode('Latin-1')
Unorderable types
● Many built in types that were comparable
  now are not
● __cmp__ is no longer supported
Use “Rich comparison methods”
● __lt__
● __le__


● __eq__


● __ge__


● __gt__


● __ne__
Doctests
● Binary data now is a b'' literal
● Unicode data no longer has the u''


● Classes and types have often changed

  names or at least __repr__
● Exceptions are formated differently as a

  result, and exception matching doesn't
  work under both versions.
Test with ==
Go from:

>>> myfunction()
u'Foobar'

To:

>>> myfunction() == u'Foobar'
True
Capture exceptions
>>> try:
...    dosomethingthatfails()
...    print “ExpectedException not raised”
... except ExpectedException:
...      print “Success”
Success
Without 2to3
Workaround for stdlib reorg
try:
       from StringIO import StringIO
except ImportError:
       from io import StringIO
Workaround for except:
●   Python 2:
        except Exception, e:
●   Python 3:
        except Exception as e:
●   Both:
        except Exception:
           e = sys.exc_info[1]
Workaround for print()
●   For simple print cases:
         print(“Something”) works everywhere.
         print(“Something”, “else”) doesn't.
●   Make your own print function!
Modernize your code
Don't float ints
Python 2:
 >>> float(3)/2
 1.5

Python 2.2 and later:
 >>> from __future__ import division
 >>> 3/2
 1.5
Sorting
●   Old way:
       – Needs lists
       – Slow
       – Comparison methods

●   New way:
       – Sort any iterable
       – Fast
       – Key methods = trivial (often lambdas)
Old way
>>> def lastnamefirst(a, b):
...    s = "%s, %s" % (a.lastname, a.firstname)
...    o = "%s, %s" % (b.lastname, b.firstname)
...    return cmp(s, o)
>>> thelist = [Person('Donald', 'Duck'), Person('Paul', 'Anka')]
>>> thelist.sort(cmp=lastnamefirst)
>>> thelist
[Paul Anka, Donald Duck]
Exponential slowness
● The cmp function compares pairs
● Averages (from Jarret Hardie):


     – 4 items: 6 calls (1.5 per item)
     – 10 items: 22 calls (2.2 per item)
     – 100 items: 528 calls (5.28 per item)
     – 40,000 items: 342,541 calls (8.56 per item)
New way
>>> def lastnamefirst(a):
... return "%s, %s" % (a.lastname, a.firstname)
>>> thetuple = (Person('Donald', 'Duck'), Person('Paul', 'Anka'),)
>>> sorted(thetuple, key=lastnamefirst)
[Paul Anka, Donald Duck]
Fast!



The method is called exactly one time per item
Use iterator methods


                  Instead of
      {}.keys(), {}.values(), {}.items()
                      Use
{}.iterkeys(), {}.itervalues(), {}.iteritems()
Use iterator methods
● In Python 3, {}.keys(), {}.values(),
  {}.items() are iterators
● 2to3 wraps them in list(), so d.values()

  becomes list(d.values())
● By explicitly using iterators in Python 2

  code, you avoid the list()
Put an in in it


●   Old: adict.has_key(foo)

●   New: foo in adict
C-code
● There are API changes
● But you can handle them with ifdefs.
2 * 3 = Six
● A module to help with compatibility
● Several compatibility methods:


       – b()
       – print_()
       – etc...

●   Tons of helpful constants:
       – integer_types
       – string_types
       – etc...
That's it!
Comparison Example
class ComparableMixin(object):
  def __lt__(self, other): return self._compare(other, (-1,))
  def __le__(self, other): return self._compare(other, (-1, 0,))
  def __eq__(self, other): return self._compare(other, (0,))
  def __ge__(self, other): return self._compare(other, (0, 1,))
  def __gt__(self, other): return self._compare(other, (1,))
  def __ne__(self, other): return self._compare(other, (-1, 1,))
Comparison Example
class Orderable(ComparableMixin):
  def __init__(self, firstname, lastname):
     self.firstname = firstname
     self.lastname = lastname
   def _compare(self, other, truthvalues):
     try:
        s = "%s, %s" % (self.lastname, self.firstname)
        o = "%s, %s" % (other.lastname, other.firstname)
        value = (s > o) - (s < o)
        return value in truthvalues
     except AttributeError:
        return NotImplemented

More Related Content

What's hot

Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Pedro Rodrigues
 
Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Pedro Rodrigues
 
Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutesSidharth Nadhan
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionNandan Sawant
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select TopicsJay Coskey
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 
Python Programming: Data Structure
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data StructureChan Shik Lim
 
Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)gekiaruj
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processingIntro C# Book
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Rick Copeland
 
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCEFUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCEVenugopalavarma Raja
 
Python 3.6 Features 20161207
Python 3.6 Features 20161207Python 3.6 Features 20161207
Python 3.6 Features 20161207Jay Coskey
 
Python programing
Python programingPython programing
Python programinghamzagame
 
Programming in Python
Programming in Python Programming in Python
Programming in Python Tiji Thomas
 
Introduction to Python Language and Data Types
Introduction to Python Language and Data TypesIntroduction to Python Language and Data Types
Introduction to Python Language and Data TypesRavi Shankar
 

What's hot (20)

Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
 
Day2
Day2Day2
Day2
 
Python
PythonPython
Python
 
Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)
 
Python in 90 minutes
Python in 90 minutesPython in 90 minutes
Python in 90 minutes
 
Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutes
 
Day3
Day3Day3
Day3
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 Edition
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select Topics
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python Programming: Data Structure
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data Structure
 
Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
 
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCEFUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
 
Python 3.6 Features 20161207
Python 3.6 Features 20161207Python 3.6 Features 20161207
Python 3.6 Features 20161207
 
Python programing
Python programingPython programing
Python programing
 
Programming in Python
Programming in Python Programming in Python
Programming in Python
 
Introduction to Python Language and Data Types
Introduction to Python Language and Data TypesIntroduction to Python Language and Data Types
Introduction to Python Language and Data Types
 

Similar to Porting to Python 3

Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in pythonKarin Lagesen
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnArnaud Joly
 
Python bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of NairobiPython bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of Nairobikrmboya
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
Introduction To Programming with Python
Introduction To Programming with PythonIntroduction To Programming with Python
Introduction To Programming with PythonSushant Mane
 
What's new in Python 3.11
What's new in Python 3.11What's new in Python 3.11
What's new in Python 3.11Henry Schreiner
 
Python Training v2
Python Training v2Python Training v2
Python Training v2ibaydan
 
Programming python quick intro for schools
Programming python quick intro for schoolsProgramming python quick intro for schools
Programming python quick intro for schoolsDan Bowen
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonAhmed Salama
 
Python language data types
Python language data typesPython language data types
Python language data typesHarry Potter
 
Python language data types
Python language data typesPython language data types
Python language data typesYoung Alista
 
Python language data types
Python language data typesPython language data types
Python language data typesLuis Goldster
 
Python language data types
Python language data typesPython language data types
Python language data typesTony Nguyen
 
Python language data types
Python language data typesPython language data types
Python language data typesFraboni Ec
 

Similar to Porting to Python 3 (20)

Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Python lecture 03
Python lecture 03Python lecture 03
Python lecture 03
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
 
Python bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of NairobiPython bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of Nairobi
 
Python 3
Python 3Python 3
Python 3
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Introduction To Programming with Python
Introduction To Programming with PythonIntroduction To Programming with Python
Introduction To Programming with Python
 
What's new in Python 3.11
What's new in Python 3.11What's new in Python 3.11
What's new in Python 3.11
 
Python Training v2
Python Training v2Python Training v2
Python Training v2
 
Programming python quick intro for schools
Programming python quick intro for schoolsProgramming python quick intro for schools
Programming python quick intro for schools
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Faster Python, FOSDEM
Faster Python, FOSDEMFaster Python, FOSDEM
Faster Python, FOSDEM
 
Cc code cards
Cc code cardsCc code cards
Cc code cards
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 

Recently uploaded

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

Porting to Python 3

  • 1. Porting to Python 3 Lennart Regebro EuroPython 2010, Birmingham
  • 2. Python 3 is here
  • 3. Loads of goodies! ● print is a function ● All strings are unicode ● Binary data handled by new bytes type ● dict.keys/items/values() are generators ● Integers are all long ● 3/2 == 1.5 ● The standard library is reorganized ● New easter egg
  • 5. Only support Python 3 ● For end-user software and systems ● Run 2to3 once ● Then fix the code until it works. ● Done!
  • 6. Separate branches ● For stable python modules ● If you only do bugfixes ● Make a branch for the old version ● Run 2to3 once ● Fix until it works ● Bug fix both branches
  • 7. How to distribute ● Separate package names on pypi ● Add a warning and error in the setup.py: “For Python 2 support, please use version 3.x of MyCoolModule” ● Only release binary eggs (bdist_egg) ● Include both src2/ and src3/ and have different setup() parameters for different Python versions.
  • 8. Continuous conversion with 2to3 ● If you need to support Python 2 and Python 3 and the code is changing a lot ● Keep developing in Python 2 ● Convert to Python 3 for testing and install ● Only one source distribution ● Compatibility hacks may be needed
  • 9. Solution: Distribute! ● Very little work to set up 2to3 support ● Runs 2to3 on testing and installing: – Only one source tree – Only one distribution
  • 10. Using Distribute setup(name='py3examples', ... test_suite='py3example.tests.test_suite', use_2to3=True, convert_2to3_doctests=['py3example/README.txt'], )
  • 11. Single code base; no conversion ● If 2to3 for some reason is infeasible ● Support Python 2 and Python 3 from the same code without 2to3 ● No distribution worries! ● Loads of compatibility hacks ● Fun, but ugly!
  • 12. When? ● For end-user systems: When you feel like it ● For modules: As soon as you can ● I.e. when your dependencies do
  • 14. Get rid of warnings ● Run under Python 2.6 with -3 ● Fix all deprecation warnings
  • 15. Use // instead of / In Python 2: >>> 3/2 1 In Python 3: >>> 3/2 1.5 In Python 2.2 and later: >>> 3//2 1
  • 16. Prepare for bytes ● Use separate variables for binary data ● Add 'b' and 't' to file flags
  • 17. Write tests Increasing your test coverage will simplify porting and increase confidence in the port
  • 19. Porting with 2to3 2to3 -w . 2to3 -w -d . 2to3 -w -d README.txt
  • 21. Comparisons ● cmp() is gone ● cmp = lambda a, b: (a > b) - (a < b)
  • 22. Bytes vs Strings vs Unicode The unicode type is now called string The string type is gone The bytes type handles binary data
  • 23. Bytes: ● Used for binary data >>> file = open('maybe_a.gif', 'rb') >>> file.read(6) b'GIF89' >>> b'GIF89'[2] 70
  • 24. Solutions >>> import sys >>> if sys.version < '3': ... def b(x): ... return x ... else: ... import codecs ... def b(x): ... return codecs.latin_1_encode(x)[0] >>> b('binaryx67data')
  • 25. Still behaves differently >>> data = open('a.gif', 'rb').read() >>> data[2] Python 2: 'F' Python 3: 70
  • 26. Wrapper class for Python 2 class bites(str): def __new__(cls, value): if isinstance(value[0], int): # It's a list of integers value = ''.join([chr(x) for x in value]) return super(bites, cls).__new__(cls, value) def itemint(self, index): return ord(self[index]) def iterint(self): for x in self: yield ord(x)
  • 27. Wrapper class for Python 3 class bites(bytes): def __new__(cls, value): if isinstance(value, str): # It's a unicode string: value = value.encode('ISO-8859-1') return super(bites, cls).__new__(cls, value) def itemint(self, x): return self[x] def iterint(self): for x in self: yield x
  • 28. Usage >>> from bites import bites >>> bites('GIF89a').itemint(2) 70 >>> for x in bites('GIF89a').iterint(): ... print(x), 71 73 70 56 57 97
  • 29. Mixed/unknown files ● Open in binary mode, and decode >>> data = open('maybe_a.gif', 'rb').read() >>> if data[:6] != bites('GIF89a'): ... str = data.decode('Latin-1')
  • 30. Unorderable types ● Many built in types that were comparable now are not ● __cmp__ is no longer supported
  • 31. Use “Rich comparison methods” ● __lt__ ● __le__ ● __eq__ ● __ge__ ● __gt__ ● __ne__
  • 32. Doctests ● Binary data now is a b'' literal ● Unicode data no longer has the u'' ● Classes and types have often changed names or at least __repr__ ● Exceptions are formated differently as a result, and exception matching doesn't work under both versions.
  • 33. Test with == Go from: >>> myfunction() u'Foobar' To: >>> myfunction() == u'Foobar' True
  • 34. Capture exceptions >>> try: ... dosomethingthatfails() ... print “ExpectedException not raised” ... except ExpectedException: ... print “Success” Success
  • 36. Workaround for stdlib reorg try: from StringIO import StringIO except ImportError: from io import StringIO
  • 37. Workaround for except: ● Python 2: except Exception, e: ● Python 3: except Exception as e: ● Both: except Exception: e = sys.exc_info[1]
  • 38. Workaround for print() ● For simple print cases: print(“Something”) works everywhere. print(“Something”, “else”) doesn't. ● Make your own print function!
  • 40. Don't float ints Python 2: >>> float(3)/2 1.5 Python 2.2 and later: >>> from __future__ import division >>> 3/2 1.5
  • 41. Sorting ● Old way: – Needs lists – Slow – Comparison methods ● New way: – Sort any iterable – Fast – Key methods = trivial (often lambdas)
  • 42. Old way >>> def lastnamefirst(a, b): ... s = "%s, %s" % (a.lastname, a.firstname) ... o = "%s, %s" % (b.lastname, b.firstname) ... return cmp(s, o) >>> thelist = [Person('Donald', 'Duck'), Person('Paul', 'Anka')] >>> thelist.sort(cmp=lastnamefirst) >>> thelist [Paul Anka, Donald Duck]
  • 43. Exponential slowness ● The cmp function compares pairs ● Averages (from Jarret Hardie): – 4 items: 6 calls (1.5 per item) – 10 items: 22 calls (2.2 per item) – 100 items: 528 calls (5.28 per item) – 40,000 items: 342,541 calls (8.56 per item)
  • 44. New way >>> def lastnamefirst(a): ... return "%s, %s" % (a.lastname, a.firstname) >>> thetuple = (Person('Donald', 'Duck'), Person('Paul', 'Anka'),) >>> sorted(thetuple, key=lastnamefirst) [Paul Anka, Donald Duck]
  • 45. Fast! The method is called exactly one time per item
  • 46. Use iterator methods Instead of {}.keys(), {}.values(), {}.items() Use {}.iterkeys(), {}.itervalues(), {}.iteritems()
  • 47. Use iterator methods ● In Python 3, {}.keys(), {}.values(), {}.items() are iterators ● 2to3 wraps them in list(), so d.values() becomes list(d.values()) ● By explicitly using iterators in Python 2 code, you avoid the list()
  • 48. Put an in in it ● Old: adict.has_key(foo) ● New: foo in adict
  • 49. C-code ● There are API changes ● But you can handle them with ifdefs.
  • 50. 2 * 3 = Six ● A module to help with compatibility ● Several compatibility methods: – b() – print_() – etc... ● Tons of helpful constants: – integer_types – string_types – etc...
  • 52. Comparison Example class ComparableMixin(object): def __lt__(self, other): return self._compare(other, (-1,)) def __le__(self, other): return self._compare(other, (-1, 0,)) def __eq__(self, other): return self._compare(other, (0,)) def __ge__(self, other): return self._compare(other, (0, 1,)) def __gt__(self, other): return self._compare(other, (1,)) def __ne__(self, other): return self._compare(other, (-1, 1,))
  • 53. Comparison Example class Orderable(ComparableMixin): def __init__(self, firstname, lastname): self.firstname = firstname self.lastname = lastname def _compare(self, other, truthvalues): try: s = "%s, %s" % (self.lastname, self.firstname) o = "%s, %s" % (other.lastname, other.firstname) value = (s > o) - (s < o) return value in truthvalues except AttributeError: return NotImplemented