Dynamic typing

Python is dynamically typed, which means that variables do not have a fixedtype. In fact, in Python, variables are very different from what they are inmany other languages, specifically statically-typed languages. Variables are nota segment of the computer’s memory where some value is written, they are ‘tags’or ‘names’ pointing to objects. It is therefore possible for the variable ‘a’ tobe set to the value 1, then to the value ‘a string’, then to a function.

The dynamic typing of Python is often considered to be a weakness, and indeedit can lead to complexities and hard-to-debug code. Something named ‘a’ can beset to many different things, and the developer or the maintainer needs to trackthis name in the code to make sure it has not been set to a completely unrelatedobject.

Some guidelines help to avoid this issue:

  • Avoid using the same variable name for different things.
    Bad
  1. a = 1
  2. a = 'a string'
  3. def a():
  4. pass # Do something

Good

  1. count = 1
  2. msg = 'a string'
  3. def func():
  4. pass # Do something

Using short functions or methods helps reduce the riskof using the same name for two unrelated things.

It is better to use different names even for things that are related,when they have a different type:

Bad

  1. items = 'a b c d' # This is a string...
  2. items = items.split(' ') # ...becoming a list
  3. items = set(items) # ...and then a set

There is no efficiency gain when reusing names: the assignmentswill have to create new objects anyway. However, when the complexitygrows and each assignment is separated by other lines of code, including‘if’ branches and loops, it becomes harder to ascertain what a givenvariable’s type is.

Some coding practices, like functional programming, recommend never reassigninga variable. In Java this is done with the final keyword. Python does not havea final keyword and it would be against its philosophy anyway. However, it maybe a good discipline to avoid assigning to a variable more than once, and ithelps in grasping the concept of mutable and immutable types.