Re:Show HN: Pydb – a lightweight database with Python syntax...
by emehrkay on Saturday January 28, 2017 @04:56PM
(#13509659)
I 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 {}
Re:Show HN: Pydb – a lightweight database with Python syntax...
by moreati on Saturday January 28, 2017 @06:26PM
(#13510274)
It'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 = []
...
Re:Show HN: Pydb – a lightweight database with Python syntax...
by reubano on Wednesday February 01, 2017 @01:56AM
(#13538909)
This 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
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 ()`.