简体   繁体   中英

Python Equivalent of Julia UnPack.jl

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.

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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM