I'm trying to write a Python script to create a CLI command. To make it more readable, I'm creating argparse.ArgumentParser
object directly in the class __init__()
(not in the '__main__'
part of the script as is usually the case in tutorials).
The approach included in the sample code below works but it looks messy.
I wonder whether this would be the correct way to do it or I should do something else. (Sorry for newbie question.)
import argparse
class Command:
def __init__(self, *args):
self.parser = argparse.ArgumentParser(usage='command [--first] [--second]', description='This is a sample command')
self.parser.add_argument('--first', type=str, required=True, help='first argument', dest='first_argument')
self.parser.add_argument('--second', type=str, required=True, help='second argument', dest='second_argument')
args = self.parser.parse_args()
self.first_argument = args.first_argument
self.second_argument = args.second_argument
def some_operation(self):
concatenated_str = self.first_argument + self.second_argument
return concatenated_str
if __name__ == '__main__':
command = Command() # creating class instance
print(command.some_operation())
Putting it in a separate class method in this way doesn't work and produces AttributeError
:
# Code above
def set_params(self):
args = self.parser.parse_args()
self.first_argument = args.first_argument
self.second_argument = args.second_argument
return self.first_argument, self.second_argument
# Code below