Can't deselect vertex in this way... why not?

I can’t tell if this is a bug.

The blend file contains two scripts side by side for easy comparison. The scripts should do opposite things.

The left script selects a random vert and moves it up. This works correctly.

The right script should DESELECT a random vert and move it down, but it doesn’t deselect it, it just moves it down.

Could someone tell me why? Thanks!

Attachments

select_deselect.blend (485 KB)

it’s an API limitation, you can’t deselect vertices. Using bmesh module it’s possible however:


import bpy
from random import choice
import bmesh
'''This script is supposed to DEselect a random vert and move it down, but doesn't work.'''


#This mesh starts with all of its verts selected...
obj = bpy.data.objects['start selected']

#make sure the right mesh is the active one...
for o in bpy.data.objects: o.select = False
bpy.context.scene.objects.active = obj
obj.select = True
if obj.mode != 'EDIT':
    bpy.ops.object.mode_set(mode='EDIT')
    
bm = bmesh.from_edit_mesh(obj.data)
try:
    random_vert = choice([vert for vert in bm.verts if vert.select])
except IndexError:
    pass
else:
    random_vert.co[2] -= .5
    random_vert.select_set(False)

made choice() safer and added if vert.select to list comprehension to move selected verts only