Skip to content

Commit 158fd81

Browse files
aadeinajacobtylerwalls
authored andcommitted
Fixed #36899 -- Implemented SessionBase.__bool__.
1 parent e85db77 commit 158fd81

4 files changed

Lines changed: 28 additions & 1 deletion

File tree

django/contrib/sessions/backends/base.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,9 @@ def __delitem__(self, key):
6666
del self._session[key]
6767
self.modified = True
6868

69+
def __bool__(self):
70+
return not self.is_empty()
71+
6972
@property
7073
def key_salt(self):
7174
return "django.contrib.sessions." + self.__class__.__qualname__

docs/releases/6.1.txt

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,9 @@ Minor features
150150
:mod:`django.contrib.sessions`
151151
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
152152

153-
* ...
153+
* :class:`~django.contrib.sessions.backends.base.SessionBase` now supports
154+
boolean evaluation via
155+
:meth:`~django.contrib.sessions.backends.base.SessionBase.__bool__`.
154156

155157
:mod:`django.contrib.sitemaps`
156158
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

docs/topics/http/sessions.txt

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,17 @@ You can edit it multiple times.
191191

192192
Example: ``'fav_color' in request.session``
193193

194+
.. method:: __bool__()
195+
196+
.. versionadded:: 6.1
197+
198+
Returns the inverse of :meth:`is_empty`. This allows checking if a
199+
session has data::
200+
201+
if request.session:
202+
# Session has data or a key
203+
pass
204+
194205
.. method:: get(key, default=None)
195206
.. method:: aget(key, default=None)
196207

tests/sessions_tests/tests.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1373,3 +1373,14 @@ async def test_atest_cookie(self):
13731373

13741374
def test_is_empty(self):
13751375
self.assertIs(self.session.is_empty(), True)
1376+
1377+
def test_bool(self):
1378+
# Empty session is falsy
1379+
self.assertIs(bool(self.session), False)
1380+
# Session with data is truthy
1381+
self.session["foo"] = "bar"
1382+
self.assertIs(bool(self.session), True)
1383+
# Session with key but no data is truthy
1384+
session_with_key = SessionBase()
1385+
session_with_key._session_key = "testkey1234"
1386+
self.assertIs(bool(session_with_key), True)

0 commit comments

Comments
 (0)