Usage of __slots__?

In Python, what is the purpose of __slots__ and what are the cases one should avoid this? TLDR: The special attribute __slots__ allows you to explicitly state which instance attributes you expect your object instances to have, with the expected results: faster attribute access. space savings in memory. The space savings is from Storing value … Read more

What’s with the integer cache maintained by the interpreter?

Python caches integers in the range [-5, 256], so integers in that range are usually but not always identical. What you see for 257 is the Python compiler optimizing identical literals when compiled in the same code object. When typing in the Python shell each line is a completely different statement, parsed and compiled separately, … Read more

How does the @property decorator work in Python?

The property() function returns a special descriptor object: >>> property() <property object at 0x10ff07940> It is this object that has extra methods: >>> property().getter <built-in method getter of property object at 0x10ff07998> >>> property().setter <built-in method setter of property object at 0x10ff07940> >>> property().deleter <built-in method deleter of property object at 0x10ff07998> These act as … Read more

Accessing class variables from a list comprehension in the class definition

Class scope and list, set or dictionary comprehensions, as well as generator expressions do not mix. The why; or, the official word on this In Python 3, list comprehensions were given a proper scope (local namespace) of their own, to prevent their local variables bleeding over into the surrounding scope (see List comprehension rebinds names … Read more

Are dictionaries ordered in Python 3.6+?

Are dictionaries ordered in Python 3.6+? They are insertion ordered[1]. As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. This is considered an implementation detail in Python 3.6; you need to use OrderedDict if you want insertion ordering that’s guaranteed across other implementations of Python (and other … Read more

Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?

The Python 3 range() object doesn’t produce numbers immediately; it is a smart sequence object that produces numbers on demand. All it contains is your start, stop and step values, then as you iterate over the object the next integer is calculated each iteration. The object also implements the object.__contains__ hook, and calculates if your … Read more