4 ms·
The pythonic example I've seen not once: {"some": "dict"}.setdefault("some", foo()) while expecting foo() to be short-circuited.
by avip 9y ago
The pythonic example I've seen not once:
{"some": "dict"}.setdefault("some", foo())
while expecting foo() to be short-circuited.
- raverbashing 9y agoThat's awful What are people expecting with that?
- avip 9y agoThey expect to have some form of "lazy caching": conf = {} def get_conn(): return conf.setdefault("db_conn", expensive_creation_of_db_conn())
- tomjakubowski 9y agoProbably expecting something like you get from collections.defaultdict: "dict subclass that calls a factory function to supply missing values": https://docs.python.org/2/library/collections.html#collections.defaultdict https://docs.python.org/2/library/collections.html#collectio...
- HCIdivision17 9y agoI thought, "gosh, that seems at least marginally useless; why wouldn't that short circuit?" and then just tried it. I tried a few variations, and about the only use I can think of is to signal as a side effect for when the dict is made. Fun trick to learn exists. Though I would really like to know what led up to it, since it seems ... unhelpful. Edit: Looking at other comments, I did try popping off that entry in the dict, and no, it didn't have anything in it (it doesn't make the dict anything like defaultdict).
- nerdponx 9y agoAs far as I know there is no native mechanism for short circuiting in Python. So anything that short-circuits should be considered a special case.
- HCIdivision17 9y agoBinary operations will do it, like in `True or foo()`, but there's no real lazy evaluation machinery for parameters to a function. (Yet? I bet someone's working on it... at least I haven't tried any packages like lazypy for it.)
- nerdponx 9y agoIIRC the boolean operators "and" and "or" are short-circuiting.
- leeter 9y agoThis is why I've started to think about () as the Invoke operator. Seeing it should always make the programmer assume that whatever that operator is to the right of will likely be invoked with possible side effects.