11

I have a line of code like this:

mydict['description_long'] = another_dict['key1'][0]['a_really_long_key']['another_long_key']['another_long_key3']['another_long_key4']['another_long_key5']

How do I format it so it adheres to the PEP8 guidelines?

6
  • 2
    Split it into two using an intermediate variable? Jan 16, 2017 at 23:37
  • Have you tried the PEP8 Checker to see if that's a legal line? I'm sure it breaks the line length rule, but it might tell you what to do Jan 16, 2017 at 23:37
  • 1
    wow thats pretty nested!! It's a bit of an eye bleed, can't you break it down and hide some of the levels of indirection behind meaningfully named function calls? That would get rid of the need produce such long lines. Jan 16, 2017 at 23:38
  • PEP8 compliant deep dictionary access has a few answers, although not a definitive one (so I don't think it's a good candidate for a dupe) Jan 16, 2017 at 23:39
  • @SterlingArcher I think that's the point of the question, although, it isn't explicit. Jan 16, 2017 at 23:39

3 Answers 3

11

The only relevant part of PEP8's style guidelines here is line length. Just break up the dict keys into their own separate lines. This makes the code way easier to read as well.

mydict['description_long'] = (another_dict['key1']
                                          [0]
                                          ['a_really_long_key']
                                          [etc.])
1
  • 4
    This does not pass a PEP8 check either, but I would consider this better than the above. "[Whitespace] Immediately before the open parenthesis that starts an indexing or slicing: Yes: dct['key'] = lst[index] No: dct ['key'] = lst [index]" Jan 16, 2017 at 23:44
2

I think I'd do something like this, add parens to go over multiple lines:

mydict['description_long'] = (
    another_dict['key1'][0]['a_really_long_key']['another_long_key']
    ['another_long_key3']['another_long_key4']['another_long_key5'])

Though it'd be better not to have such a deep structure in the first place, or to split up the lookup into several, if you can give those good names:

item = another_dict['key1'][0]['a_really_long_key']
part_name = item['another_long_key']['another_long_key3']
detail = part_name['another_long_key4']['another_long_key5']

At least that way the deep structure is documented a little.

1
  • really agree with that second part, instead of fumbling around with breaking it up into multiple lines
    – cryanbhu
    Dec 17, 2020 at 5:56
1

each [ is a bracket. So it nominally just like nesting parenthesis:

mydict['description_long'] = another_dict['key1'][0][
    'a_really_long_key']['another_long_key'][
        'another_long_key3']['another_long_key4'][
            'another_long_key4']

A more generic way might be to just do some metaprogramming and use a series of list comprehensions or iteration to expand child datastructures. For example, your child node can be found by following a path represented by the list:

keypath = ['key1', 0, 'a_really_long_key', 'another_long_key', 
           'another_long_key3','another_long_key4',
           'another_long_key4']

so you reference your final node by something like:

def resolve_child(root, path):
    for e in path:
        child = root[e]
        root = child
    return child

mydict['description_long'] = resolve_path(another_dict, keypath)

Or if you want to be all functional (Note that reduce() is moved to functools in Py3K):

mydict['description_long'] = reduce(lambda p,c: p[c], keypath, another_dict)

It is usually rare that you have to explicitly reference a deeply nested structure like that; usually the structure is being instantiated by some function, like json.parse or lxml.objectify

4
  • 2
    Your first grouping I would say is worse than just throwing it all on one line. Jan 17, 2017 at 0:30
  • Note sure if it passes PEP 8 though? I mean the closing bracket /does/ "match" the visual indentation in this case...
    – cowbert
    Jan 17, 2017 at 0:53
  • Realistically, I think PEP 8 is intentionally a guideline. There are reasonable exceptions to most rules. I relatively regularly, intentionally violate PEP8 because it makes the code more readable... and PyCharm complains and I ignore it. Because at the end of the day, another dev is going to be the one who has to figure it out, and I'll break guidelines where they detract from the overall readability. Jan 17, 2017 at 2:14
  • Note that all of these methods make it harder to figure out what's actually happening. That's not the point of PEP8. Jan 17, 2017 at 9:58

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.