Buenas Practicas

Python

__init__

NO ES EL CONSTRUCTOR DE LA CLASE, ES EL INICIALIZADOR

Programar en Windows

Usar Python 2

import *

Two Scoops of django

Caracteres por linea

entre 80 y 100

print(len((1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1))) # 32
print(len((1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1))) # 43
print(len((1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1))) # 54

#

print(len((1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, \
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1))) # 43

Por favor No Hagan Escaleras

if condicion1:
    if condicion2:
        if condicion3:
            if condicion5:
                if condicion6:
                    if condicion7:

Imports

Use el import *, bajo tu propio riesgo

Yes: import os
     import sys
     from subprocess import Popen, PIPE

No:  import sys, os


# Stdlib imports
from __future__ import absolute_import
from math import sqrt
from os.path import abspath

# Core Django imports
from django.db import models
from django.utils.translation import ugettext_lazy as _

# Third-party app imports
from django_extensions.db.models import TimeStampedModel

# Imports from your apps
from splits.models import BananaSplit

Referencia

from core.views import view Absoluto Se usa cuando se importa algo fuera del actual modulo
from .views import view Relativo Se usa cuando se importa un modulo en el mismo modulo
from views import view Implicito Relativo Usar bajo criterio propio, no es recomendado

Tipos de Imports

__all__ == *

Convenciones

 Yes:

# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# More indentation included to distinguish this from the rest.
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

# Hanging indents should add a level.
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)

No:

# Arguments on first line forbidden when not using vertical alignment.
foo = long_function_name(var_one, var_two,
    var_three, var_four)

# Further indentation required as indentation is not distinguishable.
def long_function_name(
    var_one, var_two, var_three,
    var_four):
    print(var_one)

Tabs o Espacios

Espacios es la forma preferida para la sangría

Tabs solo debe usarse si ya el archivo a sido indentado de esta manera

Nombres

Modulos, debe ser en lowercase y cortos, se puede usar _ para mejorar la lectura

Clases CapWords

Funciones, Metodos de Clases y  Variables, deben ser en lowercase y palabras separadas por _

Constantes son en uppercase y palabras separadas por _

 

self para los metodos de la instancia

cls para los metodos de la clase

class Prueba(object):
    def metodo1(self):
        print(self.__class__)

    @classmethod
    def metodo2(cls):
        print(cls)

Prueba().metodo1() # <class '__main__.Prueba'>
Prueba.metodo2() # <class '__main__.Prueba'>

Metodos Magicos

Magic Method When it gets invoked (example) Explanation
__new__(cls [,...]) instance = MyClass(arg1, arg2) __new__ is called on instance creation
__init__(self [,...]) instance = MyClass(arg1, arg2) __init__ is called on instance creation
__cmp__(self, other) # ** self == other, self > other, etc. Called for any comparison
__pos__(self) +self Unary plus sign
__neg__(self) -self Unary minus sign
__invert__(self) ~self Bitwise inversion
__index__(self) x[self] Conversion when object is used as index
__nonzero__(self) #__bool__ bool(self) Boolean value of the object
__getattr__(self, name) self.name # name doesn't exist Accessing nonexistent attribute
__setattr__(self, name, val) self.name = val Assigning to an attribute
__delattr__(self, name) del self.name Deleting an attribute
__getattribute__(self, name) self.name Accessing any attribute
__getitem__(self, key) self[key] Accessing an item using an index
__setitem__(self, key, val) self[key] = val Assigning to an item using an index
__delitem__(self, key) del self[key] Deleting an item using an index
__iter__(self) for x in self Iteration
__contains__(self, value) value in self, value not in self Membership tests using in
__call__(self [,...]) self(args) "Calling" an instance
__enter__(self) with self as x: with statement context managers
__exit__(self, exc, val, trace) with self as x: with statement context managers
__getstate__(self) pickle.dump(pkl_file, self) Pickling
__setstate__(self) data = pickle.load(pkl_file) Pickling
Magic Method When it gets invoked (example) Explanation
__eq__(self, other) self == other
__ne__(self, other) self != other
__lt__(self, other) self < other
__gt__(self, other) self > other
__le__(self, other) self <= other
__ge__(self, other) self >= other
__abs__(self) abs(self)
__round__(self, n)
round(self, n)
Boolean value of the object
__getattr__(self, name)
self.name # name doesn't exist Accessing nonexistent attribute
__setattr__(self, name, val) self.name = val Assigning to an attribute
__delattr__(self, name) del self.name Deleting an attribute
__getattribute__(self, name) self.name Accessing any attribute
__getitem__(self, key) self[key] Accessing an item using an index
__setitem__(self, key, val) self[key] = val Assigning to an item using an index
__delitem__(self, key) del self[key] Deleting an item using an index
__iter__(self) for x in self Iteration
__contains__(self, value) value in self, value not in self Membership tests using in
__call__(self [,...]) self(args) "Calling" an instance
__enter__(self) with self as x: with statement context managers
__exit__(self, exc, val, trace) with self as x: with statement context managers
__getstate__(self) pickle.dump(pkl_file, self) Pickling
__setstate__(self) data = pickle.load(pkl_file) Pickling

Buenas Practicas

By Leonardo Fabio Orozco Padilla