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

后端 未结 6 971
误落风尘
误落风尘 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:11

    I'm afraid there are no equivalents in Python. To some extent, you can simulate their effect using (and passing) locals:

    >>> def compact(locals, *keys):
    ...     return dict((k, locals[k]) for k in keys)
    ...
    >>> a = 10
    >>> b = 2
    >>> compact(locals(), 'a', 'b')
    {'a': 10, 'b': 2}
    
    >>> def extract(locals, d):
    ...     for k, v in d.items():
    ...         locals[k] = v
    ...
    >>> extract(locals(), {'a': 'foo', 'b': 'bar'}
    >>> a
    'foo'
    >>> b
    'bar'
    

    Nevertheless, I don't think these functions are "tremendously handy". Dynamic global/local variables are evil and error-prone -- PHP guys learned that when they discouraged register_globals. From my experience, few experienced PHP programmers or major frameworks use compact() or extract().

    In Python, explicit is better than implicit:

    a = 1
    b = 2
    # compact
    c = dict(a=a, b=b)
    
    # extract
    a, b = d['a'], d['b']
    

提交回复
热议问题