Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's argparse: How to use keyword as argument's name

lambda has a keyword function in Python:

f = lambda x: x**2 + 2*x - 5

What if I want to use it as a variable name? Is there an escape sequence or another way?

You may ask why I don't use another name. This is because I'd like to use argparse:

parser = argparse.ArgumentParser("Calculate something with a quantity commonly called lambda.")
parser.add_argument("-l","--lambda",help="Defines the quantity called lambda", type=float)
args = parser.parse_args()

print args.lambda # syntax error!

Script called with --help option gives:

...
optional arguments
  -h, --help            show this help message and exit
  -l LAMBDA, --lambda LAMBDA
                        Defines the quantity called lambda

Because of that, I would like to stay with lambda as the variable name. Solutions may be argparse-related as well.

like image 314
unndreay Avatar asked Aug 04 '14 12:08

unndreay


People also ask

What are keyword arguments in Python?

What are keyword arguments? Let’s take a look at what keyword arguments (also called “named arguments”) are. First let’s take this Python function: When we call this function, we can pass each of our three arguments in two different ways. We can pass our arguments as positional arguments like this:

What is the use of add_argument in Python argparse?

The Python argparse module provides a special class that can be sent to the type keyword argument of add_argument, which is argparse.FileType. The argparse.FileType class expects the arguments that would be sent to Python’s open function, excluding the filename (which is what is being provided by the user invoking the program).

What is the difference between *keyword and argparse in Python?

*keyword and **keyword are for passing parameters/stuff to classes/functions/methods INSIDE the python code. argparse is used to pass arguments/options into the python program from outside/the commandline. So you're not going to get a 1 for 1 replication of it.

How does Python know the name of my arguments?

When we use keyword/named arguments, it’s the name that matters, not the position: So unlike many other programming languages, Python knows the names of the arguments our function accepts. If we ask for help on our function Python will tell us our three arguments by name:


1 Answers

You can use dynamic attribute access to access that specific attribute still:

print getattr(args, 'lambda')

Better still, tell argparse to use a different attribute name:

parser.add_argument("-l", "--lambda",
    help="Defines the quantity called lambda",
    type=float, dest='lambda_', metavar='LAMBDA')

Here the dest argument tells argparse to use lambda_ as the attribute name:

print args.lambda_

The help text still will show the argument as --lambda, of course; I set metavar explicitly as it otherwise would use dest in uppercase (so with the underscore):

>>> import argparse
>>> parser = argparse.ArgumentParser("Calculate something with a quantity commonly called lambda.")
>>> parser.add_argument("-l", "--lambda",
...     help="Defines the quantity called lambda",
...     type=float, dest='lambda_', metavar='LAMBDA')
_StoreAction(option_strings=['-l', '--lambda'], dest='lambda_', nargs=None, const=None, default=None, type=<type 'float'>, choices=None, help='Defines the quantity called lambda', metavar='LAMBDA')
>>> parser.print_help()
usage: Calculate something with a quantity commonly called lambda.
       [-h] [-l LAMBDA]

optional arguments:
  -h, --help            show this help message and exit
  -l LAMBDA, --lambda LAMBDA
                        Defines the quantity called lambda
>>> args = parser.parse_args(['--lambda', '4.2'])
>>> args.lambda_
4.2
like image 108
Martijn Pieters Avatar answered Sep 20 '22 11:09

Martijn Pieters