Is there a way to negate a boolean returned to variable?

Question:

I have a Django site, with an Item object that has a boolean property active. I would like to do something like this to toggle the property from False to True and vice-versa:

def toggle_active(item_id):
    item = Item.objects.get(id=item_id)
    item.active = !item.active
    item.save()

This syntax is valid in many C-based languages, but seems invalid in Python. Is there another way to do this WITHOUT using:

if item.active:
    item.active = False
else:
    item.active = True
item.save()

The native python neg() method seems to return the negation of an integer, not the negation of a boolean.

Thanks for the help.

Asked By: Furbeenator

||

Answers:

You can do this:

item.active = not item.active

That should do the trick 🙂

Answered By: jdcantrell

item.active = not item.active is the pythonic way

Answered By: Serdalis

I think you want

item.active = not item.active
Answered By: srgerg

The negation for booleans is not.

def toggle_active(item_id):
    item = Item.objects.get(id=item_id)
    item.active = not item.active
    item.save()

Thanks guys, that was a lightning fast response!

Answered By: Furbeenator

Its simple to do :

item.active = not item.active

So, finally you will end up with :

def toggleActive(item_id):
    item = Item.objects.get(id=item_id)
    item.active = not item.active
    item.save()
Answered By: Yugal Jindle

Another (less concise readable, more arithmetic) way to do it would be:

item.active = bool(1 - item.active)
Answered By: miku
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.