1

$python example.py --function cos(x)

x = [...]

def foo(f, x):
    return f(x)

Is there a smart way I can pass any function (let's say any mathematic functions defined in numpy for simplicity) from the command line so that it will produce the same result that would produce the following piece of code:

foo(lambda t: numpy.cos(t), x)
1
  • 1
    You're going to run into parsing problems almost immediately; SymPy may be of interest to you. To get the values in from the command line, just use argparse. Commented Feb 26, 2014 at 0:40

1 Answer 1

1

As you have specified python2.7, you can use the import_module function from the backported importlib module.

>>> np = importlib.import_module('numpy')
>>> cos = getattr(np, 'cos')
>>> cos
<ufunc 'cos'>
>>> cos(3.14159)
-0.99999999999647926

You would need to parse the command line options (using argparse as @HenryKeiter suggests in the comments), then split the function from the module string, import the module and use getattr to access the function.

>>> def loadfunc(dotted_string):
...     params = dotted_string.split('.')
...     func = params[-1]
...     module = '.'.join(params[:-1])
...     mod =  importlib.import_module(module)
...     return getattr(mod, func)
...
>>> loadfunc('os.getcwd')
<built-in function getcwd>
>>> loadfunc('numpy.sin')
<ufunc 'sin'>
>>> f = loadfunc('numpy.cos')
>>> f(3.14159)
-0.99999999999647926

Note this doesn't load functions from the global namespace, and you might want to add some error checking.

EDIT

There is also no need for the lambda function in this line

foo(lambda t: numpy.cos(t), x)

You can just pass numpy.cos directly without evaluating it

foo(numpy.cos, x)
Sign up to request clarification or add additional context in comments.

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.