Why does not python give warning when a variable changes its type

I have been hit by this problem but I anticipate it is going to hit me in the future.

Case1 : I have use phi_func = False in a code (so can I turn on and off easily later)
and then define a variable call phi_func to be assigned any of the 3 predefined functions Sure enough if phi_func: suddenly becomes true. Took me a while to figure out.

Case2: I have accidentally use dict for a dictionary type variable. No problem when the code
is short. But when the code grows big and when i use
ax.text( …, bbox=dict(…)) that gives very strange error about dict is not callable.

For Case2 I spent a few good hours trying to isolate the “bug”.

This name collision is killer. It is a compounded by sophisticated syntax esp in matplotlib.

Live with it as long as we are using python? I believe just too many hours per person have been spent
in this kind of thing.

This isn’t related to Jupyter, it’s a general question about the design of Python.

You might find type hints useful

1 Like

If you are working in jupyter(lab), you can get some help from jupyterlab-lsp, a language server, and some plugins.

a tldr example:

mamba install jupyter-lsp-python-plugins jupyterlab-lsp
# restart jupyterlab

Of course, this exposes all of the problems mypy will find, which will be many for your average quick-and-dirty data munging/vis code.

Another technique is using run-time type-checking libraries, such as:

but these can become their own burden, and incur various levels of overhead.

1 Like