Python Analogues for PHP's compact() and extract()
In PHP, compact() and extract() are widely used functions that facilitate the creation and extraction of hashtables with specified values or variables. This has raised questions about their availability in Python.
Implementing compact()
For Python, a possible implementation of compact() is:
<code class="python">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</code>
Implementing extract()
While compact() can be implemented, extracting values faces challenges in modern Python interpreters. Previously, it was possible to use:
<code class="python">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</code>
However, this no longer works reliably.
Alternatives
It's noteworthy that these functions may not be considered good practices in Python. They go against the principles of explicitness, simplicity, and comprehensibility. Consider alternative approaches such as using:
The above is the detailed content of Here are a few title options, playing with different question styles: Direct & Focused: * Python Equivalents for PHP\'s compact() and extract(): How to Achieve Similar Functionality? * Replacing. For more information, please follow other related articles on the PHP Chinese website!