user2899444
user2899444

Reputation: 323

Getting variable name in Python?

I have this method that takes in an unknown number of args and I have some variables from another class that I want to match the arg variable name to. The variable names are the same across this current class and the OtherClass. I was thinking something like:

def my_method(self, *args):
    for arg in args:
        OtherClass.arg_variable_name = arg # where "arg" on the right is the value

How could I do this effectively in python?

Upvotes: 1

Views: 144

Answers (2)

HavelTheGreat
HavelTheGreat

Reputation: 3386

You could use something like

dict( (name,eval(name)) for name in['self','args']

To get a dict with the values for each argument, and then from there you could match the dict values with your respective arg variable name.

Upvotes: 1

Jaehyun Yeom
Jaehyun Yeom

Reputation: 364

I think you should use **kwds instead of args. *args are values, so the caller can send it not with the variable, but just value itself.

my_object.my_method(1, 2, 3, "string")

If you use **kwds, you'll know the key, value pairs.

Upvotes: 3

Related Questions