2

I want to have a python command line argument --lambda, but I can't access it as lambda is a python keyword.

import argparse

p = argparse.ArgumentParser()
p.add_argument('--lambda')
args = p.parse_args()

print args.lambda

I get:

print args.lambda
                ^
SyntaxError: invalid syntax

How can I do this?

2 Answers 2

4

You can add a different name for the attribute with dest e.g.

import argparse

p = argparse.ArgumentParser()
p.add_argument('--lambda', dest='llambda')
args = p.parse_args()

print args.llambda
Sign up to request clarification or add additional context in comments.

Comments

1

argparse uses hasattr and getattr to set values in the Namespace. This allows you to use flags/dest that are not valid in the args.dest syntax. Here the problem is with a restricted key word. It could also be a string with special characters. So getattr(args, 'lambda') should work.

vars(args) creates a dictionary, allowing you to use vars(args)['lambda'].

But changing the dest is a cleaner solution. That's part of why that parameter is allowed.

(For a positional argument, choose a valid dest right away.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.