SlideShare une entreprise Scribd logo
1  sur  55
Télécharger pour lire hors ligne
Porting to Python 3
         Lennart Regebro @ PyCon Atlanta 2011




Sebastian, an albino Burmese python. Photo by Emmanuel “Tambako” Keller
Python 3: Pretty scary
Not actually dangerous
Not going away




Stackoverflow questions about Python 3
Third-party projects




The number of projects on the CheeseShop
Check the status




http://py3ksupport.appspot.com/
Currently 34% out of the top 50 projects has Python 3 support
Choosing a strategy
Only support Python 3
●   For end-user software and systems
●   Run 2to3 once
●   Then fix the code until it works.
Separate trees
●   For stable Python libraries
●   Make a branch or copy
●   Run 2to3 once
●   Fix until it works
●   Bug fix both trees
How to distribute
Include both src2/ and src3/ and have different
parameters for different Python versions:

import sys
from distutils.core import setup

if sys.version < '3':
    package_dir = {'': 'src2'}
else:
    package_dir = {'': 'src3'}

setup(name='foo',
      version='1.0',
      package_dir = package_dir)
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
●   Compatibility hacks may be needed
●   Distribute helps
Single code base; no conversion
●   If 2to3 for some reason is infeasible
●   Support Python 2 and Python 3 from the
    same code without 2to3
●   Loads of compatibility hacks
●   Fun, but ugly!
●   Adding Python 2 support to Python 3 is often
    less work than the other way around
●   Check out six
Try with 2to3 first!
●   Run 2to3 to see if it changes much
●   If in doubt use Distribute!
When?
●   For end-user systems: When you feel like it
    ●   Not a good thing to do the week before
        deployment
    ●   Your customers want Python 3!
●   For libraries: As soon as you can
    ●   I.e. when your dependencies runs on Python 3
Preparing for the port
Get rid of warnings
●   Run under Python 2.7 with -3
●   Fix all deprecation warnings

●   [Use iterator methods on dicts]
Prepare for bytes
●   Use separate variables for binary data
●   Add 'b' and 't' to file flags
Use key instead of cmp


>>> def compare(a, b):
...     return cmp(a[1:], b[1:])

>>> names = ['Adam', 'Donald', 'John']
>>> names.sort(cmp=compare)
>>> names
['Adam', 'John', 'Donald']
Slow!
●   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 keyfunction(item):
...     return item[1:]

>>> names = ['Adam', 'Donald', 'John']
>>> names.sort(key=keyfunction)
>>> names
['Adam', 'John', 'Donald']
Fast and simple!
●   The key method is called exactly one time per item
●   The key method is simpler to implement than a
    cmp method
Way simpler


>>> names = ['Adam', 'Donald', 'John']
>>> names.sort(key=len)
>>> names
['Adam', 'John', 'Donald']

>>> names = ['Adam', 'Benno', 'april']
>>> names.sort(key=str.lower)
>>> names
['Adam', 'april', 'Benno']
Use rich comparison methods
●   No support for __cmp__ in Python 3
●   Use rich comparison operators instead:
    __lt__, __le__, __eq__,
    __ge__, __gt__, __ne__
●   Not entirely trivial to implement
    ●   The @totalordering recipe is WRONG!
My mixin
class ComparableMixin(object):
    def _compare(self, other, method):
        try:
             return method(self._cmpkey(), other._cmpkey())
        except (AttributeError, TypeError):
             # _cmpkey not implemented, or return different type,
             # so I can't compare with "other".
             return NotImplemented

    def __lt__(self, other):
        return self._compare(other, lambda s, o: s < o)

    def __le__(self, other):
        return self._compare(other, lambda s, o: s <= o)

    def __eq__(self, other):
        return self._compare(other, lambda s, o: s == o)

    def __ge__(self, other):
        return self._compare(other, lambda s, o: s >= o)

    def __gt__(self, other):
        return self._compare(other, lambda s, o: s > o)

    def __ne__(self, other):
        return self._compare(other, lambda s, o: s != o)
