1

Julia has a package called UnPack.jl that can convert Dict or NamedTuple to variables. For example, given the Dict

params = Dict(:a=>5.0, :b=>2, :c=>"Hi!")

I can get a and c by unpacking the values in the Dict to variables with the same name as the keys:

@unpack a, c = params

Some great features of UnPack.jl are:

  • a, c created in this way will not be treated as "undefined variables" by linting tools;
  • The order of the variables to be unpacked can be arbitrary; the only requirement is that the variable names are the same as the keys in the dictionary.
  • Here I do not want to use b, so @unpack will not create b. In other words, I have full control on what variables are to be extracted; unneeded variables will not be created.

It there a similar (or even equivalent) package in Python to unpack a dict? In particular, please avoid locals(), eval, exec because either the linting tools cannot recognize the definition of the variables, or they are "dangerous" functions not recommended for use.

1 Answers1

0

It puts new variables in global namespace :(, but:

d = {'a' : 5.0, 'b' : 2, 'c' : "Hi!"}
globals().update((k, d[k]) for k in ['a', 'b', 'c'])
Bill
  • 5,600
  • 15
  • 27
  • Although this solution works, the linting tools will not recognize the creation of the variables, and will still treat `a`, `b`, `c` as undefined variables. I updated the question to further specify what I want. – Zhengyuan Yue Jun 13 '22 at 09:42
  • This is not going to happen with static linting tools like pylint anyway, with or without eval() or globals(). Pylint, for example, does static analysis, not dynamic analysis, and you say that you want to create the variable names from data dynamically. – Bill Jun 14 '22 at 03:18