Hassan Baig
Hassan Baig

Reputation: 15814

Deleting session variable while avoiding KeyError exception

One of the ways to delete a Django session variable is:

del request.session["sess_variable"]

This naturally gives a KeyError exception in case sess_variable wasn't in the request.session dictionary.

To handle this exception, one can wrap the line in try, except KeyError. But is there a separate command one can use that doesn't throw an error if the key doesn't exist?

Upvotes: 0

Views: 784

Answers (1)

Alasdair
Alasdair

Reputation: 308809

You can pop the key from the session. If you specify None as the default, then you won't get a KeyError.

request.session.pop("sess_variable", None)

Upvotes: 4

Related Questions