I’ve been learning meta-programming in Ruby, and have found it quite useful. I’m sure I can do the same in Python.
E.g.: how would I rewrite this function given this function in a concise and general way using meta-programming?
def foo(bar=None, baz=None, qux=None, haz=None):
txt = {}
if bar:
txt.update({'bar': bar})
if baz:
txt.update({'baz': baz})
if qux:
txt.update({'qux': qux})
if haz:
txt.update({'haz': haz})
return txt
(this is obviously over-simplified, in practice one might perform different tasks based on value-set of individual keys)
You could use the
**kwargssyntax:Or, if you’re short on ink:
As suggested by Clement Bellot:
If you want to be sure those args are in your expected set, you could have an
ALLOWED_PARAMS = ('bar','baz','qux','haz')constant and replaceif vwithif v and k in ALLOWED_PARAMS.As suggested by DSM:
If you’re running Python 2.7+, you can use a dict comprehension.
This version also offers an alternate take on the “Allowed variables” problem:
Let’s say you actually wanted to call functions depending on those parameters being there, you could do:
Now, all in all, I’m not totally sure that’s really ‘meta’.