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!
>>> {'uno': 1, 'dos':2} {'dos': 2, 'uno': 1} >>> b = {'uno': 1, 'dos':2} >>> b["uno"] 1 >>> b["tres"] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'tres' >>> b.get("tres", 3) 3 >>> "dos" in b True >>> "tres" in b False >>> b.keys() ['dos', 'uno'] >>> b.items() [('dos', 2), ('uno', 1)]
>>> c = {1,2,3} >>> c set([1, 2, 3]) >>> d = {3,4,5} >>> c.union(d) set([1, 2, 3, 4, 5]) >>> c.difference(d) set([1, 2]) >>> c.intersection(d) set([3]) >>> c.issubset(c.union(d)) True >>> 2 in c True >>> 5 in c
>>> t = (1,2,3) >>> t[1] 2 >>> t[1:] (2, 3) >>> t[1]=2 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment
>>> dir(1) [... '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', ....]
>>> "a" + "b" 'ab' >>> "a" + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects
>>> "Hola %s" % 'Persona' 'Hola Persona' >>> "Hay %.2f cosas" % 12.543 'Hay 12.54 cosas' >>> "Hola %s" % 1 'Hola 1'
>>> "{a} es de tipo {a.__class__}".format(a="hola") "hola es de tipo <type 'str'>" >>> "{} persona".format("hola") 'hola persona
>>> ", ".join(["uno", "dos", "tres"]) 'uno, dos, tres'
>>> (lambda x: x if x == 2 else 0)(5) 0 >>> (lambda x: x if x == 2 else 0)(2) 2 >>> map(lambda x: x+1, [1,2,3]) <map object at 0x7f19383b0550> >>> list(map(lambda x: x+1, [1,2,3])) [2, 3, 4] >>> list(filter(lambda x: x % 2 == 1, [1,2,3])) [1, 3] >>> from functools import reduce >>> reduce(lambda x, y: x + (y % 2), [1,2,3,4,5], 0) 3
>>> [x for x in range(1,10)] [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [x+1 for x in range(1,10)] [2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [x for x in range(1,10) if (x % 2)] [1, 3, 5, 7, 9]
>>> a = [(x, x+10) for x in range(1,10)] >>> a [(1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)] >>> [j for x in a for j in x] [1, 11, 2, 12, 3, 13, 4, 14, 5, 15, 6, 16, 7, 17, 8, 18, 9, 19]
>>> {x: x+10 for x in range(1,10)} {1: 11, 2: 12, 3: 13, 4: 14, 5: 15, 6: 16, 7: 17, 8: 18, 9: 19} >>> {x for x in range(1,10)} {1, 2, 3, 4, 5, 6, 7, 8, 9} >>> type({x for x in range(1,10)}) <class 'set'> >>> (x+10 for x in range(1,10)) <generator object <genexpr> at 0x7f1935b315e8>
>>> for x in [1,2,3]: ... x ... else: ... print("fin!") ... 1 2 3 fin! >>> for x in [1,2,3]: ... if x >= 3: ... break ... else: ... x ... else: ... print("fin!") ... 1 2
>>> class Pepito1(): ... pass ... >>> dir(Pepito1()) ['__doc__', '__module__'] >>> class Pepito2(object): ... pass ... >>> dir(Pepito2()) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
>>> class Pepito3 (Pepito2, dict): ... pass >>> dir(Pepito3()) ['__class__', '__cmp__', ... '__weakref__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
super(clase, instancia).metodo
finally
ejecutara siempre
else
solo ejecuta si no salto la excepcion
# fichero: gigas_api/api/handlers/virtualmachine.py from api.handlers.base import admin_only class K(object): @admin_only def post(self, virtual_machine_id): resp = vm_actions.unlock(self.console, self.user_id, self.cloud_id, {"id": virtual_machine_id}, self.is_admin, vm_mng_cls=self.vm_mng_cls) self.write_response(resp['code'], resp['response'])
def admin_only(func): """ decorator to check if a method is called as admin """ def _decorator(self, *args, **kwargs): # access a from TestSample if not getattr(self, "is_admin", False): logging.error("tried to access an admin only method") raise HTTPError(403, "Insufficient privileges") func(self, *args, **kwargs) return _decorator
>>> from managers.db_manager import DiskManager >>> DiskManager(1,1,True).get_list() <managers.db_manager.ListIterator object at 0x7f85c8b91a10> >>> it = DiskManager(1,1,True).get_list() >>> it.next() { "created_at": "2014-01-28T12:36:06", "id": 1579, .... } >>> it.next() { "created_at": "2014-01-28T12:36:06", "id": 1580, .... } >>> for i in it: ... i.id # una lista muy larga 2284L 2285L # y termina >>> it.next() #no se puede volver atras Traceback (most recent call last): File "<stdin>", line 1, in <module> File "managers/db_manager.py", line 27, in next return self._get_next() File "managers/db_manager.py", line 53, in _get_next raise StopIteration StopIteration
>>> def counter(): ... x = 0 ... while True: ... x += 1 ... yield x >>> counter() <generator object counter at 0x7f85c75c2370> >>> a = counter() >>> next(a) 1 >>> next(a) 2 >>> next(a) 3 >>> a = counter() >>> next(a) 1
Si anda como un pato
Tiene el color de un pato y
Hace -Cuack-
Me da igual lo que sea: lo trataré como a un pato
Muchas cosas evaluan a True/False por lo que en determinados casos puede hacerse:
if x:
foo(x)
# fichero: retoken/retoken.py self.logging.error("Couldn't connect to redis: " "there is no connection info")
virtualenv + nose = tox
https://gist.github.com/kracekumar/09a60ec75a4de19b346e