-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.

Georgi Angelov
  • 4,338
  • 12
  • 67
  • 96
  • 1
    Are you serious? The person who answered my question had it exactly right. – Georgi Angelov Jul 02 '14 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. – Bakuriu Jul 02 '14 at 21:26
  • 2
    @Bakuriu no wild guess, although poorly worded (before the edit), this question _does_ make sense. – Stefano Sanfilippo Jul 02 '14 at 21:29
  • @StefanoSanfilippo Exactly, in this case it's also a (obvious) duplicate. – Bakuriu Jul 02 '14 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. – Stefano Sanfilippo Jul 02 '14 at 21:32
  • Yes. It is definitely a duplicate. – Georgi Angelov Jul 02 '14 at 21:33

1 Answers1

4

Yes, with dictionary unpacking:

calculate_fun(**{self.key1: "some_value", self.key2: "another_value"})
Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80