Python Equivalents to PHP's compact() and extract()
In PHP, the compact() and extract() functions serve practical purposes for creating hashtables and updating local variables, respectively. Python offers similar functionality, although it adheres to distinct principles.
Python's Implementation of compact()
While not strictly recommended in Python, one can implement a compact()-like function as follows:
import inspect
def compact(*names):
caller = inspect.stack()[1][0]
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
This function introspects the caller's local and global variables to create a dictionary with specified variable values.
Python's Approach to Extract Functionality
Previously, it was possible to implement a Python equivalent of extract(), but this method is no longer supported. This reflects Python's preference for explicit variable assignment instead of dynamically updating local variables.
Alternative Approaches
If the need for compact() or extract()-like functions persists, consider whether your approach aligns with Pythonic principles of clarity and explicitness. Alternatives such as accessing variables directly or using data structures like dictionaries may be more appropriate in Python.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3