-
-
Save asiellb/0f480166c89526e2564f8d4dfc578202 to your computer and use it in GitHub Desktop.
PHP compact() function in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def compact(*args): | |
''' compact() function, analoguous to the PHP version. | |
Converts a series of (possible nested) iterables containing variable names | |
into a dictionary mapping those names to variable values. | |
Example: | |
>>> x, y, z, a, b, c = 1, 2, 3, 4, 5, 6 | |
>>> compact('x', ['y','z'], ['a', ['b'], [['c']]]) | |
{'a': 4, 'b': 5, 'c': 6, 'x': 1, 'y': 2, 'z': 3} | |
''' | |
def _compact_arg(res, arg): | |
if isinstance(arg, basestring): | |
res[arg] = locals()[arg] if arg in locals() else globals()[arg] | |
else: | |
res.update(compact(*arg)) | |
return res | |
return reduce(_compact_arg, args, {}) | |
# tested a bit but not thoroughly |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment