3 ms·
Yes but they are not equivalent. dict and list are factories; {} and [] are reified when the code is touched and then never reinitialised again. This catches ou
by mickeyp 1y ago
Yes but they are not equivalent. dict and list are factories; {} and [] are reified when the code is touched and then never reinitialised again. This catches out beginners and LLMs alike:
https://www.inspiredpython.com/article/watch-out-for-mutable-defaults-in-function-arguments https://www.inspiredpython.com/article/watch-out-for-mutable...
- thayne 1y agoThat article is about how defaults for arguments are evaluated eagerly. It doesn't real have to do with dict vs {}. However, using the literal syntax does seem to be more efficient. So that is an argument for having dedicated syntax for an empty set.
- fainpul 1y agoYour link doesn't support your argument.
- mickeyp 1y agoI wrote the link and yes it does. Module evaluations reify {}, [], etc. once. That is why people keep making subtle bugs when they do `def foo(a=[]):` unaware that this will in fact not give you a brand new list on every function call. Factory functions like list/tuple/set are function calls and are executed and avoid this problem. Hence why professional python devs default to `None` and check for that and _then_ initialise the list internally in the function body. Adding {/} as empty set is great, sure; but that again is just another reified instance and the opposite of set() the function.
- rand_r 1y agoThere is no difference between “def f(x={})” and “def f(x=dict())”, unless you have shadowed the dict builtin. They both have exactly the same subtle bug if you are mutating or return x later.
- deleted 1y ago[deleted]
- spott 1y agoThey are equivalent. In function signatures (what your article is talking about), using dict() instead of {} will have the same effect. The only difference is that {} is a literal of an empty dict, and dict is a name bound to the builtin dict class. So you can reassign dict, but not {}, and if you use dict() instead of {}, then you have a name lookup before a call, so {} is a little more efficient.
- mickeyp 1y agoRight, but it instantiates it _once_ on module load! That is the point I am making; nothing else.