Python – way to prevent variables from changing their type in Python

duck-typingdynamic-typingpythonvariables

It is useful to have the interpreter derive the type of a variable automatically. This on its own is similar to the auto keyword in C++11. However, in Python variables can change their type after being declared for the first time. This potentially can cause a lot of errors. I haven't seen any reasonable use case for this, besides changing from or to None.

For performance reasons, PyPy claims to be written in what they call RPython, which goes into this direction. However, it seems like there is neither a standard for this nor a way to make the interpreter complain about type changing.

Is there a way to prevent variables from changing their type in Python?

Best Answer

A Python variable is not like a C variable, which is to say it is not a box with data inside it. A Python variable is more like a sticky note that has been stuck on a box with data inside it.

The type of the box's data rarely changes, but the sticky note can be passed from box to box to box.

So, the type isn't really changing.

Having said that, there are ways to limit this: Use a class with custom descriptors to check and enforce what new value is trying to be assigned to your sticky-note variable name, and use a custom metaclass to prevent the class variable sticky note from being reassigned to something else.

I beleive Enthought Traits have this ability.

Related Topic