Showing posts with label The Zen of Python. Show all posts
Showing posts with label The Zen of Python. Show all posts

Tuesday, April 4, 2017

The Python “Secret Handshake”


I’ve been involved with Python for some 18 years now as of this writing in 2010, and I have seen it grow from an obscure language into one that is used in some fashion in almost every development organization and a solid member of the top four or five most widely-used programming languages in the world. It has been a fun ride. But looking back over the years, it seems to me that if Python truly has a single legacy, it is simply that Python has made quality a more central focus in the development world. It was almost inevitable. A language that requires its users to line up code for readability can’t help but make people raise questions about good software practice in general. Probably nothing summarizes this aspect of Python life better than the standard library this module—a sort of Easter egg in Python written by Python core developer  Tim Peters, which captures much of the design philosophy behind the language. To see this for yourself, go to any Python interactive prompt and import the module (naturally, it’s available on all platforms):

 >>> import this
 The Zen of Python, by Tim Peters
 Beautiful is better than ugly.
 Explicit is better than implicit.
 Simple is better than complex.
 Complex is better than complicated.
 Flat is better than nested.
 Sparse is better than dense.
 Readability counts.
 Special cases aren't special enough to break the rules.
 Although practicality beats purity.
 Errors should never pass silently.
 Unless explicitly silenced.
 In the face of ambiguity, refuse the temptation to guess.
 There should be one-- and preferably only one --obvious way to do it.
 Although that way may not be obvious at first unless you're Dutch.
 Now is better than never.
 Although never is often better than *right* now.
 If the implementation is hard to explain, it's a bad idea.
 If the implementation is easy to explain, it may be a good idea.
 Namespaces are one honking great idea -- let's do more of those!
 >>>


Worth special mention, the “Explicit is better than implicit” rule has become known
as “EIBTI” in the Python world—one of Python’s defining ideas, and one of its sharpest
contrasts with other languages. As anyone who has worked in this field for more than
a few years can attest, magic and engineering do not mix. Python has not always fol-
lowed all of these guidelines, of course, but it comes very close. And if Python’s main
contribution to the software world is getting people to think about such things, it seems
like a win. Besides, it looked great on the T-shirt.



APIsExceptions


Here’s the plan: when someone uses a feature you don’t understand, simply shoot them.
This is easier than learning something new, and before too long the only living coders
will be writing in an easily understood, tiny subset of Python 0.9.6 <wink>1.
— Tim Peters
 legendary core developer and author of The Zen of Python
“Python is an easy to learn, powerful programming language.” Those are the first words
of the official Python Tutorial. That is true, but there is a catch: because the language is
easy to learn and put to use, many practicing Python programmers leverage only a
fraction of its powerful features.


Exceções como APIsExceptions formam um aspecto importante da API como função. Os programadores de uma função precisam saber quais exceções esperar em várias condições para que eles possam garantir manipuladores de exceção adequados. Usaremos um achado da raiz quadrada como um exemplo usando uma função de raiz quadrada.
Coloque o seguinte código em um arquivo chamado roots.py. Há apenas um recurso de linguagem neste programa que não conhecemos antes, o lógico e o operador, que usamos neste caso para testar que duas condições são verdadeiras em cada iteração do loop. O Python também inclui um lógico ou operador, que pode ser usado para testar se um ou ambos os operandos são verdadeiros.

O Python fornece vários tipos de exceção padrão para sinalizar erros comuns. Se um parâmetro de função for fornecido com um valor ilegal, é costume criar um ValueError. Podemos fazer isso usando a palavra-chave raise com um objeto de exceção recém-criado, que podemos criar chamando o construtor ValueError. Há dois lugares que podemos lidar com a divisão por zero. A primeira abordagem seria envolver a raiz encontrando enquanto loop em uma tentativa, exceto ZeroDivisionError, em seguida, criar uma nova exceção ValueError dentro do manipulador de exceção. 


As you may have noticed, several of the operations mentioned work equally for texts, lists and tables. Texts, lists and tables together are called trains. […] The FOR command also works generically on trains1. Geurts, Meertens and Pemberton
 ABC Programmer’s Handbook

Understanding the variety of sequences available in Python saves us from reinventing the wheel, and their common interface inspires us to create APIs that properly support and leverage existing and future sequence types.

Overview of common mapping methods
The basic API for mappings is quite rich. Table 3-1 shows the methods implemented by dict and two of its most useful variations: defaultdict and OrderedDict, both
defined in the collections module.

ORM

Object-Relational Mapper — an API that provides access to database tables and records as Python classes and objects, providing method calls to perform database operations. SQLAlchemy is a popular stand-alone Python ORM; the Django and Web2py frameworks have their own bundled ORMs. 

overriding descriptor A descriptor that implements __set__ and therefore intercepts and overrides attempts at setting the managed attribute in the man‐ aged instance. Also called data descriptor or
enforced descriptor. Contrast with non-overriding descriptor.

parallel assignment Assigning to several variables from items in an iterable, using syntax like a, b = [c, d] — also known as destructuring assignment. This is a common application of tuple
unpacking.