Instatiating module / Reusing module of command-line tool

Cameron Simpson cs at cskk.id.au
Sat May 7 02:28:54 EDT 2022


On 06May2022 14:11, Loris Bennett <loris.bennett at fu-berlin.de> wrote:
>ram at zedat.fu-berlin.de (Stefan Ram) writes:
>>   If you need a class, you can write a class.
>>
>>   When one imports a module, the module actually gets executed.
>>   That's why people write "if __name__ == '__main__':" often.
>>   So, everything one wants to be done at import time can be
>>   written directly into the body of one's module.
>
>So if I have a module which relies on having internal data being set
>from outside, then, even though the program only ever has one instance
>of the module, different runs, say test and production, would require
>different internal data and thus different instances.  Therefore a class
>seems more appropriate and it is more obvious to me how to initialise
>the objects (e.g. by having the some main function which can read
>command-line arguments and then just pass the arguments to the
>constructor.
>
>I suppose that the decisive aspect is that my module needs
>initialisation and thus should to be a class.  Your examples in the
>other posting of the modules 'math' and 'string' are different, because
>they just contain functions and no data.

Yeah, I do this quite a bit. So I might have the core class which does 
it all:

    class Thing:
        def __init__(self, whatever...):
            ....

and if I'm exercising this from the command line I'll write a main 
function:

    def main(argv):
        cmd = argv.pop(0)
        ... use the arguments to specify data files or modes or whatever 
        ...
        obj = Thing(...init the thing...)
        obj.do_something(...)

That is usually the top thing, after the imports but before everything 
else. Then right down the bottom:

    if __name__ == '__main__':
        sys.exit(main(sys.argv))

for running the module in command line mode:

    python3 -m the.module.name args here ...

That way you can import it elsewhere for the "thing" class and also do 
basic command line stuff with it directly.

Cheers,
Cameron Simpson <cs at cskk.id.au>
way I'll probably write a class for a command line.


More information about the Python-list mailing list