Define variables using a list of names

I am trying to do something dirty here in my script.

I have a function that applies some transformations on an object called model. model can have several attributes, which includes alpha and delta. The function, however, must be able to override those attributes with its own optional parameters.

I guess I have to check if the function has received those arguments and, if not, reassign the attribute to the flat name. (From model.alpha to alpha). The main issue here is to code the loop that solves this for any given case.

The only way I have managed to do this is using the locals() dict, but I find that quite dirty. Any suggestions? Here is my code, roughly.

 def transform(model, alpha=None, theta=None):
        for p in ('alpha', 'theta'): #the list is longer, actually
            if not locals()[p] and hasattr(model, p):
                locals()[p] = getattr(model, p)

        _rotate(model, alpha)
        _translate(model, delta)

Finally, is there any internal list for the optional parameters of the function? Something like __parameters__? That way, I could just do for p in __parameters__ and so on.

Thank you!

Upvotes: 1

Views: 64

Answers (2)

piokuc
piokuc

Reputation: 26164

If you declare your function like this:

def transform(model, **kwargs):
    ...

then all keyword arguments will be passed to the function in kwargs as a dictionary.

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599510

You can just use the **kwargs syntax, and then operate directly on that kwargs dictionary rather than the locals:

def transform(model, **kwargs):
    for p in ('alpha', 'theta', ...):
        if 'p' not in kwargs and hasattr(model, p):
            kwargs[p] = getattr(model, p)

(You probably still want to explicitly iterate through a list of expected names, to filter out any unexpected arguments that might also be in kwargs.)

Upvotes: 1

Related Questions