Python Newbie

Oscar Benjamin oscar.j.benjamin at gmail.com
Mon Feb 25 01:45:09 CET 2013


On 25 February 2013 00:08,  <piterrr.dolinski at gmail.com> wrote:
Chris Angelico wrote:
>> For example (I believe it's already been mentioned) "declaring" intX with some integer value does *nothing* to maintain
>>
>> X as an integer:
>>
>> --> intX = 32
>>
>> --> intX = intX / 3.0
>>
>> --> intX
>>
>> 10.6666666666
>>
>
> Yes I did see that it is possible to redefine the type of a variable. But I don't think I would ever do this intentionally; need to be really careful with Python.

You do need to be careful around types in Python (as in all
languages). It took some time for me to understand how to use types in
Python. After a while I came to realise that not knowing exactly the
type of a particular object is not as much of a problem as I initially
thought. Once you understand how to use this ambiguity to your
advantage it becomes possible to write very flexible code that can be
reused without ambiguity in situations that you haven't yet
anticipated.

The key mental hurdle, I think, is to realise that instead of relying
on compilation errors to spot (a small subset of) your programming
errors, you are relying on runtime exceptions. Python still gives
errors when you use an object in a way that is inconsistent with its
type; you just don't see those errors at compile time.

The trickier cases are ones where two types are very similar and can
be used similarly in most, but not all, situations. An example of this
would be the one that Chris has highlighted where an object that you
expected to be an int is actually a float. I find that I need to be
careful when using division on quantities that I expected to be
integers (true in all languages) and careful about the notation used
in a numeric literal. Once you get used to it, you will find it easy
to see that the '.0' that Chris appended was deliberate in order to
control the type of the resulting object.


Oscar



More information about the Python-list mailing list