Reputation: 75
I am building a todo-list CLI and it requires a del argument for deleting an entry from the list. The CLI usage is as given below
$ ./todo help
Usage :-
$ ./todo add "todo item" # Add a new todo
$ ./todo ls # Show remaining todos
$ ./todo del NUMBER # Delete a todo
$ ./todo done NUMBER # Complete a todo
$ ./todo help # Show usage
$ ./todo report # Statistics
But in python( I am using python 3.8.3) when using the argparse module for parsing the arguments from command line the code for the above specified feature is as follows
parser.add_argument("--del", type=int, help="Delete a todo")
The problem arises since del is a reserved keyword by python for completely different purpose and so it gives a syntax error when reading that line of code
print (args.del)
Error message is as follows
File "todo.py", line 24
if args.del:
^
SyntaxError: invalid syntax
Is there a solution to use del as per requirements of the project.
Upvotes: 1
Views: 702
Reputation: 6474
As del
is a reserved keyword it cannot be used. However you can use dest
to create a custom attribute and not use the auto generated attribute.
parser = argparse.ArgumentParser()
parser.add_argument('--del', dest='delete')
parser.parse_args('--del XXX'.split())
Results in: Namespace(delete='XXX')
Upvotes: 2
Reputation: 32244
The dest
parameter can be passed to argparse.add_argument
to change the eventual attribute name that the argument will be bound to. You can use this to change "del" to a non-reserved keyword attribute name
parser.add_argument('--del', type=int, help='Delete a todo', dest='should_delete')
Upvotes: 5
Reputation: 95907
del
is a reserved keyword. It cannot be used as an attribute.
In this case, you can use a string to dynamically access this attribute, however:
getattr(args, "del")
However, it is probably better to change this name.
Upvotes: 2