Skip to content

Tag: python-internals

How are small sets stored in memory?

If we look at the resize behavior for sets under 50k elements: This pattern is consistent with quadrupling of the backing storage size once the set is 3/5ths full, plus some presumably constant overhead for the PySetObject: A similar pattern continues even for larger sets, but the resize factor switches to do…

How does Python’s reversed() function work?

According to Python’s docs, reversed() uses __getitem__ and __len__ if __reversed__ is not implemented. I’ve encountered a weird behavior and failed to explain it: Although calling reversed() on mapping types makes no sense, how does it know it’s a mapping? Does it internally check isinstanc…

delete the hashed node in deque in O(1)

How do I hash a built-in node in deque (which is a double linked list) and delete the node in the middle in O(1)? Is the built-in node exposed? For example, I want to save a deque’s node in dict so I can delete the node in constant time later. This is a use case in LRU, using deque so

How does a generator function work internally?

Below is a generator function. Does this generator function (f) get implemented, internally, as shown below? Edit: This is the answer for my question. Answer Internally, a generator works about the same as a regular function call. Under-the-hood, running generators and running functions use mostly the same ma…

Why are Python’s arrays slow?

I expected array.array to be faster than lists, as arrays seem to be unboxed. However, I get the following result: What could be the cause of such a difference? Answer The storage is “unboxed”, but every time you access an element Python has to “box” it (embed it in a regular Python ob…