Share
Embed
Python 3 O __Futuro__ é Agora
Apresentar o Python 3.x como uma alternativa a versão 2.x
Apresentado no pysm.org
Tonin Bolzan
August 29, 2015
Transcript
22 slides
-
Python 3 Lançada em 2008 É mais consistente que a
2.X Novos Módulos/Bibliotecas Porém Falta algumas bibliotecas e módulos Fabric e Scrapy (Twisted 75%) -
pypi.python.org PyPI Ranking 58/100 Mais baixados pypi-ranking.info Python 3 Wall
of Superpowers 171/200 Monitorados python3wos.appspot.com Python 3 Readiness 304/360 Mais Populares py3readiness.org -
Novidades Python 3 Tudo é Unicode ou binário Quase tudo
é Iterador Ajustes de Nomenclatura Módulos Renomeados Módulos Agrupados Depreciado foi Removido https://docs.python.org/release/3.0/whatsnew/3.0.html -
Básico Divisão de números mais dinâmica >>> 3/2 == 1.5
Desempacotamento melhorado >>> (a, *rest, b) = range(5) >>> a, rest, b (0, [1, 2, 3], 4) Comparação entre tipos diferentes gera TypeError >>> 2 > 'a' TypeError: unorderable types: int() > str() -
Statement vs function Python 2.x print "teste" print "teste", name
print "\n".join([x, y]) print >> sys.stderr, "error" -- exec "print 'hello'" exec code in global_ns Python 3.x print("teste") print("hello", name) print(x, y, sep="\n") print("error",file=sys.stderr) -- exec("print 'hello'") exec(code, global_ns) -
Nomenclatura Python 2.x raw_input ConfigParser cPickle Queue repr SocketServer Tkinter
_winreg thread dummy_thread markupbase Python 3.x input configparser pickle queue reprlib socketserver tkinter winreg _thread _dummy_thread _markupbase http://docs.pythonsprints.com/python3_porting/py-porting.html -
Reorganização Python 2.x xrange() unichr() basestring() long() itertools.imap() itertools.ifilter() HTMLParser
httplib Python 3.x range() chr() str() int() map() filter() html.parser http.client Muito mais em: http://docs.pythonsprints.com/python3_porting/py-porting.html -
Agrupados Python 2.x urllib urllib2 urlparse robotparser BaseHTTPServer CGIHTTPServer SimpleHTTPServer
Python 3.x urllib - - - http.server - - -
Classes Python 2.x Old/New Style >>> class A(): pass >>>
class B(object): pass >>> a=A() >>> b=B() >>> a.__class__ <class __main__.A> >>> b.__class__ <class '__main__.B'> >>> type(a) <type 'instance'> >>> type(b) <class '__main__.B'> Python 3.x Somente New Style >>> class A(): pass >>> class B(object): pass >>> a=A() >>> b=B() >>> a.__class__ <class '__main__.A'> >>> b.__class__ <class '__main__.B'> >>> type(a) <class '__main__.A'> >>> type(b) <class '__main__.B'> -
Exceções Python 2.x raise IOError, "file error" raise "ahhhh!" raise
TypeError, msg, tb -- try: pass except IOError, err: pass Python 3.x raise IOError("file error") raise Exception("ahhhh!") raise TypeError.with_traceback(tb) -- try: pass except IOError as err: pass During handling of the above exception, another exception occurred -
Novos Módulos -- 3.1+ importlib - Pure Python implementation of
import -- 3.2+ concurrent.futures - Launching parallel tasks -- 3.3+ venv - Virtual Environments (3.3+) >>> python3 -m venv new-env-folder/ -- 3.4+ statistics - Mathematical statistics functions asyncio – Async I/O, event loop, coroutines and tasks pathlib — Object-oriented filesystem paths enum — Support for enumerations tracemalloc — Trace memory allocations -
Diretório __pycache__ • Todos os arquivos .pyc ficam no dir.
__pycache__ • Arquivos .pyc incluem o interpretador e nº versão no nome • Permite diferentes interpretadores e versões do Python sem sobrescrever os arquivos .pyc -
Python 3.5.0 13 Setembro 2015 Eliminação dos arquivos .PYO, porém
estendendo .PYC Corotinas com a sintaxe async e await async def read_data(db): async with db.transaction(): data = await db.fetch('SELECT ...') Novo operador binário “@”, para multiplicação de matriz Type Hints def greeting(name: str) -> str: return 'Hello ' + name Nova função os.scandir() Um iterador diretório melhor e mais rápido.