Tuesday, 17 November 2026

Python Generics, Union vs Type Constraints

I've recently come up with some use of Python generic types that confused me a bit, so I've been looking into it a bit. It's not our typical list[Book] kind of generics, but a composed form, with 2 apparently similar shapes:

list[Human | Book] vs list[(Human, Book)]

The first case, a generic type: Human | Book, is just like the normal uses we're used to, only that with a Union type. So T is a Union Type here, rather than a single Type. We call this bound type / bound union type. It tells us that the objects used there have to be of that type or a derived type. list[Book] means that in that list we can have instances of Book, of CheapBook, or ExpensiveBook, and they can be mixed, the same list can have both CheapBooks and ExpensiveBooks. For Union types, it's the same idea. list[Human, Book] means that the same list can contain instances of CheapBook, ExpensiveBook, Employer and Employee, all in the same list.

The second case, (Human, Book), is a bit different. This is called a Type Constraint. With list[(Human, Book)] a list instance will go one way or another, but not both. In a list we can have Humans, Employers and Employees, or Books, CheapBooks and ExpensiveBooks, but we won't mix Humans and Books.

C# and Kotlin do not have Union types (and much less Intersection types, not present in Python either), but for Generic Types they have sort of "Intersection Constraints" where we can express multiple requirements that T must satisfy. For example in Kotlin:


fun <T> process(x: T)
where T : Human,
	T : Serializable

T has to be both Human and Serializable. We don't have this kind of type constraint in Python. To achieve something similar (an intersection bound) we would have to leverage Protocols, like this: (remember that a protocol can’t extend a regular class, otherwise you get a TypeError: Protocols can only inherit from other protocols).


class HumanLike(Protocol):
    def speak(self) -> str: ...

class BookLike(Protocol):
    def isbn(self) -> str: ...

class HumanAndBookLike(HumanLike, BookLike, Protocol):
    pass


def process(x: HumanAndBookLike) -> None:
    ...

But notice that given that Protocols are involved and Protocols use structural typing rather than nominal typing, the above is not strictly equivalent to the Kotlin code. The Python solution means:
"anything having the required Human-like AND Book-like interface"
rather than:
"anything nominally belonging to Human AND BookLike."

Monday, 9 November 2026

Python Execution Unit

In a previous post about Python class bodies and lexical scopes I mentioned that the code in a class body is executed by creating a "synthetic" function around it. When Python compiles (at runtime) one module it basically creates a tree of code objects (let's think of a code object as an object containing bytecodes and metadata). A code object for the module level code, a code object for each function or method, a code object for each class body... Then at runtime it'll create a class object when it comes across the LOAD_BUILD_CLASS bytecode instruction, and a function object when it comes across the MAKE_FUNCTION bytecode instruction. Functions reference the code object that contains their code, and as I've said when a class is created a synthetic, one-shot function is created at runtime in order to execute the code object corresponding to the body of that class. Based on this, one could think that in order to execute the code object corresponding to the module level code, Python we'll also create a "synthetic" function on the fly. I've been discussing this with some GPT's and that's not the case. In order to execute some Python code it's not strictly necessary to have a function.

At the lowest level code execution of interpreted code (bytecodes) in CPython involves invoking the _PyEval_EvalFrameDefault function with a Frame object (as we saw in some previous post this is an optimized "internal Frame" object, not the user-friendly Frame object that gets materialized when we use sys._getframe or inspect.stack()[n].frame). This Frame points to a code object, the current instruction position, variables (locals (normal locals, parameters, closure variables...), globals, builtins). That information is normally gathered from invoking a function (CALL instruction that goes through the vector-call protocol). The function object contains the globals (the module level variables of the module where the function was defined), closure variables, the code object. Let's see the precise description given by a GPT of the relation between Frames, Functions and Code Objects:

A useful way to understand Python execution is to separate several layers that are often mentally collapsed into one:

Code object: the compiled instructions and static metadata.
Function object: a callable package containing a code object and persistent execution context.
Frame: the state of one concrete execution of a code object.
Evaluator: the interpreter loop that executes the frame, represented in CPython by machinery such as _PyEval_EvalFrameDefault().
For an ordinary function call, the flow is approximately:

function object
   │
   │ supplies:
   │   code object
   │   globals
   │   closure cells
   │   defaults and keyword defaults
   │
   │ call supplies:
   │   positional and keyword arguments
   ▼
frame
   │
   ▼
_PyEval_EvalFrameDefault()

This leads to an important principle:

The evaluator fundamentally executes a frame. A function object is one mechanism for packaging the information needed to construct and initialize that frame, but bytecode execution does not intrinsically require a function object.

2. The role of each object
- Code object
A code object describes what is to be executed. It contains, among other things:

bytecode instructions
constants
referenced names
local-variable names
cell-variable names
free-variable names
argument-count metadata
source-position information
A code object does not normally contain the runtime values of its globals, free variables, or arguments.

- Function object
A function object packages a code object with persistent context, notably:

function.__code__
function.__globals__
function.__closure__
function.__defaults__
function.__kwdefaults__
Arguments belong to a particular invocation, so they are supplied when the function is called rather than being permanently stored in the function object.

- Frame
A frame represents one particular execution. It brings together the code and the concrete runtime state required by the evaluator, including:

instruction position
evaluation stack
locals
globals
builtins
arguments
cell and free-variable storage
exception state
Thus, multiple invocations of the same function use the same function and code objects but create distinct frames.

A Function stores closure cells and globals, defaults, receiving its parameters in each invokation. But what if we don't need any of these? When executing the code object for module level code, we have no closure cells (there's not a lexical outer scope from which to trap free vars, the module itself is the outermost scope), there are no parameters to be provided... so indeed a function object is not necessary. This is different from the execution of a class body, where as seen in my aforementioned post, we can trap free vars from an outer scope (the class being defined inside a function) and also have globals (those of the module where the class is defined).

So contrary to the execution of a class body, the execution of module level code does not need the creation of a function for it. Conceptually we can think module execution as: exec(module_code, module_dict, module_dict)

Indeed, there are 2 other mechanisms to execute code without having a function, exec and eval. So module level code execution, exec and eval follow this route:

C-Level Evaluation: Instead of executing a function-based call path, the subsystem calls the internal C-API entry point: PyObject *PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)

Frame Allocation: PyEval_EvalCode sets up a new PyFrameObject. Crucially, both globals and locals map directly to the single __dict__ dictionary of the module.

Conceptual Flow of exec("x = 10")
[String Input] -> compile(text, "", "exec") -> PyEval_EvalCode() -> PyFrameObject -> Interpreter Loop

And to complete the post with more GPT wisdom:

Final mental model
The cleanest formulation is:
_PyEval_EvalFrameDefault() executes a frame. A frame represents one concrete execution of a code object. A function object is a higher-level package that helps turn a call into such a frame by supplying the code object, globals, closure cells, defaults, and related metadata.

From that model:

Module bodies bypass the function-object layer because the import or exec machinery already has the code object and namespace, and module code has no enclosing lexical scope from which to capture free variables.
Ordinary functions use function objects to package reusable code together with persistent context and to support repeated calls with different arguments.
Class bodies in CPython use temporary function objects because the class-body code may need globals and closure cells, while __build_class__ separately supplies a prepared class-local namespace.

As you can see my posts are becoming more and more a summary of my investigation on some topic with a GPT. There are few external links and more and more text copy-pasted from the final output of a (sometimes rather long) GPT discussion (or multiple ones). That's how life is now. Anyway, during this "investigation" I've also come across an excellent explanation of how the Python bytecode interpreter works.

Monday, 2 November 2026

FICXixon 2025

FICXixon 2025, was the 63rd edition of the film festival that puts Xixón on the map, and some of the world in Xixón, for a few days. This edition took place from November 14 to November 22. It started with the same disgusting weather of the previous week, more than 20 degrees in November in the Northern coast of Iberia because of the fucking south winds. Hopefully as days went by we moved into rainy November weather, though with temperatures above the average. All in all I attended 6 screenings, the same number as in the previous edition. All in all it was OK, though no film did particularly impress me.

  • Anémona, Saturday 15, Teatro Jovellanos. British film, a dark character with a painful past related to the Northern Ireland conflict (contrary to most films related to that conflict, he was on the British oppressors side rather than on the Irish side). Powerful acting and even some fantasy element.
  • Balearic, Sunday 16, CMI Xixón Sur. Interesting Spanish film. There are 2 scenarios, one shows a real life horror situation, the other one is almost hilarious, showing the declining world of some upper class adults.
  • Las corrientes, Tuesday 18, OCine. Argentinian film directed by Milagros Mumenthaler, the wife of the sadly gone Fran Gayo (more on this at the end of the post). I think I expected this was going to be the kind of film you'll only find in an indy film festival... but I attended because I was interested in the director.
  • Reedland, Wednesday 19, Teatro Jovellanos. Dark, slow Dutch film, about suspicion and guilt in a rural area. In a way it works also as a documentary about rural life and tradicional hard work. I liked it, but without finding a place in my "to see again" list.
  • L'interet d'Adam, Friday 21, Teatro Jovellanos. Good social Belgian (in French language) film. Tense and intense hospital drama about a child at risk because of his troublesome mother, and how complex this situation becomes for the doctors involved. It reminded me of Sages-femmes / Matronas a pretty good film I watched on FICXixon 2023.
  • Gorgoná (preceded by a short: 'Los murciélagos han abandonado el campanario'), Saturday 22, OCine. Greek dystopic film. Two powerful (and hot, very hot) women fight to survive in an apocalyptic society dominated by tough, muscular men with an underdeveloped brain. I guess it's some feministic stuff, but honestly, what I get from the film is that (I have to stress it again) these 2 main female characters were 2 real sex-bombs.

