Are list comprehensions syntactic sugar for `list(generator expression)` in Python 3?

Both work differently. The list comprehension version takes advantage of the special bytecode LIST_APPEND which calls PyList_Append directly for us. Hence it avoids an attribute lookup to list.append and a function call at the Python level. >>> def func_lc(): [x**2 for x in y] … >>> dis.dis(func_lc) 2 0 LOAD_CONST 1 (<code object <listcomp> at … Read more

How exactly is Python Bytecode Run in CPython?

Yes, your understanding is correct. There is basically (very basically) a giant switch statement inside the CPython interpreter that says “if the current opcode is so and so, do this and that”. http://hg.python.org/cpython/file/3.3/Python/ceval.c#l790 Other implementations, like Pypy, have JIT compilation, i.e. they translate Python to machine codes on the fly.

‘is’ operator behaves unexpectedly with floats

This has to do with how is works. It checks for references instead of value. It returns True if either argument is assigned to the same object. In this case, they are different instances; float(0) and float(0) have the same value ==, but are distinct entities as far as Python is concerned. CPython implementation also … Read more

Why is a class __dict__ a mappingproxy?

This helps the interpreter assure that the keys for class-level attributes and methods can only be strings. Elsewhere, Python is a “consenting adults language”, meaning that dicts for objects are exposed and mutable by the user. However, in the case of class-level attributes and methods for classes, if we can guarantee that the keys are … Read more

python is operator behaviour with string [duplicate]

One important thing about this behavior is that Python caches some, mostly, short strings (usually less than 20 characters but not for every combination of them) so that they become quickly accessible. One important reason for that is that strings are widely used in Python’s source code and it’s an internal optimization to cache some … Read more

Why does list ask about __len__?

See the Rationale section from PEP 424 that introduced __length_hint__ and offers insight on the motivation: Being able to pre-allocate lists based on the expected size, as estimated by __length_hint__ , can be a significant optimization. CPython has been observed to run some code faster than PyPy, purely because of this optimization being present. In … Read more

How references to variables are resolved in Python [duplicate]

In an ideal world, you’d be right and some of the inconsistencies you found would be wrong. However, CPython has optimized some scenarios, specifically function locals. These optimizations, together with how the compiler and evaluation loop interact and historical precedent, lead to the confusion. Python translates code to bytecodes, and those are then interpreted by … Read more

tech