[Python-ideas] making a module callable

Ben Finney ben+python at benfinney.id.au
Mon Nov 25 04:58:11 CET 2013


Greg Ewing <greg.ewing at canterbury.ac.nz> writes:

> Ben Finney wrote:
> > It's more convenient to look in “the sequence of command-line
> > parameters” for all the command-line parameters, without
> > special-casing the command name.
>
> But you hardly ever want to process argv[0] the same way as the rest
> of the arguments, so you end up treating it as a special case anyway.

This isn't about *processing* that argument; it's about *receiving* it
in the first place to the function. Having it omitted by default means
there's a special case just to *get at* the first command-line
argument::

    def __main__(argv_without_first_arg=None):
        if argv is None:
            argv = sys.argv[1:]
        first_arg = sys.argv[0]

Which still sucks, because how do I then pass a different command name
to ‘__main__’ since it now expects to get it from elsewhere?

Much better to have the interface just accept the *whole* sequence of
command line arguments:

    def __main__(argv=None):
        if argv is None:
            argv = sys.argv

Now it's completely up to the caller what the command-line looks like,
which means the ‘__main__’ code needs no special cases for using the
module as a library or for unit tests etc. You just construct the
command-line as you need it to look, and pass it in to the function.

> It seems to me we only think of it as a command line argument because
> C traditionally presents it that way.

What C does isn't relevant here. I think of the whole command line as a
sequence of arguments because that's how the program receives the
command line from the Python interpreter. Mangling it further just makes
a common use case more difficult for no good reason.

> I don't think it's something that would naturally come to mind
> otherwise. I know I found it quite surprising when I first encountered
> it.

Many useful things are surprising when one first encounters them :-)

-- 
 \        “I don't accept the currently fashionable assertion that any |
  `\       view is automatically as worthy of respect as any equal and |
_o__)                                   opposite view.” —Douglas Adams |
Ben Finney



More information about the Python-ideas mailing list