python - Picklable data containers that are dumpable in the current namespace -
the documentation suggests next mechanism dynamically create info containers in python:
class employee: pass john = employee() # create empty employee record # fill fields of record john.name = 'john doe' john.dept = 'computer lab' john.salary = 1000 the above allows 1 grouping various set of variables within 1 single identifier (john), without having type quotes ('') 1 dictionary.
i looking solution allows me "dump" pieces (the attributes) current namespace. there 3 ideas/problems come mind address this:
1. given identifier above john, how can programatically list of it's attributes?
2. how can dump john's attributes in current namespace? (i.e. create local variables called name, dept, salary either via shallow or deep copies)
3. top reply in next thread describes way dump variables namespace created argparse: importing variables namespace object in python
perhaps utilize namespace object info container, in above post, , dump variables with:
locals().update(vars(john)) ?
for convenience, below include list of threads discussing other approaches creating info containers in python, of don't seem pickable:
using python class info container accessing dict keys attribute in python? are there 'gotchas' python pattern? connection matlab workflows:for reference, matlab provides exact functionality through save , load, , variables can nested , unnested easily, eliminating need quotes/dictionaries purpose). motivation behind question identify mechanisms back upwards such "pickable workspaces" in python.
given identifier above john, how can programatically list of it's attributes?
vars(john)
technically, give dictionary mapping. if want list of attributes, need vars(john).keys()
i'm not sure mean here shallow or deep copies. if you're talking simple references, there no (good) way this. if you're in global (module level) namespace, can do:
globals().update(vars(john)) if you're using cpython, using locals().update(vars(john)) works (in places), documentation explicitly warns against doing this. best can sort of exec loop (yuck!):
d = vars(john) k in john: exec '{key} = d["{key}"]'.format(key=k) beware there reason why code ugly -- -- shouldn't doing :-p
and when using exec, usual warnings apply -- create sure trust attributes on john. e.g. setattr(john,'__import__("os").remove("useful_file"); foo',"anything here") create pretty bad day ...
python matlab
No comments:
Post a Comment