I was recently using the cmd module for a project where my CLI
could connect to and interact with another host.  I implemented prompt in
such a way that it would show the IP address when connected.  I.e.,

class MyCmd(cmd.Cmd):
    ...

    @property
    def prompt(self) -> str:
        if self.remote_host.connected():
            return f'> ({self.remote_host.ip}) '
        else:
            return '> '

This worked perfectly fine... until I ran mypy.  mypy complained because,
in cmd.Cmd, prompt is a class attribute.

Looking at cmd.py, this seems like an odd design choice as all of the
references to cmd are through the instance (i.e., self.prompt).

While it's easy to fix this in my subclass by overriding the onecmd method
and setting self.prompt there, this seems kludgy ("Beautiful is better than
ugly").  More importantly, this whole arrangement obscures the fact that
prompt is a de facto attribute of the instance and not the class.  It's not
the class that's displaying the prompt but the instance.

It seems more intuitive for cmd.Cmd to be implemented thus:

   class Cmd:
        PROMPT = '> '

        def __init__(self):
            ...

            self.prompt = self.PROMPT
_______________________________________________
Python-Dev mailing list -- python-dev@python.org
To unsubscribe send an email to python-dev-le...@python.org
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at 
https://mail.python.org/archives/list/python-dev@python.org/message/PCXEIWFOJ23ZVFWXW7NGTOSMAKKGMQ4Z/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to