4

I am trying to setup a system where users can submit an equation to be solved. I have a class, DP, which represents the full parameterization of the problem. A different class, dpsolver, takes a dp object, constructs the matrices, and will solve the problem.

When creating the DP object, one of the attributes is a function reference where the function is like this:

def equation1(r, tx, p, p_prime, k, k_prime, z, z_prime ):
    """ it is assumed all arguments are same sized ndarray or scalar"""
    inv = k_prime - 0.8 * k
    v = np.power(z_prime * inv, 0.75) * (1-tx) - p*tx + p_prime
    return(v)

r and tx are scalars defined in the DP object. p, p_prime, k, k_prime, z, z_prime are all numpy matrices which are constructed based on other information contained in the instantiation of the DP class. The DP class contains an OrderedDict which has p,k, and z as keys (in that order). p_prime, k_prime, and z_prime are all inferred by solver. My question is, what is the right way to call the equation1 function from solver. I want to that function as simple as possible, so other people can submit equations which can be easily integrated into this system.

I was thinking that using eval could work, or alternatively using lists and then using eval to unpack the list within equation1. What is the best way to do this without using eval? Or will eval be okay in terms of performance?

1
  • I'm confused. How come you can't just call that function with the arguments you've defined? Commented Aug 3, 2011 at 4:37

1 Answer 1

3

From your question:

alternatively using lists and then using eval to unpack the list within equation1

You may very well already be aware of this, but in case you're not, calling:

equation1(*list_of_parameters)

Does just this.

Similarly, doing

equation1(**dict_of_parameters)

Will expand a dict to keyword arguments.

Eval is there for a reason, but using it for metaprogramming is often a bad idea.

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

3 Comments

Ah, thank you. I was not aware of this. This is my first Python project. Thanks for the help. What is this functionality called?
@stevejb - Um, honestly, I don't know... "Parameter expansion" maybe? I'm not sure I've ever actually run across the "real" name for it...
@stevejb: The closest thing to a special term for this is a word you already used in the text of your question: unpacking. See section 4.7.4 of the tutorial in the official Python docs.

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.