SlideShare une entreprise Scribd logo
1  sur  39
Télécharger pour lire hors ligne
2×3=6
six
• Utilities for wrapping between Python 2 and 3	

• Multiplication is more powerful	

• “Five” has already been snatched away by the
Zope Five project

http://pythonhosted.org/six/
Use Case: Reflection
Python 2

>>> text = 'Lorem ipsum'!
>>> isinstance(text, str)!
True
Python 2

>>> text = u'Lorem ipsum'!
>>> isinstance(text, str)!
False
Python 2
>>> text = u'Lorem ipsum'!
>>> isinstance(text, str)!
False!
>>> isinstance(text, unicode)!
True
Python 2
>>> text1 = 'Lorem ipsum'!
>>> text2 = u'Lorem ipsum'!
>>> isinstance(text1, (str, unicode))!
True!
>>> isinstance(text2, (str, unicode))!
True
Python 2
>>> text1 = 'Lorem ipsum'!
>>> text2 = u'Lorem ipsum'!
>>> isinstance(text1, basestring)!
True!
>>> isinstance(text2, basestring)!
True
Python 3

>>> text = 'Lorem ipsum'
>>> isinstance(text, str)!
True

# "Unicode"!
Python 3
>>> text = u'Lorem ipsum' ! # Python 3.3+!
!
>>> isinstance(text, unicode)!
Traceback (most recent call last):!
File "<stdin>", line 2, in <module>!
NameError: name 'unicode' is not defined
Python 3
>>> text = 'Lorem ipsum'!
>>> isinstance(text, basestring)!
Traceback (most recent call last):!
File "<stdin>", line 2, in <module>!
NameError: name 'basestring' is not defined
six
>>> import six!
>>> text = 'Lorem ipsum'!
>>> isinstance(text, six.string_types)!
True!
>>> text = u'Lorem ipsum' # Python 3.3+!
>>> isinstance(text, six.string_types)!
True
six

Python 2

Python 3

class_types

type, types.ClassType

type

integer_types

long, int

int

string_types

basestring

str

text_type

unicode

str

binary_type

str, bytes (2.7)

bytes

MAXSIZE

sys.maxsize (2.6+)

sys.maxsize
Use Case:
Syntax Compatibility
Python 2
>>> lv = {}!
>>> exec 'x = 3, y = 4' in {}, lv!
>>> with open('foo.txt', 'w') as f:!
...
print >>f lv['x'], lv['y']!
...!
>>>
Python 3
>>> lv = {}!
>>> exec('x = 3, y = 4', {}, lv)!
>>> with open('foo.txt', 'w') as f:!
...
print(lv['x'], lv['y'], file=f)!
...!
>>>
six
>>> from six import exec_, print_!
>>> lv = {}!
>>> exec_('x = 3, y = 4', {}, lv)!
>>> with open('foo.txt', 'w') as f:!
...
print_(lv['x'], lv['y'], file=f)!
...!
>>>
Python 2
class MetaFoo(type):!
pass!
!

class Foo(object):!
__metaclass__ = MetaFoo
Python 3
class MetaFoo(type):!
pass!
!

class Foo(object, metaclass=MetaFoo):!
pass
six
from six import add_metaclass!
!

class MetaFoo(type):!
pass!
!

@add_metaclass(MetaFoo)!
class Foo(object):!
pass
six
from six import with_metaclass!
!

class MetaFoo(type):!
pass!
!

class Foo(with_metaclass(object, MetaFoo)):!
pass
six

Python 2

Python 3

exec_

exec (statement)

exec (function)

print_

print (statement)

print (function)

reraise

exception re-raising	

(can contain previous tracebacks)

with_metaclass

metaclassing	

(creates an intermediate class)

add_metaclass

metaclassing	

(no intermediate class)
Use Case: Texts
Python 2

a_byte_string = 'Lorem ipsum'!
still_bytestr = b'Lorem ipsum'
a_unicode_obj = u'Lorem ipsum'

# 2.7!
Python 3

a_unicode_obj = 'Lorem ipsum'!
still_unicode = u'Lorem ipsum'
a_byte_string = b'Lorem ipsum'

# 3.3+ !
six

from six import b, u!
a_byte_string = b('Lorem ipsum')!
a_unicode_obj = u('Lorem ipsum')
six

