Try calling these before and after the function.
cmds.undoInfo(chunkName="myFunction", openChunk=True)
my_function()
cmds.undoInfo(chunkName="myFunction", closeChunk=True)
This will cause all undoable calls to maya.cmds to be grouped together into a "chunk". It's important to call closeChunk after, as it could otherwise make Maya and undoing unstable. To make it more safe, you could use something like a context manager.
@contextlib.contextmanager
def undo_chunk(name):
try:
cmds.undoInfo(chunkName=name, openChunk=True)
yield
finally:
cmds.undoInfo(chunkName=name, closeChunk=True)
with undo_chunk("myFunction"):
my_function()
That way, even if your function fails or throws an exception, the chunk will still be closed.