Accept either single dict or list of dicts as function argument
I'd like to accept either one dict or a list of dicts as a function argument. So far, I've come up with the following, but I suspect I've missed something completely obvious, and am using something fragile (开发者_JS百科isinstance
):
def wrap(f):
def enc(inp):
if isinstance(inp, list):
for item in inp:
f(item)
else:
f(inp)
return enc
@wrap
def prt(arg):
# do something with the dict
print arg.keys()
I would accept a variable number of arguments:
def wrap(f):
def enc(*args):
for item in args:
f(item)
return enc
Then you can either pass a single dictionary, multiple dictionaries or a list by unpacking it.
See Arbitrary Argument Lists in the Python tutorial.
I would avoid using a decorator, I think it would be easier to handle the logic for that in your ptr
function:
def prt(arg):
try:
# we'll try to use the dict...
print arg.keys()
except AttributeError:
# ok that didn't work, we have a list of dicts
for d in arg:
print d.keys()
精彩评论