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

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.

83293 次浏览

You can do this:

item.active = not item.active

That should do the trick :)

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

I think you want

item.active = not item.active

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!

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

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

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