Skip to content

Instantly share code, notes, and snippets.

@rittersebastian
Created May 6, 2012 15:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rittersebastian/2623010 to your computer and use it in GitHub Desktop.
Save rittersebastian/2623010 to your computer and use it in GitHub Desktop.
good practices
'''
Defining dictionaries
'''
my_dict = {
'key_1': 'notice the space after colon',
'key_2': 'but not before the colon',
'key_3': 'we are exactly 4 spaces indented'
}
'''
Function/Method definition. No space before open parenthesis,
underscores instead of camel case,
no spaces before/after = in keyword args
wrapped at 79ish characters.
'''
def my_function(para1, para2, para3='foo',
para4='bar'):
pass
'''
Function/Method invocation. You decide. Both are fine.
'''
results = my_function(para1, para2, para3='foo',
para4='bar')
results = my_function(
para1,
para2,
para3='foo',
para4='baar',
)
'''
Often "ors" can be better than long if statements
'''
my_long_var_email_name = request.user.email if request.user.email else "Unknown"
my_long_var_email_name = request.user.email or "Unkown"
'''
In Python. We are optimistic! We assume everything works
and simply handle failure. Exceptions are better
than if statements!
'''
if num.isdigit() and int(num) != 0:
result = 1000 / num
else:
result = 0
try:
result = 1000 / int(num)
except ValueError, ZeroDivsionError:
result = 0
'''
List comprehensions are awesome! In fact they are 4 times faster
than for loops. BUT DON'T USE THEM FOR COMPLEX LOGIC!
'''
good = [i**2 for i in range(x) if i % 2]
bad = [x * y for x in range(10) for y in range(20) if not y % 2 and y > x]
'''
**** Do's and Don'ts ****
''''
if len(a) and a not in ('', [], {}, None, False, 0):
print "DO THIS AND YOUR PULL REQUEST WILL BE REJECTED"
if a:
print "Life can be so easy"
'''
Dictionaries are the heart of python.
They are extremely powerful/fast and have
all the built-in methods that one needs!
'''
if param in request.GET and request.GET['param'] not in ('', None):
value = request.GET['param'] ### Don't do this
else:
value = 0
value = request.GET.get('param', 0)
'''
If you can copy/paste code and change only minor things,
then there is a better way to write it.
'''
### Bad
if SOMETHING:
result = my_function(aaa=1, bbb=2, when_true=xyz)
else:
result = my_function(aaa=1, bbb=2, when_true=abc)
### GOOD
params = {
'aaa': 1,
'bbb': 2,
'when_true': xyz if SOMETHING else abc,
}
result = my_function(**params)
'''
Remember that in Python, variables are
nothing more than pointers to memory locations!
What does b print in the last line here?
'''
### BAD
a = b = {}
### Good
a = {}
b = {}
# Why?
a = b = {}
a[1] = 1
print b
{'1': 1}
'''
Remember that anything declared in the module scope
will only be evaluated once in the
python 'compilation' (pyc) phase.
'''
def my_func(param1=datetime.now()):
'''
I don't work. The now() will only be
evaluated once!
'''
print param1
def my_func(param1=None):
'''
Need to make the evaluation of now() lazy.
'''
value = param1 or datetime.now()
print value
'''
Python has single line conditional statements, don't exploit them.
What's a better way to write this?
'''
limit = int(kwargs['allowance']) if 'allowance' in kwargs and kwargs['allowance'] not in ('',0,None) else 0
try:
limit = int(kwargs.get('allowance', 0))
except ValueError:
limit = 0
'''
Don't use hardcode strings, integers etc in your code!
How long would it take to change the classifieds abbreviation
from 'CL' to 'CLA'?
'''
### BAD
if a == 'hardcoded_string':
# do stuff
pass
elif b == 5:
# do other stuff
pass
### GOOD
CONSTANT_STRING = 'hardcoded_string'
MEANINGFUL_VAR = 5
if a == CONSTANT_STRING:
# do stuff
pass
elif b == MEANINGFUL_VAR:
# do other stuff
pass
'''
79 Characters? With a pinch of salt!
Wrap when logical to do so. If you do wrap, don't use '\'
this is very error prone! Use parenthesis instead.
'''
### BAD
if a and b and c and d and e \
and f and g:
pass
### GOOD
if (a and b and c and d and e
and f and g):
pass
'''
Strings can also conform to the 79 character rule
'''
bad_string = 'a really really really really really long string that is too long'
good_string = ('a really really '
'really really really '
'long string that is '
'too long')
@azizmb
Copy link

azizmb commented Oct 24, 2012

For CSS and HTML styles we could borrow from here: https://github.com/styleguide/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment