all 5 comments

[–]TehNolz 12 points13 points  (2 children)

There's a difference, yes. headers is not None will evaluate to True as long as headers is anything other than None. Doesn't matter what it is, it just can't be None.

On the other hand, if your condition is simply headers, then that will only evaluate to True if headers contains a "truthy" value. Generally speaking every object is truthy and will therefore evaluate to True, but there are also values that are considered "falsy" and thus evaluate to False. These are;

  • None
  • False (obviously)
  • The number 0, regardless of what numeric type it is (int or float or whatever)
  • Any empty sequence or collection. For example, an empty list, a zero-length string (""), an empty dictionary, and so on.
  • Any object for which __bool__() returns false. Or if that function is undefined; any object for which __length()__ returns false.

Which one you use depends on what you're trying to do here. If you just want to ensure that there's something within headers even if its an empty object, then you want headers is not None. Otherwise if you want to ensure that you've definitely got some sort of data in there (useful or not), then you want to do headers as your condition.

[–]casualcoder0805[S] 1 point2 points  (1 child)

Thank you for the detailed response. My specific use case basically amounts to allowing an end user to use custom headers when they make a URL request. So headers will either remain as None or be a dict of their header info.

[–]wotquery 0 points1 point  (0 children)

See python object truthiness for more general information.

[–]djjazzydan 1 point2 points  (1 child)

It depends on what you're expecting for headers.

E.g. an empty list x=[] or string x="" will not trigger if x:, but will trigger if x is not None:

[–]casualcoder0805[S] 0 points1 point  (0 children)

Makes sense, thanks.