Picklable data containers that are dumpable in the current namespace

前端 未结 1 1681
独厮守ぢ
独厮守ぢ 2020-12-21 14:36

The documentation suggests the following mechanism to dynamically create data containers in Python:

class Employee:
    pass

john = Employee() # Create an e         


        
相关标签:
1条回答
  • 2020-12-21 15:24
    • 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()

    • How can I easily dump john's attributes in the current namespace? (i.e. create local variables called name, dept, salary either via shallow or deep copies)

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

    0 讨论(0)
提交回复
热议问题