http://bit.ly/richcomp
Write tests



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




2to3 -w .
2to3 -w -d .
2to3 -w -d README.txt
Using 2to3 with Distribute



setup(name='mystuff',
    ...
    test_suite='mystuff.tests.test_suite',
    use_2to3=True,)
Common Problems
Non-ported imports




>>> from urllib2 import urlparse
Replacing UserDict
●   UserDict.IterableUserDict →
    collections.UserDict
●   UserDict.DictMixin →
    collections.MutableMapping
●   UserDict.UserDict →
    collections.UserDict
Bytes
   vs
Strings
   vs
Unicode
Bytes


Used for binary data:

>>> file = open('maybe_a.gif', 'rb')
>>> file.read(6) == 'GIF89a'
False

>>> file.read(6)
b'GIF89a'
Byte literals
>>> type(b'GIF89a')
<class 'bytes'>

>>> b'GIF89a'[2]
70

An alias for str in Python 2.6 and 2.7:

>>> type(b'GIF89a')
<class 'str'>

>>> b'GIF89a'[2]
'F'
Python < 2.6


>>> import sys
>>> if sys.version < '3':
...     def b(x):
...         return x
... else:
...     def b(x):
...        return x.encode('latin-1')

>>> b('binaryx67data')
Still behaves differently



>>> data = open('a.gif', 'rb').read()
>>> data[2]

Python 2: 'F'
Python 3: 70
Manipulating binary data
●   >= 2.6: Use bytearray
●   <= 2.5: Helper methods to iterate and index
Reading from files
●   Python 2: Always 8-bit strings
●   Python 3: 8-bit bytes or Unicode strings
The io module



>>> import io
>>> infile = io.open('UTF-8.txt', 'rt',
       encoding='UTF-8')
The codecs module



>>> import codecs
>>> infile = codecs.open('UTF-8.txt',
    'rt', encoding='UTF-8')
Without 2to3
stdlib reorganisation



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:
●   Python 2.6 and 2.7 handles both
●   Python 3 and Python <= 2.5:
      except Exception:
           e = sys.exc_info()[1]
Workaround for print()
●   For simple print cases:
      print(“Something”) works everywhere.
      print(“Something”, “else”) doesn't.
●   Use print_() from the six module
●   Or make your own
The return of

   Bytes
     vs
  Strings
     vs
  Unicode
Python < 2.6

>>> import sys
>>> if sys.version < '3':
...     def u(x):
...         return x.decode(
...             'unicode_escape')
... else:
...     def u(x):
...        return x

>>> u('Unicxf6de')
Unicöde
Intcompability


               1L no longer works

>>> import sys
>>> if sys.version > '3':
…     long = int

>>> long(1)
1
C Extensions
●   No 2to3
●   Most differences can be handled with
    #ifndefs and macros
●   There is talk about making a compatibility
    header file.
Python 2 module init



PyMODINIT_FUNC
initspam(void)
{
    (void) Py_InitModule("spam", SpamMethods);
}
Python 3 module init

static struct PyModuleDef spammodule = {
   PyModuleDef_HEAD_INIT,
   "spam",   /* name of module */
   spam_doc, /* module documentation */
   -1,       /* size of per-interpreter state*/
   SpamMethods
};

PyMODINIT_FUNC
PyInit_spam(void)
{
    return PyModule_Create(&spammodule);
}
Writing your own fixers
●   If you must modify the API
●   Can be very complex due to edge cases
●   Requires a whole talk by itself
2 * 3 = Six
●   A module to help with compatibility
●   Several compatibility methods:
    ●   b() and u()
    ●   print_()
    ●   etc...
●   Tons of helpful constants:
    ●   integer_types
    ●   string_types
    ●   etc...
Additional Resources
●   http://docs.python.org/py3k/howto/pyporting.html
●   http://wiki.python.org/moin/PortingToPy3k/
●   python-porting@python.org
●   “Porting to Python 3”
●   I'll be sprinting, come and ask!
KEALAVV7




