# How to easily toggle a Boolean property?

I want to write a simple toggle for an existing UI Boolean property. Every time I run the following code Blender should either show or hide the name of the object in the Viewport, depending on the current state. It works fine, but I wondering if it is really necessary to to call the property 3 times for this easy task.

import bpy

obj = bpy.context.active_object

if obj.show_name == True:
obj.show_name = False
else:
obj.show_name = True


Is there a more elegant way to write this?

• This is technically a programming question... even though it is about the script, it would be more topical on SO – GiantCowFilms Jan 11 '15 at 18:40

This can trivially be done as:

obj.show_name = not obj.show_name


Which basically says: if True, make it not True (i.e. False), else if False, make it not False (i.e. True).

• I was 1 second behind.... Python syntax! – GiantCowFilms Jan 11 '15 at 18:39
• Would != be valid... just curious? – GiantCowFilms Jan 11 '15 at 18:44
• @GiantCowFilms No - != is a Boolean operator, it doesn't assign the value to the left hand operand – someonewithpc Jan 11 '15 at 18:51
• Sine when is !var possible in Python? It's a SyntaxError in 3.4. What's allowed and does not require a repetition of the variable name is the boolean shorthand for ixor(): obj.show_name ^= True – CodeManX Jan 12 '15 at 9:21

Same with xor:

obj.show_name = obj.show_name ^ 1


Or you can avoid repeating the attribute with:

    obj.show_name ^= 1

• It provides exact answer to the question "Every time I run the following code Blender should either show or hide the name of the object in the Viewport, depending on the current state." If this does not really answer the question, whats the point of the first one liner "answer". – JuhaW May 10 '16 at 22:45