If you are fairly new to Python, or even have used it for a while but wonder about how variables work in the language, I strongly recommend reading Chapter 6 of Learning Python (3rd ed., O’Relly), by Mark Lutz, entitled “The Dynamic Typing Interlude.” You may have heard that Python is not a “strongly typed” language as opposed to, say, Java. Lutz’s clear and concise explanation of Python’s handling of variables, objects, and the “references” which connect them will help you understand what typing means in Python. The upshot is that objects are typed, variables are not. Variables are simply names that point to, or reference, objects. Variables can be reassigned to objects of different types, and there are no built-in constraints on what kinds of objects a variable can point to.
Now, this “dynamic typing” has some implications for coding practices, in particular for commenting and documentation. While Python’s intuitive syntax and indentation requirements contribute to a certain base level of readability, the fact that variables do not point to fixed types can make deciphering complex code somewhat more challenging. In Java, for example, you know from a function’s signature exactly what kinds of arguments it requires, what kind of value it returns (if any) and what kinds of exceptions it may throw. There’s really no way to provide this information in the syntax of Python itself; you have to document it in your code. Also, certain errors that would be caught in other languages by the compiler (such as references to non-existent attributes or methods of an object), may only be caught at runtime in Python.
While on balance I much prefer the greater flexibility and simplicity that dynamic typing offers, I miss being able to glance at a function signature and know how to use it. Even the official Python documentation can be too vague for my taste about what a function does. Take the documentation on
urllib2, for example. For the function
urlopen(), the doc (as of Python 2.6.1) says it returns a “file-like object”. What does that mean? Do I need to know? Should I read the source code?