The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Quiet Intelligence

--

Chapters
00:00 Django Request.Session.Get(&Quot;Name&Quot;, False) - What Does This Code Mean?
00:28 Accepted Answer Score 18
00:52 Answer 2 Score 3
01:09 Thank you

--

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

--

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.