-2

Is there a way to achieve the following:

calculate_fun(self.key1="some_value", self.key2="another_value")

Basically use a variable as the key for a Keyword variable.

Currently, if I try this it errors out as it is not accepting a variable on the left hand side of the "=" sign. It is expecting something in the form of:

calculate_fun(field1="some_value", field2="another_value")

But that means that I need to hardcode field1 and field2. I would like the keyword to be a variable so I can change it at runtime, hence field1 can become field55 at runtime.

6
  • 1
    Are you serious? The person who answered my question had it exactly right. Commented Jul 2, 2014 at 21:24
  • 2
    He only made a wild guess and got it right. But to me what you wrote seems like you wanted to have to automatically perform and assignment to an instance attribute when calling a function, which doesn't make any sense. I downvoted your question because, as it currently stands, it cannot be understood by future readers. I'll lift it when you make the question clearer. Commented Jul 2, 2014 at 21:26
  • 2
    @Bakuriu no wild guess, although poorly worded (before the edit), this question does make sense. Commented Jul 2, 2014 at 21:29
  • @StefanoSanfilippo Exactly, in this case it's also a (obvious) duplicate. Commented Jul 2, 2014 at 21:30
  • Clearly a duplicate, but it should be noted that the def f(**kwargs) stated in the accepted answer of the original is not necessary. Commented Jul 2, 2014 at 21:32

1 Answer 1

4

Yes, with dictionary unpacking:

calculate_fun(**{self.key1: "some_value", self.key2: "another_value"})
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.