Home  >  Article  >  Backend Development  >  How to Replicate PHP\'s compact() and extract() Functionality in Python?

How to Replicate PHP\'s compact() and extract() Functionality in Python?

Susan Sarandon
Susan SarandonOriginal
2024-10-25 19:44:02405browse

 How to Replicate PHP's compact() and extract() Functionality in Python?

PHP's Compact() and Extract() Counterparts in Python

PHP's compact() function assembles a hashtable with values corresponding to specified symbol table names, and extract() reverses this process. While Python provides locals(), globals(), and vars(), it lacks a built-in mechanism for isolating a portion of these values.

Implementing Compact()

If desired, you can implement a Python equivalent of compact() as follows:

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

Extract() in Python

Attemping to create an extract() function in Python is not advisable. Prior Python interpreters allowed for a workaround, but in modern versions, it no longer functions.

Python's Perspective

Using compact() and extract() is generally discouraged in Python, as it runs counter to Pythonic principles of explicitness, simplicity, and clarity. However, these functions may have niche applications in debugging, post-mortem analysis, or dynamic variable creation.

The above is the detailed content of How to Replicate PHP\'s compact() and extract() Functionality in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn