4

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?

someonewithpc
  • 12,381
  • 6
  • 55
  • 89
p2or
  • 15,860
  • 10
  • 83
  • 143

2 Answers2

4

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

someonewithpc
  • 12,381
  • 6
  • 55
  • 89
4

Same with xor:

obj.show_name = obj.show_name ^ 1

Or you can avoid repeating the attribute with:

    obj.show_name ^= 1
ideasman42
  • 47,387
  • 10
  • 141
  • 223
JuhaW
  • 1,856
  • 13
  • 18
  • 2
    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