2011年8月22日 星期一

PEP 8 -- Style Guide for Python Code (2)

Whitespace in Expressions and Statements
1. Pet Peeves
  a. Avoid extraneous whitespace in the following situations:
    (1) Immediately inside parentheses, brackets or braces.
    Yes: spam(ham[1], {eggs: 2})
    No:  spam( ham[ 1 ], { eggs: 2 } )
    (2) Immediately before a comma, semicolon, or colon:
    Yes: if x == 4: print x, y; x, y = y, x
    No:  if x == 4 : print x , y ; x , y = y , x
    (3) Immediately before the open parenthesis that starts the argument list of a function call:
    Yes: spam(1)
    No:  spam (1)
    (4) Immediately before the open parenthesis that starts an indexing or slicing:
    Yes: dict['key'] = list[index]
    No:  dict ['key'] = list [index]
    (5) More than one space around an assignment (or other) operator to align it with another.
    Yes:
         x = 1
         y = 2
         long_variable = 3
    No:
         x             = 1
         y             = 2
         long_variable = 3
2. Other Recommendations
  a. Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).
  b. Use spaces around arithmetic operators:
  Yes:
       i = i + 1
       submitted += 1
       x = x * 2 - 1
       hypot2 = x * x + y * y
       c = (a + b) * (a - b)
  No:
       i=i+1
       submitted +=1
       x = x*2 - 1
       hypot2 = x*x + y*y
       c = (a+b) * (a-b)
  c. Don't use spaces around the '=' sign when used to indicate a keyword argument or a default parameter value.
  Yes:
       def complex(real, imag=0.0):
           return magic(r=real, i=imag)
  No:
       def complex(real, imag = 0.0):
           return magic(r = real, i = imag)
  d. Compound statements (multiple statements on the same line) are generally discouraged.
  Yes:
       if foo == 'blah':
           do_blah_thing()
       do_one()
       do_two()
       do_three()
  No:
       if foo == 'blah': do_blah_thing()
       do_one(); do_two(); do_three()
  e. While sometimes it's okay to put an if/for/while with a small body on the same line, never do this for multi-clause statements. Also avoid folding such long lines!
  Rather not:
    if foo == 'blah': do_blah_thing()
    for x in lst: total += x
    while t < 10: t = delay()
  Definitely not:
    if foo == 'blah': do_blah_thing()
    else: do_non_blah_thing()

    try: something()
    finally: cleanup()
    
    do_one(); do_two(); do_three(long, argument,
                                 list, like, this)

    if foo == 'blah': one(); two(); three()

沒有留言:

張貼留言