Variables in Python don't have types. They're just names for values. Those values, of course, do have types, but the variables don't care. Just as "John" can be the name for a man in one conversation or for a poodle in another, a
can be the name for an int
in one part of your program and a str
in another part.
This is part of a much larger difference between variables in Python and whatever language you're probably coming from.
In C++, a variable actually defines a location in memory where values can live. For example, and int
variable has 4 bytes of memory, and when you write a = 42
, it copies the number 42 into those 4 bytes.
In Python, a variable just defines a reference to a value that has its own life off somewhere on the heap. The value's storage still has to have a type, of course, but the variable isn't the value's storage.
(If C++ really is your most familiar language, it may help to think of every Python variable as being of type std::shared_ptr<boost::any>
.)
There are some programs where being able to reuse variable names for different types is useful, but there are others where it's more likely to be a bug than something intentional. There are static analyzers like mypy
that you can use to check for such bugs. In most cases, automated type inference is sufficient to figure out what type you wanted a variable to be and make sure you used that type consistently. When it's not, PEP 484 (which will probably be part of Python 3.5, and is already mostly handled by mypy
) standardizes a way to help these analyzers by giving them explicit type hints.
One last thing: If you're curious how this works under the covers, in Python, every scope's namespace is just a dictionary. When you write a = 5
at the module-global level, it's just like doing g['a'] = 5
, where g
is the module's dictionary. There are a few tricky bits with locals and closures, but basically, this is the key to how variables work.