a_unicode_obj = u('Lorem ipsum')

Be careful with this on Python 2!
six

Python 2

Python 3

b

str, bytes (2.7)

bytes

u

unicode	

(allows escaping)

str

unichr

unichr

chr

int2byte

chr

bytes([integer])

byte2int

ord(bytestr[0])

bytestr[0]
six

Python 2

Python 3

indexbytes(buf, i)

ord(buf[i])

buf[i]

iterbytes(buf)

an iterator for a bytes instance buf

StringIO

StringIO.StringIO

io.StringIO

BytesIO

StringIO.StringIO

io.BytesIO
Use Case:
Name Changes
Python 2
from itertools import izip!
!

u = raw_input()!
!

for i, v in izip(xrange(len(u)), u):!
print i, v
Python 3
u = input()!
!

for i, v in zip(range(len(u)), u):!
print i, v
six
from six.moves import input, zip, range!
!

u = input()!
!

for i, v in zip(range(len(u)), u):!
print i, v
Caveats
from six.moves import ConfigParser!
!

# This will fail on Python 3!!
parser = ConfigParser.SafeConfigParser()
Read the Doc
(Too many to list)

http://pythonhosted.org/six/#module-six.moves
Advanced Usage
• Customised renames	

• Object model compatibility	

• six.PY2 and six.PY3 (when all others fail)
In the Meantime
• pies	

• Supports 2.6+ only (six supports 2.4+)	

• Lightweight	

• python-future	

• Based on six	

• Let you write in pure Python 3
Related Reading
http://pythonhosted.org/six/	

http://python3porting.com/differences.html	

http://docs.python.org/3/library/	

http://docs.python.org/2/library/	

http://python-future.org	

https://github.com/timothycrosley/pies
2 × 3 = 6

Contenu connexe

Tendances

Tendances (20)

Fizz and buzz of computer programs in python.
Fizz and buzz of computer programs in python.Fizz and buzz of computer programs in python.
Fizz and buzz of computer programs in python.
 
Workshop programs
Workshop programsWorkshop programs
Workshop programs
 
Clojure made really really simple
Clojure made really really simpleClojure made really really simple
Clojure made really really simple
 
Basics
BasicsBasics
Basics
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
 
Control Flow
Control FlowControl Flow
Control Flow
 
Tuples
TuplesTuples
Tuples
 
Libraries
LibrariesLibraries
Libraries
 
Be Lazy & Scale
Be Lazy & ScaleBe Lazy & Scale
Be Lazy & Scale
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
 
Python 3.x File Object Manipulation Cheatsheet
Python 3.x File Object Manipulation CheatsheetPython 3.x File Object Manipulation Cheatsheet
Python 3.x File Object Manipulation Cheatsheet
 
First class patterns for object matching
First class patterns for object matchingFirst class patterns for object matching
First class patterns for object matching
 
Phorms: Pattern Matching Library for Pharo
Phorms: Pattern Matching Library for PharoPhorms: Pattern Matching Library for Pharo
Phorms: Pattern Matching Library for Pharo
 
Basics of python 3
Basics of python 3Basics of python 3
Basics of python 3
 
Scripting 101
Scripting 101Scripting 101
Scripting 101
 
Python 3
Python 3Python 3
Python 3
 
Introduction to Python3 Programming Language
Introduction to Python3 Programming LanguageIntroduction to Python3 Programming Language
Introduction to Python3 Programming Language
 
Grails In The Wild
Grails In The WildGrails In The Wild
Grails In The Wild
 
Class 7b: Files & File I/O
Class 7b: Files & File I/OClass 7b: Files & File I/O
Class 7b: Files & File I/O
 
File Commands - R.D.Sivakumar
File Commands - R.D.SivakumarFile Commands - R.D.Sivakumar
File Commands - R.D.Sivakumar
 

En vedette

Django mongodb -djangoday_
Django mongodb -djangoday_Django mongodb -djangoday_
Django mongodb -djangoday_
WEBdeBS
 
Django e il Rap Elia Contini
Django e il Rap Elia ContiniDjango e il Rap Elia Contini
Django e il Rap Elia Contini
WEBdeBS
 

En vedette (20)

Website optimization
Website optimizationWebsite optimization
Website optimization
 
