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

Does Python optimize away a variable that’s only used as a return value?

No, it doesn’t. The compilation to CPython byte code is only passed through a small peephole optimizer that is designed to do only basic optimizations (See test_peepholer.py in the test suite for more on these optimizations). To take a look at what’s actually going to happen, use dis* to see the instructions generated. For the … Read more

Python string interning

This is implementation-specific, but your interpreter is probably interning compile-time constants but not the results of run-time expressions. In what follows CPython 3.9.0+ is used. In the second example, the expression “strin”+”g” is evaluated at compile time, and is replaced with “string”. This makes the first two examples behave the same. If we examine the … Read more

Why is str.translate much faster in Python 3.5 compared to Python 3.4?

TL;DR – ISSUE 21118 The long Story Josh Rosenberg found out that the str.translate() function is very slow compared to the bytes.translate, he raised an issue, stating that: In Python 3, str.translate() is usually a performance pessimization, not optimization. Why was str.translate() slow? The main reason for str.translate() to be very slow was that the … Read more

Why do tuples take less space in memory than lists?

I assume you’re using CPython and with 64bits (I got the same results on my CPython 2.7 64-bit). There could be differences in other Python implementations or if you have a 32bit Python. Regardless of the implementation, lists are variable-sized while tuples are fixed-size. So tuples can store the elements directly inside the struct, lists … Read more

Why is it slower to iterate over a small string than a small list?

TL;DR The actual speed difference is closer to 70% (or more) once a lot of the overhead is removed, for Python 2. Object creation is not at fault. Neither method creates a new object, as one-character strings are cached. The difference is unobvious, but is likely created from a greater number of checks on string … Read more

How to override the copy/deepcopy operations for a Python object?

Putting together Alex Martelli’s answer and Rob Young’s comment you get the following code: from copy import copy, deepcopy class A(object): def __init__(self): print ‘init’ self.v = 10 self.z = [2,3,4] def __copy__(self): cls = self.__class__ result = cls.__new__(cls) result.__dict__.update(self.__dict__) return result def __deepcopy__(self, memo): cls = self.__class__ result = cls.__new__(cls) memo[id(self)] = result for … Read more

Is it possible to “hack” Python’s print function?

First, there’s actually a much less hacky way. All we want to do is change what print prints, right? _print = print def print(*args, **kw): args = (arg.replace(‘cat’, ‘dog’) if isinstance(arg, str) else arg for arg in args) _print(*args, **kw) Or, similarly, you can monkeypatch sys.stdout instead of print. Also, nothing wrong with the exec … Read more