Python types

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Mar 27 01:34:14 CEST 2006


Salvatore a écrit :
> Thank's everybody :-)
> 
> 
> Here is a type définition I've found on the net which I agree with :
> 
> Attribute of a variable which determines the set of the values this
> variabe can take and the
> operations we can apply on it.

Then - as already pointed by Alex - there is no type in Python, since 
there is no variable (even if this term is often improperly used for 
bindings) !-)

Ok, let's s/variable/object/g and define some objects and operations:

def myop(obj):
   return obj.foo * 2

class Bar(object):
   pass

b = Bar()

Can we apply the myop() operation on the object name 'b' is bound to ?

myop(b)
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 1, in myop
AttributeError: 'Bar' object has no attribute 'foo'


Well... but wait a minute:
b.foo = []
myop(b)
-> []

Err... Wait another minute:

b2 = Bar()
type(b) is type(b2)
-> True
myop(b2)
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 1, in myop
AttributeError: 'Bar' object has no attribute 'foo'

Ok, so even if Python itself declares b and b2 (read: objects that names 
b and b2 are bound to) to be of the same type,  you cannot apply the 
myop() operation on b2...

Also:

del b.foo
myop(b)
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 1, in myop
AttributeError: 'Bar' object has no attribute 'foo'


So *sometimes* you can apply myop() to b, and sometimes you can't.

Now if we come back to your original post:
"""
All objects seem to have a perfectly defined
type
"""

"Perfectly defined" ? Really ? Not for your current definition of 'type' 
at least !-)

I still mostly agree with the given definition of type. But the fact is 
that in Python, the type*s* of an object are not so perfectly defined - 
they're mostly implicits, and can vary during the object's lifetime.

Note that it does'nt make Python weakly typed - you cannot perform any 
arbitrary operation on a given object, only the operations this object 
can support at a given moment. FWIW, if you want a weakly typed 
language, take a look at C.



More information about the Python-list mailing list