summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAmar <100243770+aadeina@users.noreply.github.com>2026-02-03 00:34:04 +0000
committerJacob Walls <jacobtylerwalls@gmail.com>2026-02-21 09:57:49 -0500
commit158fd81ef5a5647d27eb3065063284f9ee0a3ca4 (patch)
treec6a2bc932dd9d54fb6eb25be7a4e8299babeb0e5
parente85db77e11e37d6ec82526557c4dafe4b30dc699 (diff)
Fixed #36899 -- Implemented SessionBase.__bool__.
-rw-r--r--django/contrib/sessions/backends/base.py3
-rw-r--r--docs/releases/6.1.txt4
-rw-r--r--docs/topics/http/sessions.txt11
-rw-r--r--tests/sessions_tests/tests.py11
4 files changed, 28 insertions, 1 deletions
diff --git a/django/contrib/sessions/backends/base.py b/django/contrib/sessions/backends/base.py
index e53f1d201a..8f673761f2 100644
--- a/django/contrib/sessions/backends/base.py
+++ b/django/contrib/sessions/backends/base.py
@@ -66,6 +66,9 @@ class SessionBase:
del self._session[key]
self.modified = True
+ def __bool__(self):
+ return not self.is_empty()
+
@property
def key_salt(self):
return "django.contrib.sessions." + self.__class__.__qualname__
diff --git a/docs/releases/6.1.txt b/docs/releases/6.1.txt
index 756dcf3395..6c6890b811 100644
--- a/docs/releases/6.1.txt
+++ b/docs/releases/6.1.txt
@@ -150,7 +150,9 @@ Minor features
:mod:`django.contrib.sessions`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-* ...
+* :class:`~django.contrib.sessions.backends.base.SessionBase` now supports
+ boolean evaluation via
+ :meth:`~django.contrib.sessions.backends.base.SessionBase.__bool__`.
:mod:`django.contrib.sitemaps`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/docs/topics/http/sessions.txt b/docs/topics/http/sessions.txt
index 797b49ffa2..6070b3e4ef 100644
--- a/docs/topics/http/sessions.txt
+++ b/docs/topics/http/sessions.txt
@@ -191,6 +191,17 @@ You can edit it multiple times.
Example: ``'fav_color' in request.session``
+ .. method:: __bool__()
+
+ .. versionadded:: 6.1
+
+ Returns the inverse of :meth:`is_empty`. This allows checking if a
+ session has data::
+
+ if request.session:
+ # Session has data or a key
+ pass
+
.. method:: get(key, default=None)
.. method:: aget(key, default=None)
diff --git a/tests/sessions_tests/tests.py b/tests/sessions_tests/tests.py
index 81c2e7a5de..f23fa9778d 100644
--- a/tests/sessions_tests/tests.py
+++ b/tests/sessions_tests/tests.py
@@ -1373,3 +1373,14 @@ class SessionBaseTests(SimpleTestCase):
def test_is_empty(self):
self.assertIs(self.session.is_empty(), True)
+
+ def test_bool(self):
+ # Empty session is falsy
+ self.assertIs(bool(self.session), False)
+ # Session with data is truthy
+ self.session["foo"] = "bar"
+ self.assertIs(bool(self.session), True)
+ # Session with key but no data is truthy
+ session_with_key = SessionBase()
+ session_with_key._session_key = "testkey1234"
+ self.assertIs(bool(session_with_key), True)