Data Type Enforcement at Runtime Level in Python

Such a wild dream, isn't it?

Python is quite dynamic. Variables can reference strings, then lists, then sets... It's an intrinsic characteristic of the language.

I was there, thinking that it could be possible. Never found a safe trail for achieving this, and for a long time, I thought it was just me. Some think that Type Hints could be a starting point of having such feature, without understanding the concept of Type Hints and annotations.

Some people might think that Data Classes could provide some solution, and nope: Data Classes are just a more elegant way of creating Classes, implementing __init__ and __repr__ methods by default, among other functionalities, but still, it does not take care of type enforcement at runtime level.

The best that you could have is type enforcement at instantiation level, being a Data Class or not, but still, you can pass the expected data while creating the object, later on changing the instance variable, without any validation penalty:

Pydantic does this kind of type enforcement gracefully at object creation, not runtime:

It's unlikely to happen in the near future, to be honest. And if it happens, it would be a great change for the specification of the language. Data type enforcement is a great advantage in compiled languages (not our case here), then accidents of defining an integer to a char type variable, not being allowed by the compiler.

To keep a variable consistent in regards with its data type, is something we must do by default while developing in Python. IDEs and linters can help on that. And that's the best that you can have.

I shared something on this thread a couple of weeks ago:

If type enforcement at runtime level is something you really need on your project, you need a different programming language, considering the trade-offs of not using Python.

It would be nice to have such thing in Python, one day. Hope that it will not remain as a wild dream that we all kind of have.

Mastodon