I am updating as well as trying to optimize an add-on that I haven't touched in a couple of years. I learned python as I was making that add-on back in the day, actually, and now am reading that the code that I came up with is what's commonly referred to as "Spaghetti Code".

Anyway, my add-on, amongst other things, is doing a certain number of bmesh extrudes each time the modal runs. So in order to be able to control the amount of extrudes it does, I found that the old add-on is deleting all the previously extruded vertices, in the beginning of def modal(). And so it doesn't end up with an ungodly amount of extrudes due to the mouse moving hundreds of pixels, but rather a certain number that the user can control.

So in the old add-on, which I'm trying to optimize and update, the deletion apparently only works if bm is made into a global variable. I've read that global variables are at least something to be careful with, so I'm not sure if this is 'A-OK'? From what I understand, my past self figured out that without having access to the bmesh data from the previous 'modal run' he would not be able to delete the vertices and avoid a ton of extrudes, and that exposing bmesh.from_edit_mesh() globally would solve that problem. However, can anyone suggest a better way? Or perhaps confirm if making bm a global variable is a decent solution for a blender modal operator?

def modal(self, context, event):

    global bm

    obj = bpy.context.edit_object
    me = obj.data
    bm = bmesh.from_edit_mesh(me)

1 Answer 1


It's a bit opinion-based but I think I may be able to help you and it doesn't fit in a comment.

global is not intrinsically bad but it is advised not to use it when you can do without it because it can lead to pretty nasty errors, especially with beginners who can't make sense of convoluted error messages : namespace clashing, locals shadowing, etc.

Also, particularly in the context of Blender, it might very well crash your file every time you try to CTRL Z your operator, because the API is just an interface to objects that are stored in memory. So your global bm might as well point to a totally unrelated part of the stack and lead to a crash. It also won't be there anymore when you save & load your file, but since it's a modal operator you shouldn't have to worry about it.

And bmesh is a particular module so you might want to make sure you clean it when you're done with it. See : https://docs.blender.org/api/current/bmesh.html#mesh-access I don't know of a way to reliably store a bmesh in a blend file since the module is abstracted from blender logic. You'd have to serialize it and you would then lose any optimization you'd have gained using this method.

If you can live with these limitations and your operator works, then by all means use whatever convoluted lines of codes you want to achieve your goal :)


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .