Skip to content

Instantly share code, notes, and snippets.

@Xion
Created November 13, 2011 18:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Xion/1362427 to your computer and use it in GitHub Desktop.
Save Xion/1362427 to your computer and use it in GitHub Desktop.
PHP compact() function in Python
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