[Django]-Are booleans mutable in python?

11👍

Answering your question:

Are booleans mutable in python?

Yes and no. Variables that are assigned a boolean value are (probably always, and definitely in this case) mutable, yes. They’re also not restricted to being assigned boolean values, as variables are not staticly typed.

But the booleans True and False themselves are not mutable. They are singletons that cannot be modified.

Looking at your actual code:

if success = 1:

Is not valid syntax, you want a == there. Also, idiomatically speaking you should not use 0 and 1 for success and failure values you should use True and False. So you should refactor to something like this:

def update(request):
    success = False

    try:
        product = Mattress.objects.get(id=id)
        success = True
    except Mattress.DoesNotExist:
        pass

    if success:
        return render_to_response("success.html")
    else:
        return render_to_response('failure.html')

1👍

Yes. success will be changed to 1 on success.

1👍

There are a few things wrong with this snippet.

  1. Firstly, you’re not using a boolean type. Python’s booleans are True and False.
  2. Second, you’re not comparing in your if statement. That line isn’t valid in Python 3. What you’re looking for is: if success == 1: or if success == True:
  3. You would still be able to assign a boolean value to a variable regardless of boolean immutability. I believe they are stored as a primitive type, so they’re as immutable as any other primitive type.
👤Wug

1👍

You should consider using an actual boolean and not an integer. You can set success to true or false and Python will interpret them as keywords to the values of 1 and 0. Using numbers can be a bit tricky as some languages interpret things different. In some languages 0 is false but any value besides 0 is considered true. However the answer to your question is yes, it will work just fine.

1👍

Probably the question you are asking is not even related with the problem you are trying to solve. I think there is a a Pythonic way to achieve what you want by:

def update(request):
    try:
        product = Mattress.objects.get(id=id)
    except Mattress.DoesNotExist:
        template_name = 'failure.html'
    else:
        template_name = 'success.html'

    return render_to_response(template_name)

Basically if the exception is thrown, i.e., the template you will render will be ‘failure.html’. On the other hand, if the query is performed successfully, ‘success.html’ will be rendered.

Leave a comment