http://python3porting.com/

Contenu connexe

Tendances

H U F F M A N Algorithm Class
H U F F M A N Algorithm ClassH U F F M A N Algorithm Class
H U F F M A N Algorithm Class
Jade Danial
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
Matt Harrison
 

Tendances (20)

H U F F M A N Algorithm Class
H U F F M A N Algorithm ClassH U F F M A N Algorithm Class
H U F F M A N Algorithm Class
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Biopython
BiopythonBiopython
Biopython
 
Python Tutorial
Python TutorialPython Tutorial
Python Tutorial
 
Python basic
Python basicPython basic
Python basic
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.
 
python.ppt
python.pptpython.ppt
python.ppt
 
Python in 90 minutes
Python in 90 minutesPython in 90 minutes
Python in 90 minutes
 
Python
PythonPython
Python
 
Programming in Python
Programming in Python Programming in Python
Programming in Python
 
Python 101
Python 101Python 101
Python 101
 
OpenGurukul : Language : Python
OpenGurukul : Language : PythonOpenGurukul : Language : Python
OpenGurukul : Language : Python
 
Python for Beginners(v1)
Python for Beginners(v1)Python for Beginners(v1)
Python for Beginners(v1)
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
 
Python in 30 minutes!
Python in 30 minutes!Python in 30 minutes!
Python in 30 minutes!
 
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
 
Functions
FunctionsFunctions
Functions
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 

Similaire à Porting to 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...
DRVaibhavmeshram1
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
gabriellekuruvilla
 
Getting Started Cpp
Getting Started CppGetting Started Cpp
Getting Started Cpp
Long Cao
 
Computer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .pptComputer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .ppt
RedenOriola
 
Python advanced 3.the python std lib by example – application building blocks
Python advanced 3.the python std lib by example – application building blocksPython advanced 3.the python std lib by example – application building blocks
Python advanced 3.the python std lib by example – application building blocks
John(Qiang) Zhang
 
introduction to python in english presentation file
introduction to python in english presentation fileintroduction to python in english presentation file
introduction to python in english presentation file
RujanTimsina1
 

Similaire à Porting to Python 3 (20)

Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
 
Python lecture 03
Python lecture 03Python lecture 03
Python lecture 03
 
PythonBrasil[8] - CPython for dummies
PythonBrasil[8] - CPython for dummiesPythonBrasil[8] - CPython for dummies
PythonBrasil[8] - CPython for dummies
 
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...
 
Cc code cards
Cc code cardsCc code cards
Cc code cards
 
python lab programs.pdf
python lab programs.pdfpython lab programs.pdf
python lab programs.pdf
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
 
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
 
Getting Started Cpp
Getting Started CppGetting Started Cpp
Getting Started Cpp
 
Python for web security - beginner
Python for web security - beginnerPython for web security - beginner
Python for web security - beginner
 
Python 3
Python 3Python 3
Python 3
 
Python Course Basic
Python Course BasicPython Course Basic
Python Course Basic
 
Revision of the basics of python1 (1).pdf
Revision of the basics of python1 (1).pdfRevision of the basics of python1 (1).pdf
Revision of the basics of python1 (1).pdf
 
Computer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .pptComputer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .ppt
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in 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 advanced 3.the python std lib by example – application building blocks
Python advanced 3.the python std lib by example – application building blocksPython advanced 3.the python std lib by example – application building blocks
Python advanced 3.the python std lib by example – application building blocks
 
introduction to python in english presentation file
introduction to python in english presentation fileintroduction to python in english presentation file
introduction to python in english presentation file
 
Chapter 1 Class 12 Computer Science Unit 1
Chapter 1 Class 12 Computer Science Unit 1Chapter 1 Class 12 Computer Science Unit 1
Chapter 1 Class 12 Computer Science Unit 1
 
Python basics
Python basicsPython basics
Python basics
 

