Answer the question
In order to leave comments, you need to log in
Python - how to unpack variables in a function namespace?
EOF, and in this function one configuration file is parsed. You need to somehow unpack a dictionary like {'one':'1', 'two':'2', 'three':'3', 'four':'4'} into local variables within bounds without a ton of spaghetti code this function, and some parameters are optional. I thought about a function that would take a dictionary of required arguments, a dictionary of optional and locals(), then return locals with parameters added, and then this returned locals() of yours could somehow be put back. Type:
def extract(locals_dict, args, opts, dictionary): #без ловли эксепшенов, просто для примера
entry_names = [entry['name'] for entry in dictionary]
for arg in args:
locals[arg] = dictionary[arg]
for opt in opts:
if opt in entry_names:
locals[opt] = dictionary[opt]
dictionary = config.parse()
print dictionary
#{'arg1':"value in config file with key 'arg1'", ...}
args = ['arg1', 'arg2', 'arg3']
opts = ['opt1', 'opt2', 'opt3']
new_locals = extract(locals(), args, opts, dictionary)
assign_locals(new_locals) #Вот насчёт этого я ничего не знаю =(
print arg1
#Печатает "value in config file with key 'arg1'"
Answer the question
In order to leave comments, you need to log in
Here: stackoverflow.com/questions/8028708/dynamically-set-local-variable-in-python states that locals cannot be changed. Except for some perverse cases that do not always work.
As I understand it, you have a dictionary, and quite a small one at that, and you want to unpack it into local variables. But why? Why not just use a dictionary? mydict['myname']
not much longer than myname
.
In principle, it can be used OrderedDict
to guarantee the order of values, and knowing this order, write something like
But is it necessary. Then to understand in case of bugs, where and what came from. Explicit is better than implicit.
def func(arg1=1, arg2=2, opt1=3, opt2=4, **kwargs):
print arg1, arg2, opt1, opt2
dct = config.parse()
func(**dct)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question