I found a very useful answer for this question below, but it is a bit unclear to me. Why is "if not someobj:" better than "if someobj == None:" in Python?
From my understanding of how " if not x: do something " works is that "if not" just checks to see if the value of x is True or not. If it isn't, it will do something.
I am learning Django and in one of the examples I am trying to understand, they use the "if not:" logic to set up a shopping cart.
Here is how the code is written by someone much smarter than I am:
in settings.py file:
CART_SESSION_ID = 'cart'
in cart.py file:
from django.conf import settings
class Cart(object):
def __init__(self, request):
"""
Initialize the cart.
"""
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
# save an empty cart in the session
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
So it seems to me like CART_SESSION_ID is a string initially with the value 'cart'.
The variable cart must be a dictionary to store product ids, price and quantity.
Since the initial value of "cart" is a string with a value, would "if not cart:" return "True", therefore, never execute?