1

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)

1
  • 3
    Unless I am missing something obvious, I don't think this question has anything to do with Python meta programming?
    – K Z
    Oct 29, 2012 at 1:02

2 Answers 2

6

You could use the **kwargs syntax:

def foo(**kwargs):
    txt = {}
    for k, v in kwargs.items():
        if v:
            txt[k] = v
    return txt

Or, if you're short on ink:

def foo(**kwargs):
    return dict(((k,v) for k, v in kwargs.items() if v))

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 replace if v with if 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:

def foo(bar=None, baz=None, qux=None, haz=None): 
    return {k:v for k,v in locals().items() if v}

Let's say you actually wanted to call functions depending on those parameters being there, you could do:

KWARGS_TO_FUNCTIONS = {
    'bar':fn_bar,
    'baz':fn_baz, 
    'qux':fn_qux,
    'haz':fn_haz,
}

def foo(**kwargs):
    for k, v in kwargs.items():
        if v:
            try:
                KWARGS_TO_FUNCTIONS[k](v)
            except KeyError:
                pass # We didn't want that kwarg.

Now, all in all, I'm not totally sure that's really 'meta'.

4
  • Could add a test for k in {'bar','baz','qux','haz'}. Oct 29, 2012 at 0:44
  • @ClementBellot Well, I'm not sure that's what's expected in the question, but I'll add it, yes Oct 29, 2012 at 0:45
  • def foo(bar=None, baz=None, qux=None, haz=None): return {k:v for k,v in locals().items() if v} would work too. I kind of think the OP's code has a bug and if bar is not None was meant, though, otherwise foo(bar=0) wouldn't load the dict. But without more information on what the OP is actually trying to do, it's hard to see how metaprogramming would be useful.
    – DSM
    Oct 29, 2012 at 0:51
  • @DSM I added the dict comprehension to the answer. I suggest you add the is not None pitfall as a comment to their question! : ) Oct 29, 2012 at 0:56
3

Thomas has given a few implementations using **kwargs. I don't think you need the ifs when using **kwargs. In the original code, they are necessary to test whether the parameter was omitted or not. When using **kwargs, the dictionary will contain exactly the given parameters, so all we need is

def foo(**kwargs):
    return kwargs

This implementation is not even needed – you can use the dict() constructor instead:

>>> dict(bar=1, baz=2, qux=3, haz=4)
{'qux': 3, 'haz': 4, 'baz': 2, 'bar': 1}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.