SlideShare a Scribd company logo
1 of 41
Download to read offline
1
Six o‘clock
Last call to migrate to Python 3
César C. Desales
2
Goal
Show how to write code that runs on Python 2
and Python 3 using the six library
4
Not about Python 3 awesomeness!
•  Such powerful
•  Much awesome
•  Wow syntax
•  So modern
3
Python 2 on Google image search
5
Python 3 is still a luxury
•  Mostly for new code
•  Millions of Python 2 legacy LOC
6
The clock is ticking
7
To port or not to port? How?
•  No port
•  Port to Python 3 and ditch support for 2
•  Cowboy style
•  2to3 / modernizer
•  Support both 2 and 3
8
From 2 to 3
Porting Strategy: Cowboy style
•  Read “What’s new?” and migrate by hand
9
Strategy 2: automatically move on
•  Port with a tool, e.g. 2to3 / modernizer
-  Works better with clean and tested code
-  Works only forward
10
Why not just move on to Python 3?
•  Python 2 only environment
•  Python 2 only dependencies
•  You must have backwards compatibility
•  You want to fiddle/learn
11
Using six:
Which python am I running? – 2.7
>>> import six!
>>> if six.PY2:!
... print('Still stuck there?')!
... elif six.PY3:!
... print('Nice,Python 3')!
...!
Still stuck there?!
12
Which python am I running? – 3.4
>>> if six.PY2:!
... print('Still stuck there?')!
... elif six.PY3:!
... print('Nice, Python 3')!
...!
Nice, Python 3!
13
six – string compatibility – 2.7
>>> six.b('payload')!
'payload'!
>>> six.u('foo')!
u'foo’!
Binary strings are still just strings in 2.7
14
six – string compatibility – 3.4
>>> six.b("payload")!
b'payload'!
>>> six.u('foo')!
'foo’!
15
String types – 2.7
>>> ss = 'value’!
>>> isinstance(ss, basetring)!
True!
!
>>> import six!
>>> six.string_types!
(<type 'basestring'>,)!
All strings are instances of basestring
16
String types – 3.4
>>> ss = 'value'!
>>> isinstance(ss, str)!
True!
!
>>> import six!
>>> six.string_types!
(<class 'str'>,)!
basestring is gone. Strings are of str type
17
String types - six
>>> ss = 'value’!
>>> isinstance(ss, six.string_types)!
True!
18
cStringIO – 2.7
>>> import cStringIO!
>>> !
>>> output = cStringIO.StringIO()!
>>> output.write('First line.n')!
>>> output.getvalue()!
'First line.n'!
>>> output.close()!
cStringIO = StringIO written in C
19
cStringIO – 3.4
>>> import io!
>>> !
>>> output = io.StringIO()!
>>> output.write('First line.n')!
12!
>>> output.getvalue()!
'First line.n'!
>>> output.close()!
cStringIO and StringIO => io
20
cStringIO – six
>>> try:
... from cStringIO import StringIO!
... except ImportError:!
... from six import StringIO!
...!
>>> output = StringIO()!
>>> output.write('First line.n')!
>>> output.getvalue()!
'First line.n'!
>>> output.close()!
21
cStringIO with bytes - 2.7 and 3.4
from StringIO import StringIO!
from cStringIO import StringIO!
from io import StringIO!
!
from io import BytesIO!
22
cStringIO with bytes – six on 2.7
>>> try:
... from cStringIO import StringIO as BufferIO!
... except ImportError:!
... from six import BytesIO as BufferIO!
...!
>>> buf = BufferIO(b"abcdef")!
>>> buf.read(6)!
'abcdef'!
*A prefix of 'b' or 'B' is ignored in Python 2
23
cStringIO with bytes – 3.4
>>> try:
... from cStringIO import StringIO as BufferIO!
... except ImportError:!
... from six import BytesIO as BufferIO!
...!
>>> buf = BufferIO(b"abcdef")!
>>> buf.read(6)!
b'abcdef'!
24
urlencode – 2.7 and 3.4
>>> import urllib!
>>> !
>>> urllib.urlencode({'foo':'bar'})!
'foo=bar'!
>>> import urllib.parse!
>>> !
>>> urllib.parse.urlencode({'foo':'bar'})!
'foo=bar'!
25
urlencode – six
>>> import six.moves.urllib.parse!
>>> !
>>> six.moves.urllib.parse.urlencode({'foo':'bar'})!
'foo=bar’!
26
urlparse - 2.7 and 3.4
>>> import urlparse!
>>> urlparse.urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')!
ParseResult(scheme='http', netloc='www.cwi.nl:80', path=…)!
>>> import urllib.parse!
>>> !
>>> urllib.parse.urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')!
ParseResult(scheme='http', netloc='www.cwi.nl:80', path=…)!
27
urlparse - six
>>> import six.moves.urllib.parse as url_parse!
>>> !
>>> url_parse.urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')!
ParseResult(scheme='http', netloc='www.cwi.nl:80', path=…)!
!
28
cPickle – 2.7
>>> import cPickle!
>>> cPickle.dumps("value")!
"S'value'np1n.”!
29
cPickle – pickle – 3.4
>>> import pickle!
>>> !
>>> pickle.dumps("value")!
b'x80x03Xx05x00x00x00valueqx00.'!
pickle is written in C anyway in Python 3
30
cPickle – six in 2.7
>>> import six.moves.cPickle as cPickle!
>>>!
>>> cPickle.dumps("value")!
"S'value'np1n.”!
31
cPickle – six in 3.4
>>> import six.moves.cPickle as cPickle!
>>> cPickle.dumps("value")!
b'x80x03Xx05x00x00x00valueqx00.’!
32
itertools.ifilter – 2.7
>>> from itertools import ifilter!
>>> result = ifilter(the_filter, data)!
ifilter = filter with iterators
33
itertools.ifilter – 3.4
>>> result = filter(the_filter, data)!
34
itertools.ifilter – six
>>> import six.moves!
>>> result = six.moves.filter(the_filter, data)!
35
itertools.izip – 2.7
>>> import itertools!
>>> for val1, val2 in itertools.izip([1,2], [3, 4]):!
... print(’%s %s’ % (val1, val2))!
...!
1 3!
2 4!
izip = zip with iterators
36
itertools.izip – zip – 3.4
>>> for val1, val2 in zip([1,2], [3, 4]):!
... print(’%s %s’ % (val1, val2))!
...!
1 3!
2 4!
37
itertools.izip – zip – six
>>> import six.moves!
>>> for val1, val2 in six.moves.zip([1,2], [3, 4]):!
... print(’%s %s’ % (val1, val2))!
...!
1 3!
2 4!
38
iteritems – 2.7
>>> for key, value in {'foo':'bar'}. iteritems():!
... print(’%s %s’ % (key, value))!
...!
foo bar!
39
iteritems – items – 3.4
>>> for key, value in {'foo':'bar'}.items():!
... print(’%s %s’ % (key, value))!
...!
foo bar!
40
iteritems – six
>>> import six!
>>> for key, value in six.iteritems({'foo':'bar'}):!
... print(’%s %s’ % (key, value))!
...!
foo bar!
41
Recommendations
•  No more Python 2 only commits policy
•  Check Python 2/3 in code review
•  Migration in your development
roadmap => 2020

