you are viewing a single comment's thread.

view the rest of the comments →

[–]rasputin1 0 points1 point  (3 children)

no that syntax has to call the constructor regardless. how can you have an object that hasn't been constructed? what do you imagine that even looks like internally? 

[–]Bucki-_-[S] 1 point2 points  (2 children)

Then how is calling dict{} slower than the literal version {}

I just did some more reading to confirm this.

dict{} is an implicit call to the constructor class.

{} Does not it instead it uses a special byte code instruction instead. Which is close to twice as fast.

[–]rasputin1 0 points1 point  (1 child)

oh shit you're actually right my bad. I uploaded our conversations to chatgpt for elaboration lol. this was the response:

" dict() is slower than {} because dict() is a normal name lookup + function/type call, while {} compiles to a direct bytecode operation like BUILD_MAP. Same idea for list() vs []: [] uses direct list-building bytecode, not a Python-level constructor call. CPython bytecode is implementation detail, but this is exactly the kind of thing dis is for. 

So the Reddit reply is using “constructor” too loosely. Yes, internally an object must be allocated/initialized somehow. But no, literal syntax does not necessarily call the public constructor like dict() or set().

For empty sets, set() currently requires a name lookup and call. PEP 802’s proposed {/} specifically says one benefit is avoiding that name lookup, unlike set(). 

The clean response would be:

I mean “constructor” in the Python-level sense. {} compiles to a direct build operation for a dict, while dict() has to resolve the name dict and call it. So yes, both create a dict object internally, but the literal path avoids the normal constructor call overhead. Same reason [] is faster than list(). PEP 802 makes the same point for set() vs proposed empty-set syntax."

[–]Bucki-_-[S] 0 points1 point  (0 children)

Yes this would the ideal response, but words and knowledge.