The answer here is “It depends, but it’s dangerous”. There’s a good chance you probably should keep the instance around, though.
First, the “Danger” part. The danger of doing something like this is python’s garbage collection can come through and delete the memory that controls your ui. Basically, even though the UI is using the button, Python could say “Well, since I don’t see anything using this memory, I can just delete it.” Then when the UI goes to do something with the button, it can look for something that isn’t there, and the program would crash.
If you ever look into how the C code for python works, there is a thing you have to deal with called “Reference Counting”. The reference count is a number that keeps track of how many variables are referencing a piece of data. If you don’t know what that is, definitely google it. There are some good write-ups online. If you still need more help after that, feel free to ask. The thing you need to know, however, is that when the reference count reaches 0, python’s garbage collector can (but not necessarily immediately) come through and free up the memory for that data.
So, In your line
my_module.UI(), what technically happens under the hood is: A temporary instance of your class gets created, and the reference counter is increased to 1. Then, because that instance isn’t assigned to anything, the reference counter drops back down to 0, so that means it’ll get garbage collected at some point. Garbage collection for a class will go through and delete every variable stored in that class (ie. anything you stored using
self.myButton = ButtonObject()) .
Now for the “It Depends” part.
How you define the class, how you use
self variables, and which UI system you use all influence how your UI data is stored, and how it’s reference counts change. You could be doing something that will absolutely work (maya
cmds stores the data outside of python), or you could have written a crash waiting to happen (Qt/pyside keeps the data inside python, but some references stick around). Without more information (or, even better, the code) I can’t tell you which yours is.