Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

coding guidelines for python dictionaries [closed]

I have a python dictionary, definition of which does not fit in a single line. Could anyone please tell me guidelines for python dictionaries. I currently have this which does not look good to my eyes.

initialstate =  {
                    'state':grid,
                    'f':find_manhattan_distance(grid,goal),
                    'g':0,
                    'h':find_manhattan_distance(grid,goal),
                    'ancestor': None
                }
like image 517
hrishikeshp19 Avatar asked Jul 08 '26 00:07

hrishikeshp19


2 Answers

pep8.py says:

mydict.py:2:28: E231 missing whitespace after ':'
mydict.py:1:15: E222 multiple spaces after operator

Try this:

initialstate = {
    'state': grid,
    'f': find_manhatten_distance(grid, goal),
    'g': 0,
    'h': find_manhatten_distance(grid, goal),
    'ancestor': None
}

Notice the change in spacing after commas and operators. This version passes all the pep8.py tests.

like image 180
snim2 Avatar answered Jul 10 '26 12:07

snim2


People differ on how best to format things like this. I prefer:

initialstate =  {
    'state': grid,
    'f': find_manhattan_distance(grid, goal),
    'g': 0,
    'h': find_manhattan_distance(grid, goal),
    'ancestor': None,
    }

Things I like about this style:

  1. It allows multiple nestings easily. Indenting under the open-brace would instead cause far too much indentation after just two levels.
  2. The comma after the last item means I can add another line without changing the current last one.
  3. The closing brace indented follows other Python visual style, where there is no obvious termination line, simply the undent to indicate the end of the block.

(PS: "Manhattan" has only a's in it..)

like image 38
Ned Batchelder Avatar answered Jul 10 '26 14:07

Ned Batchelder