Python equivalent of PHP's compact() and extract()

后端 未结 6 974
误落风尘
误落风尘 2020-11-28 11:22

compact() and extract() are functions in PHP I find tremendously handy. compact() takes a list of names in the symbol table and creates a hashtable with just their values.

6条回答
  •  隐瞒了意图╮
    2020-11-28 12:01

    PHP's compact function in Python (works with 2.6; not guaranteed to work with earlier versions of Python):

    import inspect
    def compact(*args):
        return dict([(i, inspect.currentframe().f_back.f_locals.get(i, None)) 
                      for i in args])
    

    I've written more extensively about this: Python can be just as ugly as PHP.

提交回复
热议问题