本文介绍了Python 等价于 PHP 的 compact() 和 extract()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

compact() 和 extract() 是我觉得非常方便的 PHP 函数.compact() 获取符号表中的名称列表,并创建一个仅包含它们的值的哈希表.提取物则相反.例如,

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. extract does the opposite. e.g.,

$foo = 'what';
$bar = 'ever';
$a = compact('foo', 'bar');
$a['foo']
# what
$a['baz'] = 'another'
extract(a)
$baz
# another

有没有办法在 Python 中做同样的事情?我环顾四周,最接近的是这个线程,它似乎对此不以为然.

Is there a way to do the same in Python? I've looked all around and the closest I've come is this thread, which seems to frown on it.

我知道 locals()、globals() 和 vars(),但是我怎样才能轻松地选择它们的值的一个子集?

I know about locals(), globals() and vars(), but how can I handily select just a subset of their values?

Python 是否有更好的东西来消除这种需求?

Does Python have something even better that obviates the need for this?

推荐答案

它不是很 Pythonic,但如果你真的必须,你可以像这样实现 compact():

It's not very Pythonic, but if you really must, you can implement compact() like this:

import inspect

def compact(*names):
    caller = inspect.stack()[1][0] # caller of compact()
    vars = {}
    for n in names:
        if n in caller.f_locals:
            vars[n] = caller.f_locals[n]
        elif n in caller.f_globals:
            vars[n] = caller.f_globals[n]
    return vars

过去可以像这样实现 extract(),但是在现代 Python 解释器中,这似乎不再起作用(并不是说它曾经应该"起作用,真的,但是在 2009 年的实施中有一些怪癖让你逃脱了它):

It used to be possible to implement extract() like this, but in modern Python interpreters this doesn't appear to work anymore (not that it was ever "supposed" to work, really, but there were quirks of the implementation in 2009 that let you get away with it):

def extract(vars):
    caller = inspect.stack()[1][0] # caller of extract()
    for n, v in vars.items():
        caller.f_locals[n] = v   # NEVER DO THIS - not guaranteed to work

如果您真的觉得需要使用这些功能,那么您可能做错了一些事情.它似乎至少在三个方面违背了 Python 的哲学:明确比隐式更好",简单比复杂好",如果实现很难解释,那是个坏主意",也许更多(实际上,如果你有足够的 Python 经验,你就会知道像这样的东西只是没有完成).我认为它对调试器或事后分析很有用,或者可能对某种非常通用的框架很有用,这些框架经常需要创建具有动态选择的名称和值的变量,但这是一个延伸.

If you really feel you have a need to use these functions, you're probably doing something the wrong way. It seems to run against Python's philosophy on at least three counts: "explicit is better than implicit", "simple is better than complex", "if the implementation is hard to explain, it's a bad idea", maybe more (and really, if you have enough experience in Python you know that stuff like this just isn't done). I could see it being useful for a debugger or post-mortem analysis, or perhaps for some sort of very general framework that frequently needs to create variables with dynamically chosen names and values, but it's a stretch.

这篇关于Python 等价于 PHP 的 compact() 和 extract()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 15:48
查看更多