Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Fomatting changes

This document is based on the Google Python Style Guide. The original document is comprehensive and should be referred for work outside the MADlib team. This document is specific to the work in MADlib.

 

Python Language rules

 Imports: Use full path of import for specific functions, while using import for packages and modules only.

...

 black_beans = [jelly_bean for jelly_bean in jelly_beans
                             if            if jelly_bean.color == 'black']

...

 Yes: for k, v in a_dict.iteritems():
               
 No: for k in dict:
                      for             for v in a_dict[k]:
                        …

          Yes Yes: for index, value in enumerate(a_list):
                     …             …
 No: for index in range(len(a_list)):
                     value             value = a_list[index]
                                  ...

True/False evaluations: Python evaluates certain values as false when in a boolean context. A quick "rule of thumb" is that all "empty" values are considered false so 0, None, [], {}, '' all evaluate as false in a boolean context. This may look strange to C/C++ developers but this is the "Pythonic" way of doing this.

...

 - For integers it is safer to compare to 0 explicity.
             e.g. 'if i % 10 == 0:'  instead of 'if i %10:'

 

Classes:  If a class inherits from no other base classes, explicitly inherit from object. This also applies to nested classes.

...

def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):

 """Fetches rows from a Bigtable.

 @brief Retrieves rows pertaining to the given keys from the Table instance represented by big_table.  Silly things may happen if other_silly_variable is not None.

 Args:
           @param big_table: An open Bigtable Table instance.
                 @param            @param keys: A sequence of strings representing key of each table row to fetch,
                 @param            @param other_silly_variable: Another optional variable, that has a much longer
                     name than the other                                        name than the other args, and which does nothing.

 Returns:
                Dict           Dict. A dict mapping keys to the corresponding table row data fetched. Each row is
           represented                            represented as a tuple of strings.
           For example:

                        {'Serak': ('Rigel VII', 'Preparer'),
                       'Zim': ('Irk', 'Invader'),
                       'Lrrr': ('Omicron Persei 8', 'Emperor')}

    If a key from the keys argument is missing from the dictionary, then that row was not
           found in the table.

 Raises:
            IOError: An error occurred accessing the bigtable.Table object.

 """

...

class SampleClass(object):

 """Summary of class here.

 Longer class information...
           Longer class information....

 Attributes:
                 likes           likes_spam: A boolean indicating if we like SPAM or not.
                 eggs           eggs: An integer count of the eggs we have laid.

 """

 def __init__(self, likes_spam=False):

               """Inits SampleClass with blah."""

          self.likes_spam = likes_spam
                self          self.eggs = 0

 def public_method(self):
             """Performs operation blah."""

...

Yes: foo_bar(self, width, height, color='black', design=None, x='foo',
                    emphasis',
                      emphasis=None, highlight=0)

  if (width == 0 and height == 0 and
              color       color == 'red' and emphasis == 'strong'):

...

Yes: x = (“This will build a very long long “
                      “long                 “long long long long long long string”)

Parentheses: Use parentheses sparingly and only when needed (but use if it reduces ambiguity)

Yes: if foo:
          bar            bar()
          while         while x:
              x             x = bar()

           if          if x and y:
              bar            bar()

  if not x:
              bar      bar()

 return foo

for (x, y) in dict.items(): ...

...

Guidelines derived from Guido's Recommendations

...

 

Type

Public

Internal

Packages

lower_with_under

 

Modules

lower_with_under

_lower_with_under

Classes

CapWords

_CapWords

Exceptions

CapWords

 

Functions

lower_with_under()

_lower_with_under()

Global/Class Constants

CAPS_WITH_UNDER

_CAPS_WITH_UNDER

Global/Class Variables

lower_with_under

_lower_with_under

Instance Variables

lower_with_under

_lower_with_under (protected) or __lower_with_under (private)

Method Names

lower_with_under()

_lower_with_under() (protected)

Function/Method Parameters

lower_with_under

 

Local Variables

lower_with_under

 

...