Skip to content
Advertisement

How to use a lambda as parameter in python argparse?

help_f= "The Syntax is  lambda x: f(x), where f(x) is the function in python lenguage"
parser.add_argument("-f",dest="f", type=function, help=help_f, required=True)
params = parser.parse_args()
method( params.f)

I have something like this, the idea is that -f parameter to be a lambda. But i do not know how to do it when I called from a bash shell because if a try:

python archive.py -f lambda x: 2*x-4

I get error: “error: argument -f: invalid function value: 'x : x-4'

Some help?

Advertisement

Answer

To be able to access imported functions/modules you need to pass globals to eval. For example:

>>> from math import exp  # anything in global scope will be accessible
>>> lambda_t = 'lambda x: exp(x)'

>>> l = eval(lambda_t, globals())
>>> l(2)
7.38905609893065

To make this work as an argument, you would need to either accept a string and process it after, or wrap the creation of the lambda in another function. You can pass this as your type parameter to handle the conversion.

import argparse
from math import exp

def create_lambda_with_globals(s):
    return eval(s, globals())

parser = argparse.ArgumentParser()

help_f= "The Syntax is  lambda x: f(x), where f(x) is the function in python language"
parser.add_argument("-f",dest="f", type=create_lambda_with_globals, help=help_f, required=True)
params = parser.parse_args()  # the lambda is now defined in params.f

print(params.f(2))  # run the lambda with an input of 2

Running this from the command line:

python test.py -f 'lambda x: exp(x)'
7.38905609893
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement