4 ms·
Yes, indeed! Thanks for pointing that out. I actually saw that when I was cleaning this up a bit for release and couldn't make up my mind. I mean I'm not modif
by asrp 10y ago
Yes, indeed! Thanks for pointing that out. I actually saw that when I was cleaning this up a bit for release and couldn't make up my mind.
I mean I'm not modifying args or kwargs now but if I did later, I could shoot myself in the foot in a not so obvious way. But on the other hand, I don't know a succinct way to express these default values. I'd probably go with `args=None, kwargs=None` and then `args = args if args else ()`.
- emehrkay 10y agoI typically do, but i don't know if it is the most "pythonic" def func(list_arg=None, dict_arg=None): list_arg = list_arg or [] dict_arg = dict_arg or {}
- moreati 10y agoIt's not ideal. For instance if I as the caller wished to provide an empty dict-like object (e.g. dict_arg=collections.OrderedDict()), then your code would silently ignore it, and use a new dict. Instead of checking for any object that evaluates to False, you should explicitly check for None, e.g. def func(list_arg=None, dict_arg=None): if list_arg is None: list_arg = [] ...
- sirtaj 10y agoIn the cases where I need to do this, I use a singleton: DEFAULT=object() # used for no other purpose def fun(arg=DEFAULT): arg_val = {} if arg is DEFAULT else arg
- reubano 10y agoThis is the pythonic way def func(*args, defaulted='default', **kwargs): # args is a list, kwargs is a dict arg0 = args[0] if args else None another_kwarg = kwargs.get('another_kwarg', 'default') print(arg0, defaulted, another_kwarg) >>> func('one', 'two', defaulted='myval') one myval default >>> func(another_kwarg='myval') None default myval >>> args = ('one', 'two') >>> kwargs = {'defaulted': 'myval', 'another_kwarg': 'other'} >>> func(*args, **kwargs) one myval other