Additionally, there are 2 films that I missed and that looked really interesting to me:

  • Made in EU. I had thought that maybe I would have to do some overtime at work, and when finally it was not the case I check for a ticket, it was sold out.
  • Valle Blanco, Gallo Negro An Asturian film by director Alex Galán. Set in Degaña, one of the most remote corners of Asturies, and one of the most rainy areas also. Drama/comedy mix (very Asturian then) where people try to create some business opportunity in one of the ares more devastated by the sudden end of coal mining.

Films aside, I have to say that this was a sad an emotional edition. It was the first edition after the decease of Fran Gayo. He was one of the master minds of FICXixon in 2 different periods, with an interruption during which he worked in the Buenos Aires Film Festival. One of the main representatives of the Asturian cultural scene for decades (other than a cinephile he was also a musician and a writer) and a supporter of the Asturian language. I think I never talked to him, but we had some common friends (Xixón has just 250.000 inhabitants). Indeed, because of that I though he was a bit younger (he was 55). This edition of the Festival was dedicated to him. It seems in the previous edition, when he was already rather weakened by cancer, he attended the festival (he had left his position and was living in Buenos Aires with his wife and child) mainly to say goodbye to his many friends. RIP.

Just a couple of weeks after the end of the festival another slap of reality hit everyone any with the Festival, Jose Luis Cienfuegos the guy that was the director of the Festival from 1995 to 2012 and that transformed it into an internationally recognized event, suddenly died. Not living in Asturies since years ago he had not been able to attend to the gathering in a local cultural cafe where close friends came together to render tribute to Fran Gayo, and just 2 weeks later he was dead.

Thursday, 22 October 2026

Python Adaptive Specializing Interpreter and Local Inline Cache

In this previous post I talked about how Python optimizes the complex attribute lookup process by means of a Global Attribute Cache/MRO cache. We'll see in this post the recent (since Python 3.11) complementary technique used to further optimize attribute lookup.

