Placement of contextmanger usage within code

14 views
Skip to first unread message

likage

unread,
Jul 10, 2019, 4:12:20 PM7/10/19
to Python Programming for Autodesk Maya
I have created a contextmanager that tracks/registers for undo and I have some questions, mostly on what is the best way to use/ code it as I am unsure which is the best approach.

In my utils.py file, I place the contextmanger class within, along with other utility functions that are used in main.py file.
Here is a snippet of it.

main.py
class MyTool(MayaQWidgetDockableMixin, QtGui.QWidget):
    def__init__
(self,parent=None):
        ...
        self.undo_manager = utils.UndoManager()
        self.ui.resetButton.clicked.connect(self.reset_keys)

   
def reset_keys(self, attr_list):
        # with self.undo_manger:
        utils
.remove_keys(attr_list)


utils.py
class UndoManager(object):
    def __init__(self):
      pass

    def __enter__(self):
        cmds.undoInfo(openChunk=True)
        
    def __exit__(self, type, value, traceback):
        cmds.undoInfo(closeChunk=True)

def remove_keyed(attr_list):
    with UndoManager:
        for attr in attr_list:
            cmds.cutKey(attr)


My question here is, where is the most appropriate place for me to place the use of `UndoManager`, in utils.py or in main.py (in coding standards)? And/Or if the use of the contextmanager that I have wrote or use is correct?

Currently, I have been placing them in utils.py, and in my other files, I also did use `self.undo_manager` as the convention to track/register the actions for undo. So far it seems to work but would like to keep my code 'clean' and tidy.


Michael Boon

unread,
Jul 15, 2019, 10:36:55 PM7/15/19
to Python Programming for Autodesk Maya
It's hard to be confident without knowing a lot more about your code, but I would put it in utils.py.

I wouldn't use "self.undo_manager" though. That adds unnecessary indirection (making things harder to track down when chasing bugs), plus, I'm not confident it would enter and exit correctly when used like that. I would say "with utils.UndoManager():"

That's just me though :)
Reply all
Reply to author
Forward
0 new messages