0

Today I saw this idiomatic piece of code

def __init__(self, data=None):
    self.data = data or {}

I used to write this kind of abbreviations Perl many years ago, and this is the first time I see this idiom in Python. Most of the time, I would write something like

self.data = data if data is not None else dict()

or even:

if data is None:
    data = dict()
self.data = data

Is there any "official" style guide that mentions this kind of style?

I'd google for it, but I don't even know what keywords to use :-)

Solomon Ucko
  • 5,724
  • 3
  • 24
  • 45
  • It works. It's a thing. People use it. I doubt there's something "official" about it. – deceze Mar 15 '23 at 09:21
  • The linked answer is about the `or` returning the first value when shortcircuiting, but here there's also the trick of assigning a parameter to a default of None instead of a default of `{}` which is explained here: https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument – Sembei Norimaki Mar 15 '23 at 09:23
  • @deceze PEP20 seems to disagree: "Readability counts." "There should be one-- and preferably only one --obvious way to do it." – BBorchik Pomidorchik Mar 15 '23 at 09:44
  • That does not mean some official document has been written about any and all possible use cases. `is None` and `or` do two different things, so they're not even the same "it". – deceze Mar 15 '23 at 09:46

0 Answers0