Dernier

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Dernier (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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
 
[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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Porting to Python 3

  • 1. Porting to Python 3 Lennart Regebro @ PyCon Atlanta 2011 Sebastian, an albino Burmese python. Photo by Emmanuel “Tambako” Keller
  • 4. Not going away Stackoverflow questions about Python 3
  • 5. Third-party projects The number of projects on the CheeseShop
  • 6. Check the status http://py3ksupport.appspot.com/ Currently 34% out of the top 50 projects has Python 3 support
  • 8. Only support Python 3 ● For end-user software and systems ● Run 2to3 once ● Then fix the code until it works.
  • 9. Separate trees ● For stable Python libraries ● Make a branch or copy ● Run 2to3 once ● Fix until it works ● Bug fix both trees
  • 10. How to distribute Include both src2/ and src3/ and have different parameters for different Python versions: import sys from distutils.core import setup if sys.version < '3': package_dir = {'': 'src2'} else: package_dir = {'': 'src3'} setup(name='foo', version='1.0', package_dir = package_dir)
  • 11. 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 ● Compatibility hacks may be needed ● Distribute helps
  • 12. Single code base; no conversion ● If 2to3 for some reason is infeasible ● Support Python 2 and Python 3 from the same code without 2to3 ● Loads of compatibility hacks ● Fun, but ugly! ● Adding Python 2 support to Python 3 is often less work than the other way around ● Check out six
  • 13. Try with 2to3 first! ● Run 2to3 to see if it changes much ● If in doubt use Distribute!
  • 14. When? ● For end-user systems: When you feel like it ● Not a good thing to do the week before deployment ● Your customers want Python 3! ● For libraries: As soon as you can ● I.e. when your dependencies runs on Python 3
  • 16. Get rid of warnings ● Run under Python 2.7 with -3 ● Fix all deprecation warnings ● [Use iterator methods on dicts]
  • 17. Prepare for bytes ● Use separate variables for binary data ● Add 'b' and 't' to file flags
  • 18. Use key instead of cmp >>> def compare(a, b): ... return cmp(a[1:], b[1:]) >>> names = ['Adam', 'Donald', 'John'] >>> names.sort(cmp=compare) >>> names ['Adam', 'John', 'Donald']
  • 19. Slow! ● 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)
  • 20. New way >>> def keyfunction(item): ... return item[1:] >>> names = ['Adam', 'Donald', 'John'] >>> names.sort(key=keyfunction) >>> names ['Adam', 'John', 'Donald']
  • 21. Fast and simple! ● The key method is called exactly one time per item ● The key method is simpler to implement than a cmp method
  • 22. Way simpler >>> names = ['Adam', 'Donald', 'John'] >>> names.sort(key=len) >>> names ['Adam', 'John', 'Donald'] >>> names = ['Adam', 'Benno', 'april'] >>> names.sort(key=str.lower) >>> names ['Adam', 'april', 'Benno']
  • 23. Use rich comparison methods ● No support for __cmp__ in Python 3 ● Use rich comparison operators instead: __lt__, __le__, __eq__, __ge__, __gt__, __ne__ ● Not entirely trivial to implement ● The @totalordering recipe is WRONG!
  • 24. My mixin class ComparableMixin(object): def _compare(self, other, method): try: return method(self._cmpkey(), other._cmpkey()) except (AttributeError, TypeError): # _cmpkey not implemented, or return different type, # so I can't compare with "other". return NotImplemented def __lt__(self, other): return self._compare(other, lambda s, o: s < o) def __le__(self, other): return self._compare(other, lambda s, o: s <= o) def __eq__(self, other): return self._compare(other, lambda s, o: s == o) def __ge__(self, other): return self._compare(other, lambda s, o: s >= o) def __gt__(self, other): return self._compare(other, lambda s, o: s > o) def __ne__(self, other): return self._compare(other, lambda s, o: s != o)
  • 26. Write tests Increasing your test coverage will simplify porting and increase confidence in the port
  • 28. Running 2to3 manually 2to3 -w . 2to3 -w -d . 2to3 -w -d README.txt
  • 29. Using 2to3 with Distribute setup(name='mystuff', ... test_suite='mystuff.tests.test_suite', use_2to3=True,)
  • 31. Non-ported imports >>> from urllib2 import urlparse
  • 32. Replacing UserDict ● UserDict.IterableUserDict → collections.UserDict ● UserDict.DictMixin → collections.MutableMapping ● UserDict.UserDict → collections.UserDict
  • 33. Bytes vs Strings vs Unicode
  • 34. Bytes Used for binary data: >>> file = open('maybe_a.gif', 'rb') >>> file.read(6) == 'GIF89a' False >>> file.read(6) b'GIF89a'
  • 35. Byte literals >>> type(b'GIF89a') <class 'bytes'> >>> b'GIF89a'[2] 70 An alias for str in Python 2.6 and 2.7: >>> type(b'GIF89a') <class 'str'> >>> b'GIF89a'[2] 'F'
  • 36. Python < 2.6 >>> import sys >>> if sys.version < '3': ... def b(x): ... return x ... else: ... def b(x): ... return x.encode('latin-1') >>> b('binaryx67data')
  • 37. Still behaves differently >>> data = open('a.gif', 'rb').read() >>> data[2] Python 2: 'F' Python 3: 70
  • 38. Manipulating binary data ● >= 2.6: Use bytearray ● <= 2.5: Helper methods to iterate and index
  • 39. Reading from files ● Python 2: Always 8-bit strings ● Python 3: 8-bit bytes or Unicode strings
  • 40. The io module >>> import io >>> infile = io.open('UTF-8.txt', 'rt', encoding='UTF-8')
  • 41. The codecs module >>> import codecs >>> infile = codecs.open('UTF-8.txt', 'rt', encoding='UTF-8')
  • 43. stdlib reorganisation try: from StringIO import StringIO except ImportError: from io import StringIO
  • 44. Workaround for except: ● Python 2: except Exception, e: ● Python 3: except Exception as e: ● Python 2.6 and 2.7 handles both ● Python 3 and Python <= 2.5: except Exception: e = sys.exc_info()[1]
  • 45. Workaround for print() ● For simple print cases: print(“Something”) works everywhere. print(“Something”, “else”) doesn't. ● Use print_() from the six module ● Or make your own
  • 46. The return of Bytes vs Strings vs Unicode
  • 47. Python < 2.6 >>> import sys >>> if sys.version < '3': ... def u(x): ... return x.decode( ... 'unicode_escape') ... else: ... def u(x): ... return x >>> u('Unicxf6de') Unicöde
  • 48. Intcompability 1L no longer works >>> import sys >>> if sys.version > '3': … long = int >>> long(1) 1
  • 49. C Extensions ● No 2to3 ● Most differences can be handled with #ifndefs and macros ● There is talk about making a compatibility header file.
  • 50. Python 2 module init PyMODINIT_FUNC initspam(void) { (void) Py_InitModule("spam", SpamMethods); }
  • 51. Python 3 module init static struct PyModuleDef spammodule = { PyModuleDef_HEAD_INIT, "spam", /* name of module */ spam_doc, /* module documentation */ -1, /* size of per-interpreter state*/ SpamMethods }; PyMODINIT_FUNC PyInit_spam(void) { return PyModule_Create(&spammodule); }
  • 52. Writing your own fixers ● If you must modify the API ● Can be very complex due to edge cases ● Requires a whole talk by itself
  • 53. 2 * 3 = Six ● A module to help with compatibility ● Several compatibility methods: ● b() and u() ● print_() ● etc... ● Tons of helpful constants: ● integer_types ● string_types ● etc...
  • 54. Additional Resources ● http://docs.python.org/py3k/howto/pyporting.html ● http://wiki.python.org/moin/PortingToPy3k/ ● python-porting@python.org ● “Porting to Python 3” ● I'll be sprinting, come and ask!