More Related Content

What's hot

What's hot (18)

Assignment6
Assignment6Assignment6
Assignment6
 
Promise list
Promise listPromise list
Promise list
 
Sistemas operacionais 13
Sistemas operacionais 13Sistemas operacionais 13
Sistemas operacionais 13
 
CentOS_slide_ver1.0
CentOS_slide_ver1.0CentOS_slide_ver1.0
CentOS_slide_ver1.0
 
Source Code
Source CodeSource Code
Source Code
 
Replacing `import` with `accio` in cpython
Replacing `import` with `accio` in cpythonReplacing `import` with `accio` in cpython
Replacing `import` with `accio` in cpython
 
Iteration
IterationIteration
Iteration
 
git. WTF is it doing anyway?
git. WTF is it doing anyway?git. WTF is it doing anyway?
git. WTF is it doing anyway?
 
Python Workshop by Tom Frantz
Python Workshop by Tom FrantzPython Workshop by Tom Frantz
Python Workshop by Tom Frantz
 
FLiSOL - Oficina Ruby on Rails
FLiSOL - Oficina Ruby on RailsFLiSOL - Oficina Ruby on Rails
FLiSOL - Oficina Ruby on Rails
 
Pop3stat sh
Pop3stat shPop3stat sh
Pop3stat sh
 
