Django & Python 3. Aymeric Augustin - @aymericaugustin. PyConFR - September 16th, 2012



Similar documents
Things you didn't know about Python

Building and breaking a Python sandbox

Java Interview Questions and Answers

Automating SQL Injection Exploits

Introduction to Python

Python 2 and 3 compatibility testing via optional run-time type checking

The following functions are provided by the Digest::MD5 module. None of these functions are exported by default.

Chapter 4: Computer Codes

Continuous Integration Part 2

Python Standard Library: Data Representation 4-1

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

CIS 192: Lecture 10 Web Development with Flask

PL/JSON Reference Guide (version 1.0.4)

socketio Documentation

Python Basics. S.R. Doty. August 27, Preliminaries What is Python? Installation and documentation... 4

10 awesome features of Python that you can't use because you refuse to upgrade to Python 3

Introduction to Python for Text Analysis

Analog Documentation. Release Fabian Büchler

Python Programming: An Introduction to Computer Science

Reverse engineering smart cards

Python Loops and String Manipulation

CME 193: Introduction to Scientific Python Lecture 8: Unit testing, more modules, wrap up

4D Plugin SDK v11. Another minor change, real values on 10 bytes is no longer supported.

Exercise 4 Learning Python language fundamentals

Django Two-Factor Authentication Documentation

Crash Dive into Python

XML. CIS-3152, Spring 2013 Peter C. Chapin

Python Tutorial. Release Guido van Rossum Fred L. Drake, Jr., editor. January 04, Python Software Foundation

How to represent characters?

Instruction Set Architecture of Mamba, a New Virtual Machine for Python

The Django web development framework for the Python-aware

List of FTP commands for the Microsoft command-line FTP client

Perl version documentation - Digest::SHA NAME SYNOPSIS SYNOPSIS (HMAC-SHA) Page 1

Demonstrating a DATA Step with and without a RETAIN Statement

Section 1.4 Place Value Systems of Numeration in Other Bases

This is great when speed is important and relatively few words are necessary, but Max would be a terrible language for writing a text editor.

Ecma/TC39/2013/NN. 4 th Draft ECMA-XXX. 1 st Edition / July The JSON Data Interchange Format. Reference number ECMA-123:2009

django-cron Documentation

State of Michigan Data Exchange Gateway. Web-Interface Users Guide

Jonathan Worthington Scarborough Linux User Group

HP Service Virtualization

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

HOMEWORK # 2 SOLUTIO

Why you shouldn't use set (and what you should use instead) Matt Austern

FmPro Migrator - FileMaker to SQL Server

The Answer to the 14 Most Frequently Asked Modbus Questions

Internationalization of Domain Names

Variables, Constants, and Data Types

Chapter 3 Writing Simple Programs. What Is Programming? Internet. Witin the web server we set lots and lots of requests which we need to respond to

Virtuozzo Virtualization SDK

Flash and Python. Dynamic Object oriented Rapid development. Flash and Python. Dave Thompson

requests_toolbelt Documentation

Writing MySQL Scripts With Python's DB-API Interface

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Login with Amazon. Getting Started Guide for Websites. Version 1.0

Pemrograman Dasar. Basic Elements Of Java

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

flask-mail Documentation

CS 1133, LAB 2: FUNCTIONS AND TESTING

Introduction to the. Barracuda Embedded Web-Server

B&K Precision 1785B, 1786B, 1787B, 1788 Power supply Python Library

Internationalizing the Domain Name System. Šimon Hochla, Anisa Azis, Fara Nabilla

Softek Software Ltd. Softek Barcode Reader Toolkit for Android. Product Documentation V7.5.1

pyownet Documentation

Obfuscation: know your enemy

C++ Wrapper Library for Firebird Embedded SQL

EE 261 Introduction to Logic Circuits. Module #2 Number Systems

Java Crash Course Part I

USING MAGENTO TRANSLATION TOOLS

Software Tool Seminar WS Taming the Snake

JavaScript: Control Statements I

PharmaSUG Paper QT26

Introduction to Java

Binary Trees and Huffman Encoding Binary Search Trees

8.5. <summary> Cppcheck addons Using Cppcheck addons Where to find some Cppcheck addons

Translating QueueMetrics into a new language

Advanced Java Client API

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Numeral Systems. The number twenty-five can be represented in many ways: Decimal system (base 10): 25 Roman numerals:

Package PKI. July 28, 2015

Unicode Support in Enterprise COBOL. Nick Tindall Stephen Miller Sam Horiguchi August 13, 2003

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Developing a Web Server Platform with SAPI Support for AJAX RPC using JSON

Everything you wanted to know about using Hexadecimal and Octal Numbers in Visual Basic 6

MS Access Lab 2. Topic: Tables

ResellerPlus - Bulk Http API Specification. (This Document gives details on how to send messages via the Bulk HTTP API for the RouteSms SMPP System)

shodan-python Documentation

Building a Python Plugin

Introduction to Programming Languages and Techniques. xkcd.com FULL PYTHON TUTORIAL

Frequently Asked Questions on character sets and languages in MT and MX free format fields

FTP Client Engine Library for Visual dbase. Programmer's Manual

C++ INTERVIEW QUESTIONS

How to translate VisualPlace

MYPY: A PYTHON VARIANT WITH SEAMLESS DYNAMIC AND STATIC TYPING. Jukka Lehtosalo University of Cambridge Computer Laboratory

Transcription:

Django & Python 3 Aymeric Augustin - @aymericaugustin PyConFR - September 16th, 2012 1

Python 3 is the future 2

Python 3 is the future present 3

Django wants a future 4

how? 5

porting strategies 3to2 single source 2to3

Django's choices single source Python 2.6 six bundled as django.utils.six unicode_literals

The plan Django 1.5 will provide experimental support for Python 3. Compatibility features will be backported to Django 1.4.2. Django 1.6 will be usable in production with Python 3.

six PY3 constants object model syntax binary and text data renamed modules and attributes

a refresher on strings 10

strings Python 2 : str and unicode Python 3 : bytes and str

byte strings str in Python 2 : 'cafe' bytes in Python 3 : b'cafe' six.binary_type or bytes (2.6) can be decoded can raise UnicodeDecodeError bytes in Django s docs

unicode strings unicode in Python 2 : u'café' str in Python 3 : 'café' six.text_type can be encoded can raise UnicodeEncodeError text in Django s docs

native strings str in Python 2 str in Python 3 used by the WSGI specification and parts of the standard library useful idiom: str('spam')

Python 2 implicit conversions >>> 'foo' + u'bar' u'foobar'

Python 2 implicit conversions >>> from StringIO import StringIO >>> s = StringIO() >>> s.write('foo') >>> s.getvalue() 'foo' >>> s.write(u'bar') >>> s.getvalue() u'foobar'

Python 2 implicit conversions >>> from cstringio import StringIO >>> s = StringIO() >>> s.write('foo') >>> s.getvalue() 'foo' >>> s.write(u'bar') >>> s.getvalue() 'foobar'

Python 2 default encoding >>> import sys >>> sys.getdefaultencoding() 'ascii'

Python 2 default encoding # Objects/unicodeobject.c static char unicode_default_encoding[100]; const char *PyUnicode_GetDefaultEncoding(void) { return unicode_default_encoding; } void _PyUnicode_Init(void) { strcpy(unicode_default_encoding, "ascii"); }

Python 2 implicit conversions >>> u'café'.decode() Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128)

Python 2 implicit conversions >>> 'café'.encode() Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 3: ordinal not in range(128)

Python 3 no implicit conversions >>> 'foo' + b'bar' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't convert 'bytes' object to str implicitly

Python 3 default encoding >>> import sys >>> sys.getdefaultencoding() 'utf-8'

Python 3 default encoding # Objects/unicodeobject.c const char * PyUnicode_GetDefaultEncoding(void) { return "utf-8"; }

Python 3 no implicit conversions >>> 'café'.decode() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'str' object has no attribute 'decode'

Python 3 no implicit conversions >>> 'café'.encode() b'caf\xc3\xa9' >>> _.encode() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'bytes' object has no attribute 'encode'

tl:dr; Python 3 has sane string handling 27

porting Django or a pluggable app in 12 steps 28

0) have a test suite If you don't, please stay on Python 2 while the rest of the world moves on. You won't be missed.

1) unicode literals from future import unicode_literals enable it in every module avoid bytestrings automation doesn't really help :( or, if you love u prefixes, PEP 414 brings the past to the future (3.3)

2) print function from future import print_function print("one day, my fingers will type " "this bracket without me even " "thinking about it.")

3) exceptions def do_stuff(): raise Exception("Nope!") def oh_well(exc): print(exc.args[0]) try: do_stuff() except Exception as exc: oh_well(exc)

4) metaclasses from six import with_metaclass class IHateMyCoworkers( with_metaclass(imetahatethem)): """Go figure.""" def with_metaclass(meta, base=object): return meta("newbase", (base,), {})

5) other syntax fixes longs: 1L => 1 sys.maxint => --- octal literals: 022 => 0o022 non-ascii bytes literals `obj` => repr(obj) etc.

6) imports from functools import reduce from six.moves import xrange try: from urllib.parse import urlparse except ImportError: # Python 2 from urlparse import urlparse

7) string types (str, unicode) (basestr,) => six.string_types => six.string_types unicode => six.text_type str(b'foo') == "b'foo'" (!) str => bytes/str (!) smart_unicode => smart_text force_unicode => force_text smart_str => smart_bytes/str (!)

8) representation if you use Django define only str @python_2_unicode_compatible django-2to3.py helper repr must return a str

9) object model next => next class Iterator(object): def next(self): return type(self). next (self) nonzero => bool div => idiv / truediv_ callable() removed no default hash implementation

10) dict methods for k in d:... for k, v in six.iteritems(d):... for v in six.itervalues(d):... keys = list(d) items = list(six.iteritems(d)) values = list(six.itervalues(d)) items = list(d.items()) values = list(d.values())

11) iterators map, range, zip return iterators wrap in list() if you need a list or plan to iterate more than once replace with a list comprehension strings are iterable avoid hasattr(x, ' iter ')

Tips write beautiful Python 3 code that also works on Python 2 design your APIs carefully before adding.encode() and.decode() python3 -m py_compile **/*.py experiment with 2to3 fixers and pick from 2to3's output

hunt regressions on Python 2 42

happy porting 43

Questions Further reading https://docs.djangoproject.com/en/dev/topics/python3/ http://docs.python.org/py3k/howto/pyporting http://packages.python.org/six/ https://www.djangoproject.com/weblog/2012/mar/13/py3k/ https://www.djangoproject.com/weblog/2012/aug/19/experimental-python-3-support/ http://nedbatchelder.com/text/unipain.html 44