How to take a function as an argument? (Python)

argparse, input, lambda, python, scipy

Solution

If there are absolutely no concerns about security risks from letting the user run arbitrary Python code, then you can use `eval` to create a callable object:

volume(eval('lambda x: %s' % args.equation), args.a, args.b)

Problem

I'm writing a program to calculate the volume of a solid of rotation. The first step of this is to calculate an integral. I'm using `scipy.integrate` for this, but I can't figure out the best way to have a equation (like `x=x**2` input at the command line. I was originally planning on adding an argument 'with respect to: x|y' and then taking the function as a lambda. Unfortunately, `argparse` won't take lambda as an argument type, and trying to use a string to construct a lambda (`f = lambda x: args.equation`) just returns a string (understandably really). Here's what I've got so far: ``` import sys import argparse import math from scipy import integrate parser = argparse.ArgumentParser(description='Find the volume of the solid of rotation defined') parser.add_argument('equation', help='continous function') parser.add_argument('a', type=float, help='bound \'a\'') parser.add_argument('b', type=float, help='bound \'b\'') parser.add_argument('-axis', metavar='x|y', help='axis of revolution') args = parser.parse_args() def volume(func, a, b, axis=None): integral = integrate.quad(func, a, b) return scipy.py * integral print volume(args.equation, args.a, args.b) ``` Any advice will be appreciated thanks

Original source