Fixup and autosquash
Fixup and autosquashFixup and autosquash
Fixup and autosquash
 
R-House (LSRC)
R-House (LSRC)R-House (LSRC)
R-House (LSRC)
 
Combine vs RxSwift
Combine vs RxSwiftCombine vs RxSwift
Combine vs RxSwift
 
Git cheat-sheet
Git cheat-sheetGit cheat-sheet
Git cheat-sheet
 
Pig
PigPig
Pig
 
Python and rust 2018 pythonkorea jihun
Python and rust 2018 pythonkorea jihunPython and rust 2018 pythonkorea jihun
Python and rust 2018 pythonkorea jihun
 
Programação Assíncrona com Asyncio
Programação Assíncrona com AsyncioProgramação Assíncrona com Asyncio
Programação Assíncrona com Asyncio
 

Similar to Migrate to Python 3 using the six library

How to write rust instead of c and get away with it
How to write rust instead of c and get away with itHow to write rust instead of c and get away with it
How to write rust instead of c and get away with it
Flavien Raynaud
 
Python language data types
Python language data typesPython language data types
Python language data types
Harry Potter
 
Python language data types
Python language data typesPython language data types
Python language data types
Young Alista
 
Python language data types
Python language data typesPython language data types
Python language data types
Luis Goldster
 
Python language data types
Python language data typesPython language data types
Python language data types
Tony Nguyen
 
Python language data types
Python language data typesPython language data types
Python language data types
Fraboni Ec
 
Python language data types
Python language data typesPython language data types
Python language data types
James Wong
 
Compiled Python UDFs for Impala
Compiled Python UDFs for ImpalaCompiled Python UDFs for Impala
Compiled Python UDFs for Impala
Cloudera, Inc.
 

Similar to Migrate to Python 3 using the six library (20)

replacing `import` with `accio`
replacing `import` with `accio`replacing `import` with `accio`
replacing `import` with `accio`
 
Modern C++
Modern C++Modern C++
Modern C++
 
Pycon taiwan 2018_claudiu_popa
Pycon taiwan 2018_claudiu_popaPycon taiwan 2018_claudiu_popa
Pycon taiwan 2018_claudiu_popa
 
CSS parsing: performance tips & tricks
CSS parsing: performance tips & tricksCSS parsing: performance tips & tricks
CSS parsing: performance tips & tricks
 
Learn Python 3 for absolute beginners
Learn Python 3 for absolute beginnersLearn Python 3 for absolute beginners
Learn Python 3 for absolute beginners
 
Python in 30 minutes!
Python in 30 minutes!Python in 30 minutes!
Python in 30 minutes!
 
Python course
Python coursePython course
Python course
 
How to write rust instead of c and get away with it
How to write rust instead of c and get away with itHow to write rust instead of c and get away with it
How to write rust instead of c and get away with it
 
The NoSQL store everyone ignored
The NoSQL store everyone ignoredThe NoSQL store everyone ignored
The NoSQL store everyone ignored
 
Python Performance Profiling: The Guts And The Glory
Python Performance Profiling: The Guts And The GloryPython Performance Profiling: The Guts And The Glory
Python Performance Profiling: The Guts And The Glory
 
Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for Bioinformatics
 
2015 bioinformatics bio_python
2015 bioinformatics bio_python2015 bioinformatics bio_python
2015 bioinformatics bio_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
 
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
 
Compiled Python UDFs for Impala
Compiled Python UDFs for ImpalaCompiled Python UDFs for Impala
Compiled Python UDFs for Impala
 

More from Cesar Cardenas Desales

More from Cesar Cardenas Desales (9)

PyConIT 2018 Writing and deploying serverless python applications
PyConIT 2018 Writing and deploying serverless python applicationsPyConIT 2018 Writing and deploying serverless python applications
PyConIT 2018 Writing and deploying serverless python applications
 
PyConIE 2017 Writing and deploying serverless python applications
PyConIE 2017 Writing and deploying serverless python applicationsPyConIE 2017 Writing and deploying serverless python applications
PyConIE 2017 Writing and deploying serverless python applications
 
Writing and deploying serverless python applications
Writing and deploying serverless python applicationsWriting and deploying serverless python applications
Writing and deploying serverless python applications
 
Scalable Web applications with Elastic Beanstalk as your PAAS: a primer
Scalable Web applications with Elastic Beanstalk as your PAAS: a primerScalable Web applications with Elastic Beanstalk as your PAAS: a primer
Scalable Web applications with Elastic Beanstalk as your PAAS: a primer
 
Software maintenance PyConPL 2016
Software maintenance PyConPL 2016Software maintenance PyConPL 2016
Software maintenance PyConPL 2016
 
Unit Testing with Nose
Unit Testing with NoseUnit Testing with Nose
Unit Testing with Nose
 
Distributed Task Processing with Celery - PyZH
Distributed Task Processing with Celery - PyZHDistributed Task Processing with Celery - PyZH
Distributed Task Processing with Celery - PyZH
 
Software maintenance PyConUK 2016
Software maintenance PyConUK 2016Software maintenance PyConUK 2016
Software maintenance PyConUK 2016
 
Code Reviews in Python - PyZh
Code Reviews in Python - PyZhCode Reviews in Python - PyZh
Code Reviews in Python - PyZh
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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...
 
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
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
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
 
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
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

Migrate to Python 3 using the six library

  • 1. 1 Six o‘clock Last call to migrate to Python 3 César C. Desales
  • 2. 2 Goal Show how to write code that runs on Python 2 and Python 3 using the six library
  • 3. 4 Not about Python 3 awesomeness! •  Such powerful •  Much awesome •  Wow syntax •  So modern
  • 4. 3 Python 2 on Google image search
  • 5. 5 Python 3 is still a luxury •  Mostly for new code •  Millions of Python 2 legacy LOC
  • 6. 6 The clock is ticking
  • 7. 7 To port or not to port? How? •  No port •  Port to Python 3 and ditch support for 2 •  Cowboy style •  2to3 / modernizer •  Support both 2 and 3
  • 8. 8 From 2 to 3 Porting Strategy: Cowboy style •  Read “What’s new?” and migrate by hand
  • 9. 9 Strategy 2: automatically move on •  Port with a tool, e.g. 2to3 / modernizer -  Works better with clean and tested code -  Works only forward
  • 10. 10 Why not just move on to Python 3? •  Python 2 only environment •  Python 2 only dependencies •  You must have backwards compatibility •  You want to fiddle/learn
  • 11. 11 Using six: Which python am I running? – 2.7 >>> import six! >>> if six.PY2:! ... print('Still stuck there?')! ... elif six.PY3:! ... print('Nice,Python 3')! ...! Still stuck there?!
  • 12. 12 Which python am I running? – 3.4 >>> if six.PY2:! ... print('Still stuck there?')! ... elif six.PY3:! ... print('Nice, Python 3')! ...! Nice, Python 3!
  • 13. 13 six – string compatibility – 2.7 >>> six.b('payload')! 'payload'! >>> six.u('foo')! u'foo’! Binary strings are still just strings in 2.7
  • 14. 14 six – string compatibility – 3.4 >>> six.b("payload")! b'payload'! >>> six.u('foo')! 'foo’!
  • 15. 15 String types – 2.7 >>> ss = 'value’! >>> isinstance(ss, basetring)! True! ! >>> import six! >>> six.string_types! (<type 'basestring'>,)! All strings are instances of basestring
  • 16. 16 String types – 3.4 >>> ss = 'value'! >>> isinstance(ss, str)! True! ! >>> import six! >>> six.string_types! (<class 'str'>,)! basestring is gone. Strings are of str type
  • 17. 17 String types - six >>> ss = 'value’! >>> isinstance(ss, six.string_types)! True!
  • 18. 18 cStringIO – 2.7 >>> import cStringIO! >>> ! >>> output = cStringIO.StringIO()! >>> output.write('First line.n')! >>> output.getvalue()! 'First line.n'! >>> output.close()! cStringIO = StringIO written in C
  • 19. 19 cStringIO – 3.4 >>> import io! >>> ! >>> output = io.StringIO()! >>> output.write('First line.n')! 12! >>> output.getvalue()! 'First line.n'! >>> output.close()! cStringIO and StringIO => io
  • 20. 20 cStringIO – six >>> try: ... from cStringIO import StringIO! ... except ImportError:! ... from six import StringIO! ...! >>> output = StringIO()! >>> output.write('First line.n')! >>> output.getvalue()! 'First line.n'! >>> output.close()!
  • 21. 21 cStringIO with bytes - 2.7 and 3.4 from StringIO import StringIO! from cStringIO import StringIO! from io import StringIO! ! from io import BytesIO!
  • 22. 22 cStringIO with bytes – six on 2.7 >>> try: ... from cStringIO import StringIO as BufferIO! ... except ImportError:! ... from six import BytesIO as BufferIO! ...! >>> buf = BufferIO(b"abcdef")! >>> buf.read(6)! 'abcdef'! *A prefix of 'b' or 'B' is ignored in Python 2
  • 23. 23 cStringIO with bytes – 3.4 >>> try: ... from cStringIO import StringIO as BufferIO! ... except ImportError:! ... from six import BytesIO as BufferIO! ...! >>> buf = BufferIO(b"abcdef")! >>> buf.read(6)! b'abcdef'!
  • 24. 24 urlencode – 2.7 and 3.4 >>> import urllib! >>> ! >>> urllib.urlencode({'foo':'bar'})! 'foo=bar'! >>> import urllib.parse! >>> ! >>> urllib.parse.urlencode({'foo':'bar'})! 'foo=bar'!
  • 25. 25 urlencode – six >>> import six.moves.urllib.parse! >>> ! >>> six.moves.urllib.parse.urlencode({'foo':'bar'})! 'foo=bar’!
  • 26. 26 urlparse - 2.7 and 3.4 >>> import urlparse! >>> urlparse.urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')! ParseResult(scheme='http', netloc='www.cwi.nl:80', path=…)! >>> import urllib.parse! >>> ! >>> urllib.parse.urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')! ParseResult(scheme='http', netloc='www.cwi.nl:80', path=…)!
  • 27. 27 urlparse - six >>> import six.moves.urllib.parse as url_parse! >>> ! >>> url_parse.urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')! ParseResult(scheme='http', netloc='www.cwi.nl:80', path=…)! !
  • 28. 28 cPickle – 2.7 >>> import cPickle! >>> cPickle.dumps("value")! "S'value'np1n.”!
  • 29. 29 cPickle – pickle – 3.4 >>> import pickle! >>> ! >>> pickle.dumps("value")! b'x80x03Xx05x00x00x00valueqx00.'! pickle is written in C anyway in Python 3
  • 30. 30 cPickle – six in 2.7 >>> import six.moves.cPickle as cPickle! >>>! >>> cPickle.dumps("value")! "S'value'np1n.”!
  • 31. 31 cPickle – six in 3.4 >>> import six.moves.cPickle as cPickle! >>> cPickle.dumps("value")! b'x80x03Xx05x00x00x00valueqx00.’!
  • 32. 32 itertools.ifilter – 2.7 >>> from itertools import ifilter! >>> result = ifilter(the_filter, data)! ifilter = filter with iterators
  • 33. 33 itertools.ifilter – 3.4 >>> result = filter(the_filter, data)!
  • 34. 34 itertools.ifilter – six >>> import six.moves! >>> result = six.moves.filter(the_filter, data)!
  • 35. 35 itertools.izip – 2.7 >>> import itertools! >>> for val1, val2 in itertools.izip([1,2], [3, 4]):! ... print(’%s %s’ % (val1, val2))! ...! 1 3! 2 4! izip = zip with iterators
  • 36. 36 itertools.izip – zip – 3.4 >>> for val1, val2 in zip([1,2], [3, 4]):! ... print(’%s %s’ % (val1, val2))! ...! 1 3! 2 4!
  • 37. 37 itertools.izip – zip – six >>> import six.moves! >>> for val1, val2 in six.moves.zip([1,2], [3, 4]):! ... print(’%s %s’ % (val1, val2))! ...! 1 3! 2 4!
  • 38. 38 iteritems – 2.7 >>> for key, value in {'foo':'bar'}. iteritems():! ... print(’%s %s’ % (key, value))! ...! foo bar!
  • 39. 39 iteritems – items – 3.4 >>> for key, value in {'foo':'bar'}.items():! ... print(’%s %s’ % (key, value))! ...! foo bar!
  • 40. 40 iteritems – six >>> import six! >>> for key, value in six.iteritems({'foo':'bar'}):! ... print(’%s %s’ % (key, value))! ...! foo bar!
  • 41. 41 Recommendations •  No more Python 2 only commits policy •  Check Python 2/3 in code review •  Migration in your development roadmap => 2020