1

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)

syntax highlight image

Error message is as follows

File "todo.py", line 24
    if args.del:
            ^
SyntaxError: invalid syntax

syntax error image

Is there a solution to use del as per requirements of the project.

Sarath Sajan
  • 45
  • 2
  • 10

3 Answers3

5

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')
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50
2

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.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
2

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')

rfkortekaas
  • 6,049
  • 2
  • 27
  • 34