-4

I am using the below python code to create a dictionary.But I am getting one PEP 8 warning for the dct_structure variable. Warning is: do not use a lambda expression use a def

from collections import defaultdict

dct_structure = lambda: defaultdict(dct_structure)
dct = dct_structure()
dct['protocol']['tcp'] = 'reliable'
dct['protocol']['udp'] = 'unreliable'

I am not comfortable with python lambda expression yet. So can anyone help me to define the function for the below two line of python code to avoid the PEP warning.

dct_structure = lambda: defaultdict(dct_structure)
dct = dct_structure()
Arijit Panda
  • 1,581
  • 2
  • 17
  • 36
  • 2
    Do you ever actually call `dct_structure` again? What's `f`? – jonrsharpe Aug 21 '17 at 06:11
  • I made a mistake while copy pasting my code. I fixed that. Thanks, @jonrsharpe. for mentioning – Arijit Panda Aug 21 '17 at 06:15
  • @Arijit that's the standard way to define a nested `defaultdict`... What tool is causing the warning (if it hasn't already vanished by using the correct name)? You should have an option be it via command line arguments or by a comment of a specified format on the line itself to suppress that particular case. – Jon Clements Aug 21 '17 at 06:16
  • @JonClements - I am using **Pycharm** for writing the code and it's still showing the warning. – Arijit Panda Aug 21 '17 at 06:18
  • @Erwin - I believe that this question is different than the other one. This is for lambda defaultdict expression. – Arijit Panda Aug 21 '17 at 06:30
  • @arjit - Fair enough, it is your question in the end. Though, the answer you accepted here is the same as the linked question... ;) – Erwin Aug 21 '17 at 09:57

1 Answers1

7

A lambda in Python is essentially an anonymous function with awkward restricted syntax; the warning is just saying that, given that you are assigning it straight to a variable - thus giving the lambda a name -, you could just use a def, which has clearer syntax and bakes the function name in the function object, which gives better diagnostics.

You may rewrite your snippet as

def dct_structure():
    return defaultdict(dct_structure) 

dct = dct_structure() 
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299