ui-cs383 / Freedom-Galaxy

Primary repository for the FitG
1 stars 6 forks source link

Style Guide for Python Code (PEP 8) #9

Closed cawaltrip closed 10 years ago

cawaltrip commented 10 years ago

Here is the Style Guide for Python Code. It's a rather easy read, with code snippets as examples throughout the entire thing.

hallister commented 10 years ago

In the meeting yesterday I mentioned "never asking for permission" in Python. There are two python methods below, one is the "Pythonic" way of doing things, the other isn't.

Note: the methods below can return invalid values (-2/0 will return infinity) so don't use it.

def pDivide(x, y):
    try:
        return  x / y
    except ZeroDivisionError:
        return float('inf')
   finally: 
        return None

def cDivide(x,y):
    if (y > 0):
         if(isinstance(x/y, (float,int,long,complex)):
            return x/y
         else: 
             return None
    else:
        return float('inf')

For the most part these do the same thing (there are caveats, since the second example won't catch Exceptions).

The first example is clean, and clear. What it's doing is:

The lesson here: ALWAYS try fail over type/value checking. Here's a full try block:

try:
    test = a / b
except ZeroDivisionError:
    print "Can't divide by zero."
else:
    print "The value is ", test
finally:
    print "An unknown exception occurred"
cawaltrip commented 10 years ago

Closed due to being moved to the wiki: Style Guide