0

I know that I can add a variable to the global namespace "by name" with something like:

def getNewVar(name,val):
    globals()[name]=val

The things is, I would like to do this in a local namespace. I have already tried and failed in using locals() instead of globals(). Someone probably wants to know why I would do something like this. OK, in my use case, the argument to the function is actually a dictionary, and I would like to do something like:

def processDictEntries(dict):
    for varname in dict.keys():
        locals()[varname]=dict[varname]  # won't work, of course

This way, further down in the function, I won't have to keep typing

result1=dict['var1']+5.
result2=dict['var2']*dict['var7']

over and over again. I can just type

result1=var1+5
result2=var2*var7

And, if there is a way to do this in a small loop like I have written, then I don't have to do:

var1=dict['var1']
var2=dict['var2'] etc.

either. I'm really just looking for economy of code; it's a big dictionary.

BTW, the entries of the dictionary are never altered; it is strictly input. And, yes, I know that if the input dictionary lacks one of the variables the function needs, I will be in touble, but I think that can be dealt with. Thanks!

1 Answer 1

2

If you can change how you call the function:

def processDictEntries(var1=None,var2=None,**kwargs):
    #do stuff with var1,var2 ...

And then call the function as:

processDictEntries(**dict)

and of course, if you can't do that, you can always use processDictEntries as a wrapper:

def _processDictEntries(var1=None,var2=None,**kwargs):
    ...

def processDictEntries(d):
    return _processDictEntries(**d)

As a side note, it's not a good idea to name a variable dict as then you shadow the builtin function

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

Comments

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.