Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...