Bottle - Python Web Microframework
Bottle - Python Web MicroframeworkBottle - Python Web Microframework
Bottle - Python Web Microframework
 
The Django Book Chapter 9 - Django Workshop - Taipei.py
The Django Book Chapter 9 - Django Workshop - Taipei.pyThe Django Book Chapter 9 - Django Workshop - Taipei.py
The Django Book Chapter 9 - Django Workshop - Taipei.py
 
EuroDjangoCon 2009 - Ein Rückblick
EuroDjangoCon 2009 - Ein RückblickEuroDjangoCon 2009 - Ein Rückblick
EuroDjangoCon 2009 - Ein Rückblick
 
Vim for Mere Mortals
Vim for Mere MortalsVim for Mere Mortals
Vim for Mere Mortals
 
PythonBrasil[8] closing
PythonBrasil[8] closingPythonBrasil[8] closing
PythonBrasil[8] closing
 
PyClab.__init__(self)
PyClab.__init__(self)PyClab.__init__(self)
PyClab.__init__(self)
 
NoSql Day - Chiusura
NoSql Day - ChiusuraNoSql Day - Chiusura
NoSql Day - Chiusura
 
The Django Book, Chapter 16: django.contrib
The Django Book, Chapter 16: django.contribThe Django Book, Chapter 16: django.contrib
The Django Book, Chapter 16: django.contrib
 
Django-Queryset
Django-QuerysetDjango-Queryset
Django-Queryset
 
Overview of Testing Talks at Pycon
Overview of Testing Talks at PyconOverview of Testing Talks at Pycon
Overview of Testing Talks at Pycon
 
Authentication & Authorization in ASPdotNet MVC
Authentication & Authorization in ASPdotNet MVCAuthentication & Authorization in ASPdotNet MVC
Authentication & Authorization in ASPdotNet MVC
 
Rabbitmq & Postgresql
Rabbitmq & PostgresqlRabbitmq & Postgresql
Rabbitmq & Postgresql
 
2016 py con2016_lightingtalk_php to python
2016 py con2016_lightingtalk_php to python2016 py con2016_lightingtalk_php to python
2016 py con2016_lightingtalk_php to python
 
Html5 History-API
Html5 History-APIHtml5 History-API
Html5 History-API
 
NoSql Day - Apertura
NoSql Day - AperturaNoSql Day - Apertura
NoSql Day - Apertura
 
2007 - 应用系统脆弱性概论
2007 - 应用系统脆弱性概论 2007 - 应用系统脆弱性概论
2007 - 应用系统脆弱性概论
 
Django mongodb -djangoday_
Django mongodb -djangoday_Django mongodb -djangoday_
Django mongodb -djangoday_
 
User-centered open source
User-centered open sourceUser-centered open source
User-centered open source
 
Django e il Rap Elia Contini
Django e il Rap Elia ContiniDjango e il Rap Elia Contini
Django e il Rap Elia Contini
 

Similaire à 2 × 3 = 6

Python for text processing
Python for text processingPython for text processing
Python for text processing
Xiang Li
 
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
 

Similaire à 2 × 3 = 6 (20)

Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
 
Session 02 python basics
Session 02 python basicsSession 02 python basics
Session 02 python basics
 
Session 02 python basics
Session 02 python basicsSession 02 python basics
Session 02 python basics
 
Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for Bioinformatics
 
Moving to Python 3
Moving to Python 3Moving to Python 3
Moving to Python 3
 
Python for text processing
Python for text processingPython for text processing
Python for text processing
 
Basic data types in python
Basic data types in pythonBasic data types in python
Basic data types in python
 
Python Traning presentation
Python Traning presentationPython Traning presentation
Python Traning presentation
 
Python String Revisited.pptx
Python String Revisited.pptxPython String Revisited.pptx
Python String Revisited.pptx
 
Programming with Python
Programming with PythonProgramming with Python
Programming with 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
 
An (Inaccurate) Introduction to Python
An (Inaccurate) Introduction to PythonAn (Inaccurate) Introduction to Python
An (Inaccurate) Introduction to Python
 
Python Workshop
Python  Workshop Python  Workshop
Python Workshop
 
PYTHON
PYTHONPYTHON
PYTHON
 

Dernier

+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@
 

Dernier (20)

Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
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
 
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
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
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
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
+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...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 

2 × 3 = 6