A
A
Arseniy2013-11-30 06:02:04
Python
Arseniy, 2013-11-30 06:02:04

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'"

Is it possible? Or is my version non-Pythonic and in Python there are other methods for this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anatoly Scherbakov, 2013-11-30
@Altaisoft

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

A
alz, 2013-11-30
@alz

def func(arg1=1, arg2=2, opt1=3, opt2=4, **kwargs):
    print arg1, arg2, opt1, opt2

dct = config.parse()
func(**dct)

A
Arseniy, 2013-12-01
@CRImier

Well, okay, I was persuaded, I will work with dictionary keys =) I just thought that it would be more beautiful, but I changed my mind. Plus, I was wondering if this is a common practice =) Thank you!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question