Time ago I talked about how the CPython bytecode interpreter is since version 3.11 an Adaptive Specializing Interpreter. This means that as it runs it monitors the code to find patterns that allow optimization by replacing generic bytecode instructions by specialized ones, this is also known as Quickening (this is similar to what we are used to with interpreter - layered JIT's combinations, only that working purely at a bytecode level). This specialization is not only a matter of changing one instruction by another, but also of storing (in an inline cache just next to the instruction, a per-site cache) additional information needed by the adaptative instruction.

Since 3.11, CPython rewrites hot instructions in place into **specialized** forms. Each specializable instruction is followed in the bytecode by **inline cache entries** that hold the facts the specialized form depends on.

For looking up an attribute we have a generic LOAD_ATTR instruction, that gets specialized like this:

1. The generic (adaptive) `LOAD_ATTR` keeps a warm-up counter.
2. When the counter runs out, the specializer looks at the current type and attribute (calling `_PyType_Lookup` once) and rewrites the instruction, for example to:
- `LOAD_ATTR_METHOD_WITH_VALUES`: method on a class whose instances use key-sharing dicts
- `LOAD_ATTR_METHOD_NO_DICT`: method on instances without a `__dict__` (for example `__slots__`)
- `LOAD_ATTR_INSTANCE_VALUE`, `LOAD_ATTR_SLOT`, `LOAD_ATTR_PROPERTY`, `LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN`, …

As you can see there are different specialized instructions for an attribute lookup that has ended up returning a method from a class and for one that ends up returning a value from an instance. We can read here:

Load methods for call: o.meth()
The actual address of the method is cached. Method loading now has no namespace lookups – even for classes with long inheritance chains.

Load attribute: o.attr
The attribute’s index inside the class/object’s namespace is cached. In most cases, attribute loading will require zero namespace lookups.

So for method lookup once the specialization is in place we no longer do a lookup in the Global Attribute Cache/MRO cache (that we can consider as a Global Type Cache), but directly have the address of the method in this Local Inline Cache next to the instruction.

For instance attributes it feels even more impressive. Without this optimization a normal lookup for person1.age would search the age attribute in the MRO (after the first attempt it would store in the MRO cache a "NOT_FOUND_IN_MRO" entry) and as not found there it would retrieve it from the dictionary in person1.__dict__. With this specialization, the Local Inline Cache next to the bytecode instruction stores an index to retrieve the value from the the internal structure that contains the values stored in person1.__dict__ (along with guards). This per-site cache works very nicely when we have loops traversing an iterable of instances of the same type, as the __dict__ structure looks the same for all of them and hence the index is valid for all of them.

A successful specialized fast path may therefore avoid both an MRO walk and a lookup in the more general type cache

Monday, 12 October 2026

Python Global Attribute Cache

In my previous post we saw how Python optimizes bound method invokation, It's time to see other particularly important optimizations, the one(s) used for attribute lookup. Because of the dynamic nature of Python, looking up an attribute involves a complex algorithm (I've talked about it here and optimizing it is key, not just to make Python fast, but almost to make it usable. Notice that this optimization is also very important when invoking a method (obj.do_something()), as method invokation involves first that complex look up process to find the callable object, then the creation of a bound method (which optimization/omission we saw in our previous post), and then calling/invoking that callable. So in modern Python there are 2 complementary optimizations that are used for attribute lookup. We'll see in this post the first of them:

- Global Attribute cache / MRO cache
We know that looking up an attribute (either through the LOAD_ATTR bytecode instruction or the dynamic getattr() function), involves following the MRO for that object. Of course Python allows us to patch an existing class, replacing one method by another, adding methods, changing base classes, but this is not particularly common. Most times classes remain static, which means that normally looking up one method/attribute through the MRO will repeatidly come up with the same result. That should prompt an idea, "let's use a cache!", and yes, that's what CPython does:

CPython therefore maintains an internal cache for type-level attribute resolution, historically called the method cache, although it is useful for class attributes in general.

That's the Global Attribute cache / MRO cache. It's useful both when looking up an attribute in an instance or directly in the class. Simplifying things a bit, we could see this cache as a sort of dictionary of [type, attribute-name]: value (it's indeed a direct-mapped cache). As explained in the linked post above when accessing an attribute in an instance the lookup mechanism searches the MRO first (class and base classes) and depending on what it finds (or not finds there) it will then search the instance. Because of this, not finding an attribute in the MRO cache is also valuable information, so the cache contains also sort of "NOT_FOUND_IN_MRO" entries. The MRO cache definitively helps in all cases.

PyObject_GenericGetAttr must call _PyType_Lookup first, even for ob.x where x lives in the instance dict, because a data descriptor on the type (such as a property) takes priority over the instance dict. For plain instance attributes that type lookup almost always finds nothing, and caching that“nothing” keeps every ob.x from walking the whole MRO.

Given the dynamic operations allowed by Python, different actions (that I mentioned above: monkey-patching, changing class hierarhcy) will invalidate cache entries, actions things like:

  • type.__setattr__ and type.__delattr__: any Cls.attr = ... or del Cls.attr, dunders included (which also refresh the matching C slots).
  • Assigning to __bases__ (which recomputes the MRO).
  • A few other type mutations.

For this to work there's a key detail. The C structure used to represent Python classes has a tp_version_tag field that changes (after being invalidated) if the class mutates.

Key properties:
0 means “no valid version”. New classes start at 0.
Tags are assigned lazily from one interpreter-wide counter (next_version_tag). A tag is only handed out when something needs one: the specializer, or the global type attribute cache. Classes that are never looked at never get one.
Tags are unique across all types, not per-class sequences, and never reused. So a cached version == N can only ever match one exact state of one exact class.

Invalidation:
Any change that could affect attribute lookup calls PyType_Modified(type), which:
Sets tp_version_tag = 0 on the type.
Walks tp_subclasses recursively and clears theirs too, because a subclass’s MRO lookup depends on its bases' dicts. The next time a tag is needed, a new one is taken from the global counter.

Another key detail, entries in the Global Attribute Cache contain this tp_version_tag. So if a class gets a new tp_version_tag, both tags will no longer match and the cache value won't be used. A normal MRO lookup will be done and the cache entry will be overwritten. Better explained by a GPT:

The lookup (attribute name in type)
Compute the slot in the cache and check entry->version == type->tp_version_tag && entry->name == name (two comparisons). If both match, return entry->value.
On a miss, do the real MRO walk (find_name_in_mro). Then, if the type has or can be given a version tag and the name can be cached, overwrite that slot.

Sunday, 4 October 2026

Python Bound Methods Optimization

We know Python is slow when compared to environments with massively optimized JIT's like the JVM or node.js (using more than one JIT, PGO, etc), but for an interpreted language with no JIT one could say that Python feels fast, particularly if we are aware of how, due to its enormous dynamism, basic actions involve rather complex steps. We saw here and here that calling a function (that at a semantic level means searching for a __call__ method in its type) is done in a more straightforward way.

We're going to look into some optimizations in this post and the next one. A key element is that these optimizations do not compromise language semantics. Under certain common circumstances the optimization will shortcut the way an action works based on the language semantics (like invoking a descriptor to create a bound method or searching the MRO to retrieve an attribute), but if we perform any changes that will render different the output of the optimization from the expected output based on language semantics, the optimization is reverted. Better explained by a GPT:

CPython may combine descriptor handling, instance storage, MRO lookup, a type-level lookup cache, per bytecode inline caches, version guards, and call paths that avoid temporary bound-method objects.
The central principle is:
The runtime must preserve every observable consequence of Python’s semantics, but it need not perform unobservable intermediate work.

Method invokation, bound-method elision
Invoking a method means looking up an attribute. That look up will find a function in a class, and as functions are descriptors the descriptor protocol will run returning a bound method (with __self__ and __func__ attributes). Then the bound method is called (semantically by looking up its __call__ attribute, but we know, from previous linked posts, that that gets optimized). The thing is that in most cases that bound method creation can be skipped. Let me explain:


class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        return f"Hello, my name is {self.name}."    

p1 = Person("Iyan")
b_m = p1.greet
print(type(b_m ))  
print(b_m.__func__)
print(b_m.__self__)
# 
# 
# <__main__.Person object at 0x74ef724286e0>

print(b_m("Francois"))
# Hello Francois my name is Iyan.


In this case, the result of attribute access becomes visible to Python code (as we store it in the b_m variable for later use). For an ordinary Python function found in the class, the descriptor protocol produces a bound method containing __self__ and __func__, and calling that bound method is conceptually equivalent to: b_m.__func__(b_m.__self__, "Francois")

But most times we just invoke a method directly, like this:


p1.greet("Francois")

Creating a temporary method object merely to unpack those two references would be wasteful. CPython could instead retain the function and receiver separately and invoke: Person.say_hi(p1, "Xuan"). And basically that's what modern CPython does.

If we look at the bytecodes generated for this second case we'll see:


 23           LOAD_FAST_BORROW         0 (p)
              LOAD_ATTR                3 (greet + NULL|self)
              LOAD_CONST               1 ('Francois')
              CALL                     1
              POP_TOP
              LOAD_CONST               2 (None)
              RETURN_VALUE

That NULL|self tells the lookup algorithm to look up the function and put it in the stack (CPython is a stack based VM) along with the self value (the receiver, the object on which we've done the look up). After that, other parameters to be passed to the function are pushed in the stack and the function is called.

In the next post we'll see the optimizations used for attribute lookup

Friday, 25 September 2026

Counting Lines in Python

We have some Python scripts that at some point count the number of lines in a file. We do so by invoking wc -l, like this:


def count_lines_wc(file_path: str) -> int:
    result = subprocess.run(
        ["wc", "-l", file_path],
        check=True,
        capture_output=True,
        text=True,
    )
    return int(result.stdout.split()[0])

Well, counting lines does not seem like a big deal, so why not just do it in pure Python? The immediate approach would be something like:


    def count_lines_1(file_path: str, encoding: str | None = None) -> int:
        """ counts the number of lines in a file, without loading it all in memory (so it can be used for big files)"""
        with open(file_path, "r", encoding=encoding) as fr:
            return sum(1 for _ in fr)   

The problem with that function when compared to wc -l is that we have to provide the encoding or use the default one (that depends on your system, it's what locale.getpreferredencoding() returns, that on Linux systems is utf-8, but on windows it's cp1252).

When we call "wc -l" we are not passing any encoding, so how does it do it? It just reads the file in binary mode and counts the bytes corresponding to a newline character, that is the 0X0A byte (or b"\n"). So we can do that in Python like this:


def count_lines_2(path: str) -> int:
    """ 
    behaves like 'wc -l' command, as it's byte based it does not have to take into account encoding, 
    but it can be used only for files that use \n as line separator (so Linux, Windows, 'modern' MacOS)
    """
    with open(path, "rb") as f:
        return sum(chunk.count(b"\n") # or b"\x0A"
            for chunk in iter(lambda: f.read(8192), b""))


So I'm reading chunks of n bytes (8192 bytes in this case) and counting the occurrences of the "\n" byte in it. Checking this with a GPT it gave me a more pythonic version:


def count_lines_3(file_path: str) -> int:
    """Counts newline bytes, like wc -l"""
    with open(file_path, "rb") as f:
        return sum(1 for _ in f)  # reads binary lines split by b'\n'

This version is using something I was not aware of. We know that the file object that we obtain after opening a file in text mode is an iterator that yields lines. But the file object that we obtain when opening a file in binary mode (in this cases it's a binary file object) is also an iterable/iterator that iterates bytes splitting by the b"\n" byte (and that b"\n" byte is also included in the bytes yielded in each iteration, save for the last 'line' if it lacks it).

We have an interesting difference depending on whether the last line of a file contains a newline character or not. The standard defines that text files should end with a newline character, but not everybody follows the standard. If we have a text file which last line does not end with a newline character, using wc -l (or my count_lines_2), that work by counting "\n"'s will not count the last line, while using my count_lines_3 will count it.

We can see that difference by executing the above functions with 2 versions of a same text file, one version with a newline character in its last line and another version without it, we get:


for file_name in files:
    print(f"-- Counting lines in {file_name}...")
    for fn in [count_lines_wc, count_lines_1, count_lines_2, count_lines_3]:
        print(f"{fn(file_name)} lines counted by {fn.__name__}")

# -- Counting lines in withEOL.txt...
# 4 lines counted by count_lines_wc
# 4 lines counted by count_lines_1
# 4 lines counted by count_lines_2
# 4 lines counted by count_lines_3

# -- Counting lines in noEOL.txt...
# 3 lines counted by count_lines_wc
# 4 lines counted by count_lines_1
# 3 lines counted by count_lines_2
# 4 lines counted by count_lines_3

Related to this, what if we want to count the lines of one file inside a zip? Obviously we can extract the file and use one of the above functions, but Python zipref.ZipFile allows us reading the file without extracting it. ZipFile.open opens a file in binary mode, and then we can either read it by chunks or iterate it, just as we did in the previous examples. So if we put the 2 previous files into a zip we have:



def count_lines_in_zip_file_1(zip_ref: zipfile.ZipFile, file_name: str) -> int:
    # works like wc -l: count newline bytes without extracting to disk.
    # "r" mode for zip_ref.open is equivalent to "rb" in the standard open, so we get bytes and can count b"\n".
    num_lines = 0
    with zip_ref.open(file_name, "r") as zipped_file:
        for chunk in iter(lambda: zipped_file.read(1024 * 1024), b""):
            num_lines += chunk.count(b"\n")
    return num_lines

def count_lines_in_zip_file_2(zip_ref: zipfile.ZipFile, file_name: str) -> int:
    # Count lines without extracting to disk. If the last line lacks a newline character, it won't be counted
    # "r" mode for zip_ref.open is equivalent to "rb" in the standard open, so we get bytes and can count b"\n".
    num_lines = 0
    with zip_ref.open(file_name, "r") as zipped_file:
        return sum(1 for _ in zipped_file)  # reads binary lines split by b'\n' (b'0x0A') and counts them, so it behaves like wc -l



zip_ref = zipfile.ZipFile("files.zip", "r")

files = ["withEOL.txt", "noEOL.txt"]

for file_name in files:
    print(f"-- Counting lines in {file_name} inside zip file...")
    for fn in [count_lines_in_zip_file_1, count_lines_in_zip_file_2]:
        print(f"{fn(zip_ref, file_name)} lines counted by {fn.__name__}")
        

# -- Counting lines in withEOL.txt inside zip file...
# 4 lines counted by count_lines_in_zip_file_1
# 4 lines counted by count_lines_in_zip_file_2

# -- Counting lines in noEOL.txt inside zip file...
# 3 lines counted by count_lines_in_zip_file_1
# 4 lines counted by count_lines_in_zip_file_2


Saturday, 12 September 2026

Python Enums missing_key

In a recent post about Python enums I mentioned the _missing_ method, that gets executed when accessing an enum member by value if that value is missing.


from enum import Enum
class Color(Enum):
    RED = "red"
    BLUE = "blue"
    @classmethod
    def _missing_(cls, value):
        value = value.lower()
        print(f"missing value: {value}")
        for member in cls:
            if member.value == value:
                return member
        return None

print(Color.RED is Color("red"))
# True

print(Color.RED is Color("rEd"))
# missing value: rEd
# True

We know that we can also get an enum member by name, using the [] syntax (subscripted access or key/name access), like color = Color["RED"], and well, it feels to me that it would be nice to have this kind missing functionality for that kind of access (let's call it 'missing_key'). I mean, defining a sort of missing_key method in our enum classes that would get invoked if the key/name used does not exist. And how can we hook this behaviour into the subscripted access to the enum? At the end of this post I talked about those __dunder_methods__ that work as behavioral hooks. We have hooks for invokation, attribute getting, attibute setting... and also one, __getitem__ for subscripted access. For this case, we'll be using the subscripted access in the class, so we have to implement it in a metaclass. The Enum class has EnumMeta as its metaclass, so we'll need our new metaclass to inherit from EnumMeta. When creating an Enum empowered with this "missing_key" functionality, it'll have to use our new metaclass, and inherit from Enum (or related child classes like IntEnum, StrEnum...).

`EnumMeta` implements the class-creation machinery (turning attributes into members, building `__members__` and `_value2member_map_`), but it relies on the base class (`Enum`) to provide the instance API and the initialization/constructor expectations used when creating each member. Without inheriting from `Enum`, those assumptions break and class creation fails or yields an object that isn't a proper enum.

So we define this metaclass, that when accessing a missing key will invoke a _missing_key method (if it exists) in the enum class.


from enum import EnumMeta, Enum

class MissingKeyEnum(EnumMeta):
    def __getitem__(cls, name):
        try:
            return super().__getitem__(name)
        except KeyError:
            print(f"Name '{name}' is not a valid member of {cls.__name__}")
            # Call a dedicated missing-name handler if present
            if hasattr(cls, "_missing_key"):
                return cls._missing_key(name)
            return None


An now we define a class that leverages the metaclass to allow case insensitive subscripted access:


class Query(Enum, metaclass=MissingKeyEnum):
    SELECT = "select"
    INSERT = "insert"
    UPDATE = "update"
    DELETE = "delete"

    @classmethod
    def _missing_key(cls, name):
        # This method is called when a name is not found in the enum
        # You can customize the behavior here, for example, allowing case insensitive access
        return getattr(cls, name.upper(), None)  # Return the enum member if it exists, otherwise return None



query1 = Query["INSERT"]  # This will return the enum member Query.INSERT
query2 = Query["Insert"]  # This will go through _missing_key and return Query.INSERT
print(query1 is query2)  # This will print True, as both refer to the same enum member

query3 = Query["insssseeerrtt"]  # This will go through _missing_key and return None
print(f"query3: {query3}")  # This will print None, as the name is not valid


Just to close this post I'll mention an interesting article that discusses inheriting from Enum vs using a new metaclass that inherits from EnumMeta.

Sunday, 6 September 2026

Python Dynamic Class Creation part 2

In a recent post I mentioned the rough steps that Python executes to create a class when it comes across a class statement (we can call it the "class creation pipeline")

  • Step 1 — Determine the metaclass. Python calls __build_class__ (a builtin), which inspects the bases and the explicit metaclass= kwarg to resolve which metaclass to use (with MRO-based metaclass conflict resolution).
  • Step 2 — Prepare the namespace. The metaclass's __prepare__ classmethod is called: namespace = Meta.__prepare__('Foo', (Base,), **kwargs). This returns the dict (or dict-like object) that will serve as the class namespace. For type, this is just a plain dict. For enum.EnumMeta, for example, it returns a special _EnumDict.
  • Step 3 — Execute the class body. The compiled code object for the class body is executed as a function, with the namespace from step 2 as its locals(). This is the key insight: it's essentially exec(body_code, globals(), namespace). After this, namespace contains {'x': 1, '__module__': ..., '__qualname__': ...}.
  • Step 4 — Call the metaclass. Meta('Foo', (Base,), namespace) is called — which, for the default type, invokes type.__call__ → type.__new__ → type.__init__. This is where the actual class object is constructed.

And explained how when we create a class dynamically using type() (or any other metaclass), we are directly at step 4. Obviously we have to take care of deciding what metaclass to use and prepare the namespace ourselves, which means that we should invoke the metaclass __prepare__ method (hook) ourselves, something that I was not aware of. Deciding what metaclass to use may seem pretty straightforward, and it is if we intend to use a particular metaclass, but if we just want to use the one that corresponds based on the inheritance chain it's not that evident. Most times, when all base classes just use type, it's just type, but we really would have to take care of analysing the metaclasses of the classes in that inheritance chain.

So indeed, correctly building a class dynamically is more complex that it seemed to me... Well, not really, cause I had missed that since python 3.3 the types module comes with a nice function just for that, types.new_class(name, bases=(), kwds=None, exec_body=None). This function follows the 4 aforementioned steps in the class creation process. It will select the metaclass to use based on whether we provide a metaclass in kwds or the parent classes in bases. It will invoke __prepare__ to create and prepopulate the class namespace, and pass it over to the exec_body function for it to continue populating it (that exec_body function corresponds to the code that we will place in the class body of a normal class statement). Finally it will invoke the selected metaclass to create the class.



def populate(namespace):
	for field in fields:
		namespace[field.name] = create_descriptor(field)

Generated = types.new_class(
	"Generated",
	(Base,),
	{"metaclass": Meta},
	populate,
)


There's another function in types that should call your attention, types.prepare_class(name, bases=(), kwds=None). It returns the metaclass to be used and the namespace created by metaclass.__prepare__, so that then you can further populate that namespace (with the code that you would put in the exec_body callback if you were using new_class), and invoke that metaclass.



meta, namespace, remaining_keywords = types.prepare_class(
	"Generated",
	(Base,),
	{"metaclass": Meta},
)

for field in fields:
	namespace[field.name] = create_descriptor(field)

Generated = meta(
	"Generated",
	(Base,),
	namespace,
	**remaining_keywords,
)


So while new_class performs the 4 steps in the class creation pipeline, prepare_class performs the 2 first steps and leaves under your responsibility performing steps 3 and 4. We could say that create_class follows a callback-based style while prepare_class moves us into an imperative, phase-oriented style.

Sometimes it can be not possible to decide what metaclass should be used based on the base classes combination (and the explicit metaclass if we happen to have provided one). If the base classes drive us to different, uncompatible (not in the same inheritance chain), metaclasses, we get an error:



>>> class MetaA(type): pass
... 
>>> class MetaB(type): pass
... 
>>> class A(metaclass=MetaA): pass
... 
>>> class B(metaclass=MetaB): pass
... 
>>> class C(A, B): pass
... 
Traceback (most recent call last):
  File "python-input-4", line 1, in module
    class C(A, B): pass
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases


If the metaclass obtained from the base classes and the one we provide explicitly do no belong to the same inheritance chain,



>>> class C(B, metaclass=A): pass
... 
Traceback (most recent call last):
  File "python-input-6", line 1, in module
    class C(B, metaclass=A): pass
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases


Saturday, 29 August 2026

Python Object Oriented Enums

Years ago, when I wrote this post about Python enums I mentioned this:

if you want something more advanced like the Java/Kotlin enums, where we can have multiple attributes as values and have instance methods (the archetypical Java Planets example), you can use the powerful aenum module (advanced enums), that just implements the Planets example.

Well, I've just found out that the standard Python enums support "enum members with associated data". You can add methods and properties to your enum classes, so you have a functionality pretty similar to the powerful Java enums. I've felt a bit like an idiot, cause after learning this from a code discussion with a GPT I realised that it's not any "python hidden feature", the standard enums documentation comes with a Planet example.


class Planet(Enum):
    MERCURY = (3.303e+23, 2.4397e6)
    VENUS   = (4.869e+24, 6.0518e6)
    EARTH   = (5.976e+24, 6.37814e6)
    MARS    = (6.421e+23, 3.3972e6)
    JUPITER = (1.9e+27,   7.1492e7)
    SATURN  = (5.688e+26, 6.0268e7)
    URANUS  = (8.686e+25, 2.5559e7)
    NEPTUNE = (1.024e+26, 2.4746e7)
    
    def __init__(self, mass, radius):
        self.mass = mass       # in kilograms
        self.radius = radius   # in meters
        
    @property
    def surface_gravity(self):
        # universal gravitational constant  (m3 kg-1 s-2)
        G = 6.67300E-11
        return G * self.mass / (self.radius * self.radius)

Planet.EARTH.value

Planet.EARTH.surface_gravity

That's the equivalent to the Java Planet one that years ago showed the world that enums could be much more than what we were used to.


public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    private double mass() { return mass; }
    private double radius() { return radius; }

    // universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }

"Traditional" enums, like those in C or C# are just "a group of named constant values with type safety", they answered this question "How do I give names to a set of integer constants?". Java enums are "classes with a fixed set of instances defined at compile time", and they answer this question "How do I represent a fixed set of domain objects?"

Before Java added enums to the language, people were using the "Typesafe Enum Pattern" pattern to simulate "object-oriented enums". By the way, years ago I wrote about emulating Java enums in C#.

Java enums have an extra feature that is not directly implemented by Python enums, each member of the enum can have its own implementation of some methods (it's a per-instance override). Let's see an example:


enum Operation {
	PLUS { public int apply(int a, int b) { return a + b; } },
	
	TIMES { public int apply(int a, int b) { return a * b; } };
	
	public abstract int apply(int a, int b);
}

Python does not have a direct equivalent, a member can’t override a method. But there are idiomatic workarounds: carry the behaviour as data (a callable in the tuple) and dispatch on self inside one method:


class Operation(enum.Enum):
	PLUS = (operator.add,)
	TIMES = (operator.mul,)

	def __init__(self, fn: Callable[[int, int], int]) -> None:
		self.fn = fn

	def apply(self, a: int, b: int) -> int:
		return self.fn(a, b)

In Python we can dynamically look up an enum member both by name Color["RED"] and by value (Color("red")). The latter is not supported in Java. Related to this, we can customize behaviour when trying to access an element using a non existing value, by means of defining a _missing_ method:


from enum import Enum
class Color(Enum):
    RED = "red"
    BLUE = "blue"
    @classmethod
    def _missing_(cls, value):
        value = value.lower()
        for member in cls:
            if member.value == value:
                return member
        return None

Color.RED is Color("rEd")
# True

Saturday, 15 August 2026

Linux Dynamic Linking

A few months ago I wrote a post about glibc, it's a good time now to follow up with a related element of linux systems, ld-linux.so, the dynamic linker or dynamic loader.

If you need a refresh on what linking is, this wikipedia article should be enough. In this post I'll be talking about dynamic linking on Linux (performed by ld-linux.so), do not confuse it with the static linking performed by the ld tool (part of the binutils package, in turn part of the build-essential metapackage) to create an executable copying inside it the library code it references.

So dynamic linking means loading into a process memory at runtime the libraries (shared objects, .so's) that it needs. This loading is mainly done when the process starts (based on the imports defined in the ELF binary file), but can also be performed dynamically at any point during the process execution, with the dlopen function. In both cases, ld-linux.so (at least in Ubuntu its exact name is: /lib64/ld-linux-x86-64.so.2) is used to perform this loading and linking.

If ld-linux.so is used to load so's, and ld-linux is a so itself, this looks like a chicken-egg problem. Well, it's the kernel itself who takes care of loading it when a process is launched:

A binary names its loader in the ELF .interp section (readelf -p .interp /bin/ls → /lib64/ld-linux-x86-64.so.2). On execve the kernel reads .interp, hands control to that interpreter, which maps the libraries and jumps into the program.

Notice that the dynamic linker/loader is also known as the ELF interpreter.

When you run a dynamically linked program, the Linux kernel reads the executable's Executable and Linkable Format (ELF) header. It looks for a specific section called .interp (or the PT_INTERP program header), which contains the hardcoded string path to this exact interpreter. How the ELF Interpreter Works: Rather than running your program directly, the operating system kernel actually loads and hands control over to ld-linux first. The interpreter then performs several crucial tasks:
- Finds Dependencies: It scans your binary to see which shared libraries (such as libc.so) it needs.
- Loads Libraries: It locates those .so files on the disk and maps them into the program's memory space.
- Resolves Symbols: It performs "relocations," fixing memory references so your program knows exactly where library functions exist in memory.
- Launches Program: Once the environment is ready, it hands control back to your program's main entry point.

There's a strong relation between glibc and ld-linux. They are built together carrying the same version:

The loader (ld.so) and libc.so.6 are a version-locked matched pair. They are built from the same source tree in the same build and talk to each other over a private, unstable ABI: the GLIBC_PRIVATE symbols.
nm -D /lib64/ld-linux-x86-64.so.2 | grep GLIBC_PRIVATE # loader DEFINES them (T/D)nm -D /lib/x86_64-linux-gnu/libc.so.6 | grep GLIBC_PRIVATE # libc has them UNDEFINED (U)

libc.so.6 lists symbols like _dl_allocate_tls@GLIBC_PRIVATE, __tunable_get_val@GLIBC_PRIVATE, _dl_find_dso_for_object@GLIBC_PRIVATE as undefined — “the loader must hand these to me at startup.” The names, semantics, and the layouts behind them (TCB/TLS, _rtld_global) change freely between glibc versions.

ld-linux.so can be executed on its own, as a normal executable. If you run it with the --help version (/lib64/ld-linux-x86-64.so.2 --help) you get this interesting information.

You have invoked 'ld.so', the program interpreter for dynamically-linked ELF programs. Usually, the program interpreter is invoked automatically when a dynamically-linked executable is started.

You may invoke the program interpreter program directly from the command line to load and run an ELF executable file; this is like executing that file itself, but always uses the program interpreter you invoked, instead of the program interpreter specified in the executable file you run. Invoking the program interpreter directly provides access to additional diagnostics, and changing the dynamic linker behavior without setting environment variables (which would be inherited by subprocesses).

libc.so also happens to have an entry point, but it seems to have no other function that showing some information about itself: (/lib/x86_64-linux-gnu/libc.so.6 --version)

GNU C Library (Ubuntu GLIBC 2.39-0ubuntu8.8) stable release version 2.39.
Copyright (C) 2024 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
Compiled by GNU CC version 13.3.0.
libc ABIs: UNIQUE IFUNC ABSOLUTE
Minimum supported kernel: 3.2.0

Invoking ld-linux.so with --version in the same system you'll see that it's the same version as glibc, /lib64/ld-linux-x86-64.so.2 --version

ld.so (Ubuntu GLIBC 2.39-0ubuntu8.8) stable release version 2.39.

Notice that in the glibc information you can see "Minimum supported kernel: 3.2.0". Bearing in mind that my current kernel is 6.8.0, so we can say that glibc is quite little demanding with regards to kernel evolution.

Probably the ldd tool resonates with you. It's just a bash script wrapper (/usr/bin/ldd) around ld-linux.so

Saturday, 8 August 2026

Python Function Call

Over the years I've come to appreciate a real lot how coherent the Python object model is. For example, the callable concept applies to every object that can be invoked, starting by functions. When you define a function, you have an object that is an instance of the types.FunctionType class, a class that has a __call__ method. In contrast, Kotlin has the invokable concept, but this is an extra (the invoke operator) that you can add to your classes, but the basic invokable element, a method/function, is not an instance of a class with an invoke operator. Functions/methods in Kotlin (at the Kotlin language level, then at a JVM or JavaScript runtime things differ) are not objects, we have to get a function reference or a method reference (with the :: syntax) to treat them as objects.

So having in mind that the callable concept applies to normal functions and methods has made me to dive deeper into what I explained in a recent post:

At the C level, all Python objects are represented by the PyObject structure, which points to a PyTypeObject (its type). The type object defines how instances of that type behave.

To make calls fast and avoid creating temporary tuple/dict arguments, CPython uses the vectorcall protocol (Py_TPFLAGS_HAVE_VECTORCALL).
When the interpreter encounters a CALL opcode, it ultimately looks at the target object's type to find its vectorcall entry point:

- Pure Python Functions (PyFunction_Type): The vectorcall pointer points to _PyFunction_Vectorcall. This function extracts the function's PyCodeObject (func->func_code), allocates a new _PyInterpreterFrame on the evaluation stack, and pushes it to _PyEval_EvalFrameDefault.

- Built-in/Native Functions (PyCFunction_Type): Native functions (like math.sqrt or print) are wrapped in a PyCFunctionObject. Their vectorcall pointer points to _PyCFunction_Vectorcall. This function extracts the underlying C function pointer (func->m_ml->ml_meth) and invokes the compiled C code directly.

But, based on the "callable protocol", when the interpreter encounters a CALL opcode, it should check if the type of the object has a __call__ method and invoke it, right? How does this fit with the above? Well, we have to separate language semantics from implementation:

It's a classic example of language semantics vs. implementation details:

At the language level (Python semantics): Everything is an object, and every object that can be invoked implements the callable protocol via __call__. Defining __call__ on function and builtin_function_or_method keeps the object model clean, predictable, and fully inspectable.

At the runtime level (C implementation): The interpreter is allowed to use any shortcut it wants as long as it doesn't break the language semantics. Since invoking fn() is the most critical operation in the language, CPython uses type-checking fast paths (ob_type) to skip the overhead of attribute lookups.

Going deeper:

Looking up __call__ via the attribute resolution mechanism on every function call would carry massive performance overhead. Here is how CPython handles this under the hood and how it fits with the previous explanation. 1. Fast Paths Bypass __call__ Entirely

For pure Python functions (types.FunctionType) and standard C builtins (types.BuiltinFunctionType), CPython completely bypasses the __call__ method lookup.

Even though type(func).__call__ exists at the Python language level (defined on function / PyFunction_Type), the bytecode interpreter does not execute a dictionary lookup for __call__ when you write func().

Instead:

The interpreter checks Py_TYPE(callable).

If it matches &PyFunction_Type or &PyCFunction_Type, it executes the direct fast paths explained previously (allocating a _PyInterpreterFrame or invoking the vectorcall C function pointer directly).

As for custom callables (instances of classes with a __call__ method), the mechanism is also optimized for performance (it's not doing an expensive MRO __call__ search for any object). The structure representing and object's type, PyTypeObject, has 2 fields, tp_call and tp_vectorcall_offset serving different generations of CPython's calling API. tp_vectorcall_offset is used among others for bound methods and functools.partial. tp_call is used for classes that define a __call__ method (and their derived classes). In that case tp_call points to the generic C wrapper that performs the lookup for "__call__" in the object's class dictionary/MRO and invokes it (and so, if the object does not have a tp_call no search is performed at all).

If we have a function: def fn(), we can invoke it normally, via fn(), but also like this: fn.__call__(). The latter invokation form ends up creating the corresponding _PyInterpreterFrame and running fn's code_object in _PyEval_EvalFrameDefault(), but does it through quite a few extra steps. First we have the look up of the __call__ attribute in the fn object, which will find it in the Function class (types.FunctionType). Retrieving it will give us a bound method (types.MethodType), where __self__ is the fn function, and __func__ is the __call__ function. Then, we have the normal invokation of that bound method, that will end up executing the code object for the fn function.

Thursday, 30 July 2026

AsyncLoop 2026

With "async loop" in this post I'm not talking about something like JavaScript's for-await or Python's async-for, where the iterator is asynchronous. What I'm talking about here is about performing an asynchronous operation in a loop (like doing a loop of http requests). Well, in the async/away world that's not something to be scared of, but in the past, when asynchronous code was based on callbacks (not even Promises) this was a bit more complicated. 15 years ago I published a couple of posts about that [1] and [2]. For whatever the reason recently my mind came to think a bit about that old stuff, and I've decided to do a sort of generic AsyncLoop class that could be used with callback based functions. It's intended for use as a sort of for-of loop (so for iterator based loops) and for normal for loops (with a specific logic for getting the next item and checking for stop).

The AsyncLoop class receives a function to obtain the next item in the iteration, a function to check if the iteration must finish and a function (actionFn) for the body of the loop. That function is the one that behaves asynchronously and expects a callback. The class provides to the action/body a callback that will take care of continuing (or stopping) with the next iteration.


class AsyncLoop {
    constructor(nextItemFn, conditionFn, actionFn, onEndFn) {
        this.nextItemFn = nextItemFn; // function that returns the next item
        this.conditionFn = conditionFn; // function that receives the current item 
        this.actionFn = actionFn; // function that receives the current item, a callback to invoke when done
        this.onEndFn = onEndFn; // function that is invoked when the loop ends
    }

    run() {
        let item = this.nextItemFn();
        if (this.conditionFn(item)) {
            this.actionFn(item, () => {
                    this.run();
                }
            );
        } 
        else {
            this.onEndFn();
        }
    }
}


We can use it like this:


// callback based asynchronous function
function getContent(item, callback) {
    setTimeout(() => {
        let content = "Content for: " + item;
        callback(content);
    }, 500);
}

function testAsyncLoop() {
    let countriesIter = ["France", "Germany", "Italy"].values();
    new AsyncLoop(
        () => countriesIter.next().value, // nextItemFn
        (item) => item !== undefined, // conditionFn
        // actionFn
        (item, nextFn) => {
            getContent(item, result => {
                console.log(result);
                nextFn();
            }); 
        },
        () => console.log("All items processed") // onEndFn
    ).run();
}

We can use it also in nested loops:


class Continent {
    constructor(name, countries) {
        this.name = name;
        this.countries = countries;
    }   
}

function testNestedAsyncLoop() {
    let continentsIter = [
        new Continent("Europe", ["France", "Germany", "Italy"]),
        new Continent("Asia", ["China", "Japan", "India"]),
        new Continent("Africa", ["Nigeria", "Egypt", "South Africa"])
    ].values();

    //nested loop
    new AsyncLoop(
        () => continentsIter.next().value, // nextItemFn
        (continent) => continent !== undefined, // conditionFn
        (continent, nextContinentFn) => {
            console.log("Processing continent: " + continent.name);
            let countriesIter = continent.countries.values();
            new AsyncLoop(
                () => countriesIter.next().value,
                (country) => country !== undefined,
                (country, nextCountryFn) => {
                    getContent(country, result => {
                        console.log(result);
                        nextCountryFn();
                    });
                },
                () => nextContinentFn() // onEndFn
            ).run();
        },
        () => console.log("All continents processed")
    ).run();
}

Async/await has always felt a bit like magic (all what the compiler does under the covers), but looking to the above code that we would have written in 2011 and comparing it to how we would write it now with async/await is like a quantum leap!


function getContentPromisified(item) {
    return new Promise((res, rej) => getContent(item, res));
}

async function testUsingAsyncAwait(){
    let continents = [
        new Continent("Europe", ["France", "Germany", "Italy"]),
        new Continent("Asia", ["China", "Japan", "India"]),
        new Continent("Africa", ["Nigeria", "Egypt", "South Africa"])
    ];
    for (let continent of continents) {
        console.log("Processing continent: " + continent.name);
        for (let country of continent.countries) {  
            console.log(await getContentPromisified(country));  
        }
    }
    console.log("All continents processed");
}

Monday, 20 July 2026

Python And Native Modules

When we think about running Python code, particularly in the CPython interpreter, we normally think about interpreted code (a bytecode interpreter), but we also know that we can write native modules (extension modules) normally in C or C++. but also using cython, nuitka or even rust. These extension modules are not used just by some third party libraries, but the python runtime/environment/standard library also makes good use of them. In this sense, as explained in this article we have 2 types of these modules:

  • A built-in extension module is a module built and shipped with the Python interpreter. A built-in module is statically linked into the interpreter, thereby lacking a __file__ attribute.
  • A shared (or dynamic) extension module is built as a shared library (.so or .dll file) and is dynamically linked into the interpreter. In particular, the module’s __file__ attribute contains the path to the .so or .dll file.

Normally the Python interpreter is contained in the python3.XX binary (.exe in Windows), that is like 30 MBs in size, but in some builds (those done with the --enable-shared flag), most of the code is put in a libpython3.14.so (.dll in Windows) dynamic libray, and the python binary just bootstraps it.

built-in extension modules (like sys, builtins, _thread, gc...) are obviously part of the Python distribution (they are inside the interpreter as we've seen), while for shared extension modules, we have those that are part of the python distribution (like math, array, _ssl, _socket) and those that are developed by third parties.

You can check all the built-in extension modules like this:


>>> sys.builtin_module_names
('_abc', '_ast', '_codecs', '_collections', '_contextvars', '_datetime', '_functools', '_imp', '_io', '_locale', '_opcode', '_operator', '_signal', '_sre', '_stat', '_string', '_suggestions', '_symtable', '_sysconfig', '_thread', '_tokenize', '_tracemalloc', '_types', '_typing', '_warnings', '_weakref', 'atexit', 'builtins', 'errno', 'faulthandler', 'gc', 'itertools', 'marshal', 'posix', 'pwd', 'sys', 'time')

While for the shared extension modules that are part of your distribution, just check the lib-dynload folder in your installation, e.g.:

ls -la /usr/local/lib/python3.14/lib-dynload/
total 27032
drwxr-xr-x  2 root root    4096 mar 14 13:26 .
drwxr-xr-x 43 root root    4096 mar 14 13:26 ..
-rwxr-xr-x  1 root root  298704 mar 14 13:26 array.cpython-314-x86_64-linux-gnu.so
-rwxr-xr-x  1 root root  399192 mar 14 13:26 _asyncio.cpython-314-x86_64-linux-gnu.so
-rwxr-xr-x  1 root root  201048 mar 14 13:26 binascii.cpython-314-x86_64-linux-gnu.so
-rwxr-xr-x  1 root root   97240 mar 14 13:26 _bisect.cpython-314-x86_64-linux-gnu.so
-rwxr-xr-x  1 root root 1705384 mar 14 13:26 _blake2.cpython-314-x86_64-linux-gnu.so
-rwxr-xr-x  1 root root  105048 mar 14 13:26 _bz2.cpython-314-x86_64-linux-gnu.so
-rwxr-xr-x  1 root root  166800 mar 14 13:26 cmath.cpython-314-x86_64-linux-gnu.so
...

So when running a Python application you have normal Python functions (that as first step of the execution have been compiled to Python bytecodes) that have to be interpreted, and other functions, living in those extension modules that are already native code and have to be executed as such, without interpretation. How does Python manage that?

The essential part in most interpreters is the interpreter loop. This is the code that loops through the bytecode instructions to be interpreted (or traverses the tree of nodes in Tree-parsing interpreters). I say "most" rather than "all" because in tree parsing interpreters we can have things like Truffle, where each node execute() method takes care of moving to the next node (and also manages its own specialization). In CPython, this interpreter loop lives in the _PyEval_EvalFrameDefault function. It's nicely explained here

When a Python function is invoked we have a Function object and a CALL bytecode instruction. If the function being called is not a native one (so a normal function that was written in pure Python and compiled to bytecodes to be interpreted) the interpreter handles this CALL by creating a frame object (the optimized _PyInterpreterFrame that I discussed here), that contains all the information needed for the function execution: local variables (including arguments and closure cells), the code object... and invokes _PyEval_EvalFrameDefault() with that frame. Indeed, there's a very interesting performance optimization added in Python3.11, _PyEval_EvalFrameDefault no longer recursively calls itself when it finds a new CALL, so we keep a flat C stack. From a GPT:

Ordinary Python→Python calls are frameless on the C stack. A chain of plain function calls runs inside a single _PyEval_EvalFrameDefault C invocation. The CALL opcode pushes a lightweight _PyInterpreterFrame onto a per thread data stack (chunked heap) and dispatches within the same C frame. Plain recursion is bounded by sys.getrecursionlimit() (a logical / data-stack counter), not the C stack.

And from this very in depth article

In CPython 3.10 and earlier, the CALL instruction used to create a new interpreter stackframe for the function being called and then it used to recursively reenter the interpreter by calling its entry point _PyEval_EvalFrameDefault.

This was bad for performance from many angles at the hardware level. The recursive call into the interpreter required saving the registers for the current function, and pushing a new C stackframe. It would lead to increased memory usage because each recursive interpreter call would allocate its own local variables on the stack, and other heap allocations. Apart from that it would also lead to poor instruction cache locality due to the constant jumps in and out of the bytecode evaluation loop.

In the 3.11 release this was fixed by eliminating the recursive call to the interpreter. Now the CALL instruction simply creates the stackframe for the called function, after that it immediately starts evaluating the new function’s bytecode without ever leaving the loop.

I've explained so far how the interpreter manages "normal" functions, but what about native functions? The Function object for a native function does not have a code object (as obviously they don't have associated bytecodes), but a function pointer to the native code. From a GPT:

Native functions: Stored as PyCFunctionObject with a function pointer
No __code__ attribute
Instead, has a function pointer (ml_meth) stored in PyMethodDef
CPython calls the C function pointer directly, bypassing the interpreter loop
The C function executes natively and returns a PyObject*

How does the interpreter check if this 'CALL function_object' should be treated one way or another (_PyInterpreterFrame + _PyEval_EvalFrameDefault() vs native call)? Basically at a low level different objects are used for a "normal" function and a native function. But the whole story goes like this (GPT explanation)

At the C level, all Python objects are represented by the PyObject structure, which points to a PyTypeObject (its type). The type object defines how instances of that type behave.

To make calls fast and avoid creating temporary tuple/dict arguments, CPython uses the vectorcall protocol (Py_TPFLAGS_HAVE_VECTORCALL).
When the interpreter encounters a CALL opcode, it ultimately looks at the target object's type to find its vectorcall entry point:

- Pure Python Functions (PyFunction_Type): The vectorcall pointer points to _PyFunction_Vectorcall. This function extracts the function's PyCodeObject (func->func_code), allocates a new _PyInterpreterFrame on the evaluation stack, and pushes it to _PyEval_EvalFrameDefault.

- Built-in/Native Functions (PyCFunction_Type): Native functions (like math.sqrt or print) are wrapped in a PyCFunctionObject. Their vectorcall pointer points to _PyCFunction_Vectorcall. This function extracts the underlying C function pointer (func->m_ml->ml_meth) and invokes the compiled C code directly.

But things are even more interesting. I already talked about how in Python3.11 the Python interpreter turned into a Python Adaptive Specializing Interpreter. Thanks to that, Function Calls are optimized like this (as explained by a GPT)

If the interpreter had to look up the type and vectorcall pointer from scratch on every single loop iteration, it would be slow. To solve this, CPython uses Opcodes Specialization (PEP 659 Adaptive Interpreter). When a generic CALL opcode executes, it starts in an "adaptive" state. It looks at the object being called and patches itself in memory to a specialized version based on what it sees:

- Python-to-Python Calls
If the target is a pure Python function, the CALL opcode specializes itself into CALL_PY_EXACT_ARGS (or CALL_PY_BOUND_METHOD).

The Check: It performs a strict pointer comparison on the target's type to ensure it is exactly PyFunction_Type.
The Action: It skips the generic lookup, directly grabs the code object, creates the _PyInterpreterFrame, and increments the frame depth.

- Python-to-Native Calls

If the target is a native C function, the CALL opcode specializes into CALL_BUILTIN_FAST or CALL_BUILTIN_CLASS.

The Check: It verifies that the object's type is PyCFunction_Type and often checks if the specific function handler matches what was cached.
The Action: It bypasses the interpreter frame creation entirely, sets up the C arguments, and jumps straight into the native C function.

That's fascinating!

If out of curiosity we want to know if a function is pure Python or native code we can check its type. For normal functions its type is FunctionType, for native functions it's BuiltinFunctionType


# Normal functions:
import types
import math

def f1(): pass
l1 = lambda x: x

isinstance(f1, types.FunctionType)
True
isinstance(l1, types.FunctionType)
True

isinstance(len, types.FunctionType)
False
isinstance(len, types.BuiltinFunctionType)
True
isinstance(math.sqrt, types.BuiltinFunctionType)


Additionally, as I've mentioned, native functions lack a __code__ attribute.


f1.__code__
code object f1 at 0x76be17bfcac0, file "", line 1

len.__code__
Traceback (most recent call last):
  File "", line 1, in 
    len.__code__
AttributeError: 'builtin_function_or_method' object has no attribute '__code__'. 

Thursday, 9 July 2026

Python unpacking and multiple assignment (again)

When I talked about Python destructuring assignment I also mentioned the * and ** syntax, and referred to it as "operators" which indeed is not right (though it's common to name them like that). They should be better referred as unpacking/packing syntax or star expressions. For the different use cases of this syntax:

  • function invokation: f1(*args, **kwargs) or function definition: def f2(*args, **kwargs) we should talk about arguments unpacking or packing
  • When used in collection literals we should talk about iterator unpacking: [*items1, *items2] and dictionary unpacking: {**dict1, **dict2}, with the expressions being called "starred expressions"
  • When used on the left side of an assignment: first, *reminder = my_list, we talk of a "starred target".

As we know the unpacking (destructuring) happens automatically when performing a multiple assignment, with no need of using * at all


x, y = [1, 2]
print(f"x: {x}, y: {y}")
# x: 1, y: 2

There are some advanced uses that I tend to forget. We can use multiple assignment with object attributes or dictionary keys:


@dataclass
class Person:
    name: str
    age: int
    country: str

# multiple assignment to attributes of an object
p1 = Person("Antoine", 47, "France")
p1.name, p1.age = ["Francois", 48]
print(f"p1.name: {p1.name}, p1.age: {p1.age}")

# multiple assignment to dictionary keys
d1 = {}
d1["name"], d1["age"] = ["Francois", 48]
print(f"d1['name']: {d1['name']}, d1['age']: {d1['age']}")


As I explained in this post we can unpack nested structures:



x, [a, b], y = [1, [2, 3], 4]
print(f"x: {x}, a: {a}, b: {b}, y: {y}")
# x: 1, a: 2, b: 3, y: 4


But notice that nested unpacking works for assignment, but not for function parameters. Surprisingly this is something that worked in Python2 but was lost in Python3.


>>> def f(a, (b, c)):
...     return c

SyntaxError: Function parameters cannot be parenthesized


>>> def f(a, [b, c]):
...     return c
...     
            
SyntaxError: invalid syntax


Python is missing the object destructuring assignment feature present JavaScript, I mean:


const user = {
  id: 42,
  isVerified: true,
};

const { id, isVerified } = user;

So we have to use this more verbose approach (notice that itemgetter and attrgetter are a nice option for dynamic scenarios)


p1 = Person("Antoine", 47, "France")

name, country = p1.name, p1.country
name, country = attrgetter("name", "country")(p1)

name, age = d1["name"], d1["age"]
name, age = itemgetter("name", "age")(d1)


Wednesday, 1 July 2026

Python Class Body to the Limit

In my 2 previous posts [1] and [2] we've seen how the class body of a Python class statement is just executable code that is put in a code object around which a synthetic function is created. This code is executed during the class creation (receiving a namespace object, a dictionary, created by the __prepare__ method of the metaclass). This is pretty powerful, as you can put complex initialization code there, not just a normal assignment). We can apply a decorator conditionally, create multiple function alias, define functions conditionally... Let's see some examples.


def log_deco(fn):
    def log_wrapper(*args, **kwargs):
        print(f"invoking {fn.__name__}")
        return fn(*args, **kwargs)
    return log_wrapper

def do_nothing_deco(fn):
    return fn

log_mode = True
profile_mode = Trumult

class Person:
    def __init__(self, name: str): 
        self.name = name

    # conditional decorator
    @(log_deco if log_mode else do_nothing_deco)
    def say_hi(self, to_x: str):
        print(f"hi {to_x} I'm {self.name}")

    # declare a function conditionally
    if profile_mode:
        def get_memory_consumption(self):
            print("my memory consumtpion is ...")

    def do_something(self):
        print(f"{self.name} is doing_something")

    # function aliases
    work = do_something
    cook = do_something
    sleep = do_something

p1 = Person("Francois")
p1.say_hi("Iyan")
p1.get_memory_consumption()
p1.sleep()


# invoking say_hi
# hi Iyan I'm Francois
# my memory consumtpion is ...
# Francois is doing_something

That's pretty nice, right? As the class body ends up being executed as a function you can put any code in it, and the compiler will compile any declarations that you put in it as attributes in the namespace object (that then is passed to the __new__ and __init__ of the metaclass to create the class). But there's one limitation. What if I want to create several alias for a same function using a loop? in principle we can't.


class MyGeoManager:
    _not_implemented = lambda self, item:  print(f"Method is not implemented yet")
    for name in ["get_city", "get_country"]:
        # obviously this does not do what we would like
        name = _not_implemented 

Obviously the above is not doing what we want. It's just creating an attribute named "name" and assigning it in a loop. How could we add an attribute get_city and an attribute get_countr?

Well, we can leverage something we've seen in previous posts, our friend frame.f_locals. I mentioned it in my last post and talked about it in depthhere. f_locals gives us a write-through proxy to the locals of a function. When using an optimized scope, adding variables to that proxy has no particular useful effect, as the function has been compiled to acces by index to the variables that were found at compile time, but in the kind of scope used in a class body, that is a real dictionary, not a fast-array, adding new variables via f_locals adds them to the namespace dictionary that then is passed to __new__ and __init__. So we can do this:


class MyGeoManager: 
    local_namespace = inspect.currentframe().f_locals
    not_implemented = lambda self, item:  print(f"Method is not implemented yet")
    for name in ["get_city", "get_country"]:
        local_namespace[name] = not_implemented

print(f"get_country: {MyGeoManager.get_country}")
print(f"get_city: {MyGeoManager.get_city}")

It works like a charm!

There's another way to do this, derived from how class scope differs from optimized scopes. We are used to the builtin functions exec, compile and eval working with a snapshot of the locals namespace (because we are used to work in optimized scopes), but in a class scope, these functions receive the real namespace object. So we can leverage exec() like this:


class MyGeoManager:
    not_implemented = lambda self, item: print("Method is not implemented yet")
    for name in ["get_city", "get_country"]:
        exec(f"{name} = not_implemented")


Sunday, 21 June 2026

Python Class Body and Lexical Scope

In my previous post about class creation in Python I mentioned how a code object is created for the code in the class body, and then that code object is executed as a function receiving a namespace object (created by __prepare__) as its locals. The class body will add attributes to that namespace, and can use whatever is already present in that namespace (if __prepare__ has put something there). This has made me wonder if apart from that, the class body can have access to its enclosing scope. Just remember that in this post we saw that methods in a class have access to its enclosing scope (they close over variables defined outside the class).

So the answer is YES, and it's just the closures mechanism in action. Let's see an example:


def create_class(id: str):
    class MyClass:
        # the class initialiation (the class body) has access to "external" variables in the enclosing scope, such as "id"
        # the code in the class body is placed in a codeobject that will run in a function having trapped (closed over) the "id" free variable
        class_id = id
        
        print(f"Free variables: {inspect.currentframe().f_code.co_freevars}")
        # Free variables: ('id',)

        def __init__(self, value):
            self.value = value

        def display(self):
            print(f"MyClass value: {self.value}, Class ID: {self.class_id}")

    return MyClass

cl = create_class("123")
instance = cl("aa")
instance.display()

# Free variables: ('id',)
# locals: {'__module__': '__main__', '__qualname__': 'create_class..MyClass', '__firstlineno__': 7, 'class_id': '123'}
# MyClass value: aa, Class ID: 123


As you can see, that class body (my understanding is that Python will execute the code object corresponding to that class body by putting it in a "synthetic function") has access to the id variable in the outer scope and can assign it to one of its attributes. We can see that 'id' in the list of freevars for the code object of the class body (that we get accessing the current frame from the class body itself). However, I came across something that confused me. If I print locals() from the class body, I can't see 'id' there. That's very strange, if I do the same from a normal function, locals shows both "normal" variables and those that the function has trapped in its closure, but, as I've said, for the class body, 'id' is missing in locals:


def create_class(id: str):
    class MyClass:
        # the class initialiation (the class body) has access to "external" variables in the enclosing scope, such as "id"
        # the code in the class body is placed in a codeobject that will run in a function having trapped (closed over) the "id" free variable
        class_id = id
        
        print(f"Free variables: {inspect.currentframe().f_code.co_freevars}")
        # Free variables: ('id',)

        # notice that locals() does not show the id free var
        # that's because we are running in "class scope" and locals() just shows its namespace, not the closure cells. The closure is a separate object that holds references to the free variables, and it is not part of the local namespace of the class body. However, the class body can still access the free variable "id" through the closure.
        print(f"locals: {locals()}")
        # {'__module__': '__main__', '__qualname__': 'create_class..MyClass', '__firstlineno__': 4, 'class_id': '123'}

While for a normal function, it's well there:



def outer(id):
    def inner(value):
        # locals() shows "id" free variable because we are in a function scope (optimized scope)
        print(f"locals: {locals()}")
        # {'value': 'bb', 'id': '456'}
        print(f"Inner function value: {value}, Outer ID: {id}")
    return inner

inner_func = outer("456")
inner_func("bb")


So, why is that? At the time of the Python3.13 release I wrote a post about locals(), f_locals and the "local namespace" (this is related to PEP-667). Well, indeed what I mention on that post (based on other articles) about the "local namespace" as a sort of dictionary is not correct for normal functions in recent Python versions. In "normal" functions we are working in an Optimized Scope. In this optimized scope local variables are not placed in a dictionary and accessed by key, but in a fastarray, and accessed by index (you can see this using dis to check the bytecodes of a function). This locals fastarray, part of the _PyInterpreterFrame for each running function, contains both local variables (including function arguments and those local variables that are cells, cellvars, because they are trapped by inner functions in its closure) and variables trapped by the function itself in its closure:

In CPython's frame object, the `fastlocals` array is laid out as:

[regular locals] [cellvars] [freevars]

At the beginning of a function that has variables in its __closure__ the `COPY_FREE_VARS` bytecode instruction copies cell references from `__closure__` into the frame's fastlocals array for quick access!*
After `COPY_FREE_VARS` executes, all variables (normal locals, cellvars and freevars) are accessed from the fastlocals array during function execution.

By the way, regarding the aforementioned _PyInterpreterFrame, I'll leverage to copy here some GPT wisdom about frames in recent (Python 3.11 and above) Python versions

The _PyInterpreterFrame is an internal C struct introduced in Python 3.11 that represents a stack frame for execution, aiming to improve performance by reducing the overhead of allocating full Python PyFrameObject objects.

Purpose: It holds the execution state for code objects, including local variables, globals, builtins, and the instruction pointer (f_lasti).
Performance: Unlike older Python versions where every frame was a full heap-allocated PyFrameObject, _PyInterpreterFrame is designed to be lightweight and often lives on the C stack, reducing garbage collection pressure.

The traditional PyFrameObject still exists, but it has been relegated to a "shadow" role. It is now treated purely as a compatibility API wrapper.

Python only creates a PyFrameObject on demand when a tool or a piece of code explicitly asks to inspect the call stack. This process is often referred to as materializing a frame.