SlideShare ist ein Scribd-Unternehmen logo
1 von 39
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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
 
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
 
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
 
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 Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
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
 
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
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

2 × 3 = 6