I am creating a small Python script to manage various classes of servers (FTP, HTTP, SSH, etc.)
On each type of server, we can perform various types of actions (deploy, configure, verify, etc.)
I have a Server base class, and then a separate class for each type of server that inherits from this:
class Server: ... def check(): ... class HTTPServer(Server): def check(): super(HTTPServer, self).check() ... class FTPServer(Server): def check(): super(FTPServer, self).check() ...
An example command line might be:
my_program deploy http
Two required arguments are needed from the command line:
- Operation to perform
- Type of server to create / manage
I used to use the argparse and store operations and used dict to map the command line option to the actual class name and function name. For instance:
types_of_servers = { 'http': 'HTTPServer', 'ftp': 'FTPServer', ... } valid_operations = { 'check': 'check', 'build': 'build', 'deploy': 'deploy', 'configure': 'configure', 'verify': 'verify', }
(In my actual code, valid_operations was not a 1: 1 naive mapping.)
And then using pretty awful code to create the desired type of object and call the correct class.
Then I decided to use the argparse subparsers function to do this instead. Therefore, I performed each operation (validation, assembly, deployment, etc.) subparser .
Usually I can associate each subcommand with a specific function and call it. However, I do not want to just call the general function check() - I need to first create the correct type of the object, and then call the corresponding function inside this object.
Is there a good or pythonic way to do this? Preferably one that doesn't require a lot of hard coding or poorly designed if / else loops?