0

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?

  • 10
    No - that's the whole point of dynamic typing. – Doval Oct 1 '14 at 12:02
  • 3
    Do you want a yes/no answer or are you open to being sold on why this isn't a terrible thing(tm)? – user7043 Oct 1 '14 at 12:04
  • 1
    There is no way to prevent this. However, there also isn't a generally accepted reason why! Myself, I have great trouble understanding why people would want the type of a variable to vary. But many, many others have trouble seeing why some would NOT want it to vary, e.g. see here: programmers.stackexchange.com/questions/134486 – Kilian Foth Oct 1 '14 at 12:06
  • 3
    @danijar Dynamic typing isn't something you can "disable" (unless you want undefined behavior.) To begin with, dynamic languages are static languages with a single type, so you're really talking about adding to the language, not turning off parts of it. Enforcing static typing in all Python code would break existing code, too, so you'd have to accept holes in your type checking. You should probably look for statically typed languages with Python's strong points. I'm guessing you like the uncluttered syntax and conciseness; you might want to look into functional languages like OCaml or F#. – Doval Oct 2 '14 at 11:33
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.