The Python Oracle

django request.session.get("name", False) - What does this code mean?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Mysterious Puzzle

--

Chapters
00:00 Question
00:36 Accepted answer (Score 18)
01:10 Answer 2 (Score 3)
01:32 Thank you

--

Full question
https://stackoverflow.com/questions/1216...

Accepted answer links:
[get]: http://docs.python.org/library/stdtypes....

Answer 2 links:
[Django docs]: https://docs.djangoproject.com/en/3.1/to...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #django

#avk47



ACCEPTED ANSWER

Score 18


If session has a key in it with the value "name" it returns the value associated with that key (which might well be False), otherwise (if there is no key named "name") it returns False.

The session is a dictionary-like type so the best place to get documenation on the get method is in the Python docs for the standard library. The short of the matter is that get is shorthand for the following:

if "name" in request.session:
    result = request.session["name"]
else:
    result = False

if result:
    # Do something



ANSWER 2

Score 3


As per Django docs the 2nd argument of the get method is the default. So "request.session.get("name",False):" statement returns the value of the 'name' items if it exists in the session if it doesn't then a default of False is returned.