1

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?

willer2k
  • 506
  • 1
  • 6
  • 17
  • `not x` will yield True for `x` being any element (may not be limited to) from the following tuple: `(None, 0, 0L, 0.0, "", (), [], set(), {})`. In *Django*'s, case there are more such cases: for example if `x` would be an __empty__ `QuerySet`. Try printing the value (and maybe type?) of `cart` (`self.session.get(..`). This isn't related to `settings.CART_SESSION_ID`. – CristiFati Jul 11 '17 at 23:37
  • So what you are saying is "self.session.get(settings.CART_SESSION_ID)" does not return "cart" that was assigned in the settings.py file? If that is the case, why is CART_SESSION_ID = 'cart' declared in the settings.py file? – willer2k Jul 12 '17 at 01:24
  • I'm not sure what `self.session` is (I'd say it's a _dict_ since its `get` method is called), that's why I suggested printing (or if you're using an _IDE_ step by step debugging). So `self.session.get('cart')` will probably return `None`. But it looks like to me that you're confusing `settings.CART_SESSION_ID`'s __value__ `'cart'` with the __variable__ `cart` (from `__init__`). They are not at all related. – CristiFati Jul 12 '17 at 05:53

1 Answers1

0

Yes, it's redundant in you example as no actual session handling mechanism is used in django-by-example tutorial.

The idea that actually has to be implemented is that it will execute when the CART_SEESION_ID is False or None therefore a new car has to be created so that a default cart (empty dict) will be generated.

So, yes, you are right, in your example the if line will never execute, but this example will never be used in real world apps.

pythad
  • 4,241
  • 2
  • 19
  • 41