Search code examples
pythonpython-3.xargparsedel

Python "del" syntax error when used as a variable name


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.


Solution

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