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

PythonDjango

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

You can do this:

item.active = not item.active

That should do the trick :)

Solution 2 - Python

I think you want

item.active = not item.active

Solution 3 - Python

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

Solution 4 - Python

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

item.active = bool(1 - item.active)

Solution 5 - Python

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!

Solution 6 - Python

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()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFurbeenatorView Question on Stackoverflow
Solution 1 - PythonjdcantrellView Answer on Stackoverflow
Solution 2 - PythonsrgergView Answer on Stackoverflow
Solution 3 - PythonSerdalisView Answer on Stackoverflow
Solution 4 - PythonmikuView Answer on Stackoverflow
Solution 5 - PythonFurbeenatorView Answer on Stackoverflow
Solution 6 - PythonYugal JindleView Answer on Stackoverflow