When building a UI in maya, what's the best way to deal with all of my callback functions?

When building a UI for Maya, I always end up with many callback functions defined inside my UI class. It starts to get difficult to find exactly which function I am looking for.

Here is an image of my (still only getting started!) outliner.

Everything called: cmd_ or make_cmd_ are callbacks, and they end up taking up almost half of all my functions. What is the best way to tidy these up? should I make them inner functions inside the method that creates the field that uses the callback? Should I put them in their own module (probably not since they deal with class attributes a lot of the time)? should I completely change the way I make UIs?

Callbacks are fine in classes but as they are used internally i’d probably prefix them with an underscore. In addition i’d not name them cmd_ as thats short for command, rather i’d prefix them cb_ or have callback in their name.

In terms of code structure i tend to declare them near the top of the class. I tend to do this with most blobs of types - properties, classmethods, setters etc…

For UI related events I tend to do things like:
_on_some_button_clicked
_on_enabled_check_toggled
etc…

For system callbacks like say a scene save event I’d probably do something like:
_on_scene_save_callback

As for how I structure them in the code, usually I’ll group event handlers together, either as just top level functions or as methods on a class.

While I don’t tend to do a lot of Maya specific UI these days, when I did I tended to just use mGui. Which would lead me to structure my code a bit differently than when I had done a lot of just cmds/pymel driven UI work.

1 Like

You might want to look at subdividing the class into smaller pieces with more narrowly defined responsibilities – that will at least cut down on the mental overhead. Frequently you want a very dumb UI class that only handles display of information and a separate functional class that uses that information – that let you keep the important working pieces separate from the fiddly bits that just make the display prettier or more responsive.

You can also make a nice separation between the ‘public’ parts of your functionality and the ‘private parts’ by using leading underscores . While you need things like little functions that highlight one control when something is selected or gray things out when an option is not compatible but you don’t want to confuse them with the key functionality of the piece.

Lastly, if the functions are essentially static – that is, if they don’t share state with the UI at all – they don’t need to be part of the class anyway – if you are making a method with a self in it and you never actually use self inside the function, it doesn’t need to be part of the class.