Voçê está aqui: Home ‣ Dive Into Python 3 ‣
❝ Isn’t this where we came in? ❞
— Pink Floyd, The Wall
Já é programador de Python? Leu o original “Dive Into Python”? Comprou a versão impressa? (Se sim, Obrigado!) Está pronto para mergulhar no Python 3? … Se assim for, continue a ler. (Se nada disso é verdade, será melhor começar do inicio..)
O Python 3 vem com um script chamado 2to3
. Aprenda-o. Ame-o. Use-o. Portar código para Python 3 com 2to3
é uma referencia de todas as coisas que a ferramenta 2to3
corrige automaticamente. Uma vez que muitas dessas correcções são mudanças da sintaxe é um bom ponto de partida para aprender sobre muitas das mudanças sintaxe do Python 3. (print
é agora uma função, `x`
não funciona, &c.)
Caso de Estudo: Portar chardet
para documentos Python 3, o meu esforço (finalmente bem sucedido) para portar uma biblioteca não trivial de Python 2 para Python 3. Pode ajudá-lo, ou não. Existe uma curva de aprendizagem bastante ingreme, primeiro é preciso entender o tipo de biblioteca, então é possível entender porque falhou e como reparar o erro. Grande parte dos erros gira em torno das strings. Falando nisso…
Strings. Ufa. Por onde começar. Python 2 tinha “strings” e “Unicode strings”. Python 3 tem “bytes” e “strings”. Ou seja, todas as strings são agora Unicode strings, e se quisermos lidar com um conjunto de bytes, usamos o novo tipo de bytes
. O Python 3 nunca vai converter implicitamente entre strings e bytes, por isso se não tivermos a certeza do tipo que estamos a usar em cada momento o código vai falhar, quase de certeza. Leia o capítulo das Strings para mais detalhes.
Bytes vs. strings aparece várias vezes ao longo do livro.
codificação
. Alguns métodos para ficheiros de texto contam caracteres, mas outros contam bytes. Se assumirmos que um caracter == um byte, o código vai falhar com caracteres multi-byte.
httplib2
procura cabeçalhos e dados através do HTTP. Os cabeçalhos do HTTP são devolvidos como strings, mas o corpo do HTTP é devolvido como bytes.
pickle
em Python 3 define um novo formato de dados que é incompatível com Python 2. (Dica: é por causa dos bytes e das strings.) Além disso, Python 3 suporta serialização de e para JSON, que nem sequer tem um tipo bytes
. Vamos mostrar como dar a volta a isso.
chardet
to Python 3, it’s just a bloody mess of bytes and strings everywhere.
Even if you don’t care about Unicode (oh but you will), you’ll want to read about string formatting in Python 3, which is completely different from Python 2.
Iterators are everywhere in Python 3, and I understand them a lot better than I did five years ago when I wrote “Dive Into Python”. You need to understand them too, because lots of functions that used to return lists in Python 2 will now return iterators in Python 3. At a minimum, you should read the second half of the Iterators chapter and the second half of the Advanced Iterators chapter.
By popular request, I’ve added an appendix on Special Method Names, which is kind of like the Python docs “Data Model” chapter but with more snark.
When I was writing “Dive Into Python”, all of the available XML libraries sucked. Then Fredrik Lundh wrote ElementTree, which doesn’t suck at all. The Python gods wisely incorporated ElementTree into the standard library, and now it forms the basis for my new XML chapter. The old ways of parsing XML are still around, but you should avoid them, because they suck!
Also new in Python — not in the language but in the community — is the emergence of code repositories like The Python Package Index (PyPI). Python comes with utilities to package your code in standard formats and distribute those packages on PyPI. Read Packaging Python Libraries for details.
© 2001–11 Mark Pilgrim