The documentation suggests the following mechanism to dynamically create data containers in Python:
class Employee:
pass
john = Employee() # Create an e
Given the identifier above john, how can I programatically get a list of it's attributes?
vars(john)
Technically, this will give you a dictionary mapping. If you only want the list of attributes, then you actually will need vars(john).keys()
I'm not sure what you mean here about the shallow or deep copies. If you're talking about simple references, there is no (good) way to do this. If you're in the global (module level) namespace, you can do:
globals().update(vars(john))
If you're using CPython, using locals().update(vars(john))
works (in some places), but the documentation explicitly warns against doing this. The best you can do is some sort of exec
loop (yuck!):
d = vars(john)
for k in john:
exec '{key} = d["{key}"]'.format(key=k)
beware that there is a very good reason why this code is ugly -- mainly -- YOU SHOULDN'T BE DOING SOMETHING LIKE THIS :-P
and when using exec
, the usual warnings apply -- Make sure you trust the attributes on john
. e.g. setattr(john,'__import__("os").remove("useful_file"); foo',"anything here")
would make for a pretty bad day ...