Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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.

like image 514
Furbeenator Avatar asked Dec 01 '11 00:12

Furbeenator


People also ask

How do you negate a boolean?

Use the not Operator to Negate a Boolean in Python The not operator in Python helps return the negative or the opposite value of a given boolean value. This operator is used by placing the not operator as a prefix of a given boolean expression.

What is the opposite of boolean return?

The ! is a logical operator that will convert a value to its opposite boolean. Since JavaScript will coerce values, it will “convert” a value to its truthy/falsey form and return the opposite boolean value.

How do you negate a boolean value in an array?

Numpy Array and ~ to Negate Boolean in Python By using the numpy array library and the bitwise operator '~' pronounced as a tilde. We can easily negate a Boolean value in Python. The tilde operator takes a one-bit operand and returns its complement. If the operand is 1, it returns 0, and vice-versa.

What operator is used to negate or take the opposite of a boolean value?

The logical NOT ( ! ) operator (logical complement, negation) takes truth to falsity and vice versa. It is typically used with boolean (logical) values. When used with non-Boolean values, it returns false if its single operand can be converted to true ; otherwise, returns true .


2 Answers

You can do this:

item.active = not item.active 

That should do the trick :)

like image 65
jdcantrell Avatar answered Sep 22 '22 19:09

jdcantrell


I think you want

item.active = not item.active 
like image 21
srgerg Avatar answered Sep 21 '22 19:09

srgerg