0

I'm looking at some code and came across the code

if data is not None

where data is a dictionary.

It got me thinking will data be None if the dictionary is empty? But I tried it on a python compiler and I got False when I do

dict2 = {}
print(dict2 == None)

So my question is, when will dict2 be equal to None?

mark
  • 135
  • 3
  • 12
  • 2
    [`None`](https://docs.python.org/3/library/constants.html#None) and [`dict`](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict) are different objects, so - never. – Olvin Roght Oct 03 '19 at 22:18
  • We can not really help you without more context of the original code. My best guess is that 'data' is a function-parameter and might get called from different place, and some of the will pass `None` to data for some reason. – MegaIng Oct 03 '19 at 22:19
  • You need to provide more context. Presumably whoever wrote that thought that `data` may be **identical** to `None`, there are many possible reasons, but an empty dictionary is definitely not `None` – juanpa.arrivillaga Oct 03 '19 at 22:19
  • 2
    `dict2` is `None` as soon as some part of the code sets `dict2 = None`. Variables aren't bound to types in Python. There may be some code path where data is not a dictionary. – chash Oct 03 '19 at 22:19
  • 1
    Most likely, `data` is *expected* to be a `dict`, but might be `None` instead, and you don't want to do something like `data['foo']` if `data is None` is true. – chepner Oct 03 '19 at 22:19
  • @chepner the idiomatic way of detecting that is with `try`/`catch` blocks. Getting `None` instead of a dict is probably a bug in the code, and having an exception may be a big help in finding it. – Mark Ransom Oct 03 '19 at 22:41

1 Answers1

2

That pattern is common in only one place: detecting a default parameter.

def func(dict2=None):
    if dict2 is None:
        dict2 = { "Default": 0 }
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • What about detecting empty returns from functions? – Stobor Oct 03 '19 at 22:35
  • And why is that superior to `def func(dict2={ "Default": 0 }):` – Stobor Oct 03 '19 at 22:37
  • 1
    @Stobor if a function is supposed to return a dictionary, it should return an empty dictionary instead of `None`. If it forgets to return anything and returns `None` by default, you'll very likely get an exception when you try to use it and the problem should be easy to find. – Mark Ransom Oct 03 '19 at 22:37
  • 1
    @Stobor it's just a common idiom that gives you a little more flexibility in the handling. – Mark Ransom Oct 03 '19 at 22:42
  • That makes sense. – Stobor Oct 03 '19 at 22:44
  • It's a common idiom because it avoids nasty surprises if you are expecting every argument-less call to have its *own* dict. See https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument – chepner Oct 04 '19 at 11:32
  • @chepner I don't know how I forgot that one! Thanks. – Mark Ransom Oct 04 '19 at 12:59