2

What is the difference in these two ways to retrieve the session data? I had though they were the same but encountered a difference. When the session variable 'username' is not set the two return different values.

if session.get('username'):

returns True while

if session['username']:

returns False .

It seems odd that the get method returns anything when the username is not present. What is the difference between these two?

c6754
  • 870
  • 1
  • 9
  • 15
  • That is the normal dictionary interface. Why would it be odd? If the username is not set, the second will raise a KeyError, not return False. – Daniel Roseman Dec 03 '16 at 18:23
  • @DanielRoseman I would find it unexpected tbh. If it doesn't raise key error, then I assume it's an empty string or something falsey stored against `username` if it's not set? In which case, `empty = {'username': ''}` then `print bool(empty.get('username'))` and `print bool(empty['username'])` are both false. – roganjosh Dec 03 '16 at 18:34

0 Answers0