4
$\begingroup$

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?

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

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

| improve this answer | |
$\endgroup$
  • 2
    $\begingroup$ I was 1 second behind.... Python syntax! $\endgroup$ – GiantCowFilms Jan 11 '15 at 18:39
  • $\begingroup$ Would != be valid... just curious? $\endgroup$ – GiantCowFilms Jan 11 '15 at 18:44
  • 2
    $\begingroup$ @GiantCowFilms No - != is a Boolean operator, it doesn't assign the value to the left hand operand $\endgroup$ – someonewithpc Jan 11 '15 at 18:51
  • 1
    $\begingroup$ 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 $\endgroup$ – CodeManX Jan 12 '15 at 9:21
3
$\begingroup$

Same with xor:

obj.show_name = obj.show_name ^ 1

Or you can avoid repeating the attribute with:

    obj.show_name ^= 1
| improve this answer | |
$\endgroup$
  • 2
    $\begingroup$ 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". $\endgroup$ – JuhaW May 10 '16 at 22:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.