0

I am learning to build a product cart app for an online shop. But while I was reading other's app, I found something I couldn't understand.

settings.py>
CART_ID = 'cart_in_session'


cart.py>
from decimal import Decimal
from django.conf import settings
from shop.models import Product

from coupon.models import Coupon

class Kart(object):
    def __init__(self, request):
        self.session = request.session
        kart = self.session.get(settings.CART_ID)
        if not kart:
            kart = self.session[settings.CART_ID] = {}
        self.kart = kart

I couldn't get this part of code snippet: if not kart: kart = self.session[settings.CART_ID] = {}

It has two "=" symbol and I am wondering if it's for assignment and if it's really an assignment, then why it sets CART_ID's value ("cart_in_session" for its matched key CART_ID) to {}

BangolPhoenix
  • 383
  • 1
  • 4
  • 16

1 Answers1

1

This statement both creates a new kart and creates the session key for the cart, setting both to an empty cart {}.

  • You can assign multiple variable to the same value by chaining = in python. It's the same as these three lines:

    temp = {}
    kart = temp    
    self.session[settings.CART_ID] = temp
    

    Thus assigning both kart and the session variable to the same empty dictionary.

  • CART_ID is a strangely chosen name. It's basically the key that's used to store the card in the session. I would have named it CART_KEY. All this code does is initialising an empty cart and adding it to the session.

Note: See here for more on chained assignment in Python.

Note2: Since we're assigning a dictionary, both kart and session[CART_ID] point to the same dictionary in memory. If you change kart by adding a product, it will automatically be reflected in the session and vice-versa.

Note3: @DanielRoseman's code makes this much more clear.

dirkgroten
  • 20,112
  • 2
  • 29
  • 42
  • I appreciate your answer. So this code isn't efficient in terms of memory management since it assigns two separate things to the same dictionary? – BangolPhoenix Aug 15 '19 at 04:39