Issue 32283: Cmd.onecmd documentation is misleading (original) (raw)
The documentation for Cmd.onecmd is misleading. It says that "This may be overridden, but should not normally need to be; see the precmd() and postcmd() methods for useful execution hooks."
https://github.com/python/cpython/blob/v3.7.0a3/Lib/cmd.py#L193
However a common idiom is to call onecmd directly to process commands coming from sys.argv. This shows up in the Cmd entries the Python MOTW site for instance.
https://pymotw.com/3/cmd/#commands-from-sys-argv
From the docs you might think that precmd and postcmd are called when you call onecmd directly this way. However this is not true - they are only called in the cmdloop method.
https://github.com/python/cpython/blob/v3.7.0a3/Lib/cmd.py#L137
Moving the precmd and postcmd methods into onecmd would make the onecmd docs make more sense. Then they could be used in lieu of overriding onecmd for all uses of onecmd - inside of cmdloop and on its own. But loads of code depends on current behaviour.
So instead something in the docs to indicate that those hooks only work when onecmd is called inside cmdloop would be good. Perhaps like so:
"""Interpret the argument as though it had been typed in response
to the prompt.
This may be overridden, but should not normally need to be;
see the precmd() and postcmd() methods for useful execution hooks
when onecmd() is called from cmdloop(). When onecmd() is called
directly, make sure to call precmd() and postcmd() yourself.
The return value is a flag indicating whether interpretation of
commands by the interpreter should stop.
"""