problems with the types module

Carl Banks imbosol at vt.edu
Wed Dec 11 15:40:37 EST 2002


Michele Simionato wrote:
> Consider the following script:
> 
> ------ begin types1.py -----
> 
> from types import *
> 
> class C(object):
>      def m(self,x): return x*x
>      assert type(m) is FunctionType
>      print 'type of m inside its class:',type(m)
> 
> print 'type of C.m:', type(C.m)
> assert type(C.m) is MethodType
> 
> ------ end types1.py -----
> 
> The output is 
> 
> type of m inside its class: <type 'function'>
> type of C.m: <type 'instance method'>
> 
> i.e. the same object is seen as a function inside the class scope
> and as an instance method outside the class scope. To me, this fact
> was quite surprising, I don't like to have a changing type depending
> on the context. Maybe a unique 'function' type for both functions
> and methods would have been a simpler solution.

It's not the same object, though.  When you access m in the class
scope, it's just a function, as you defined it.

However, when you write C.m, the class does not return the m you
defined.  Instead, it returns a completely different object of type
instancemethod.  The instancemethod object holds a reference to the
actual function m.  When the instance method is called, calls the
actual function m with the appropriate self argument.



[snip]
> Now, C.m is no more an instance method, but it is a function (I understand 
> the logic in that), whereas the type of m is ?????  
> By ????? I mean that in the types modules there is no StaticMethodType,
> I couldn't find any correct assertion for the type of m !
> According to the documentation in types the following names are defined: 
> 
[snip]
> 
> There is no StaticMethodType. At the best, this in inconsistent with the
> output of type(m) when invoked in its class. I am looking forward for
> reactions and comments, yours


Maybe it should.

But, IIRC, the language designers are trying to phase out the types
module.  A lot of built in types (those with constructors, anyways)
have built in symbols that serve as name of the type.  So, instead of
using IntType, you should use int.  Instead of StringType, you should
use str.  Instead of FileType, you should use file.

For static methods, you can use staticmethod.

And one other thing: a lot of people, myself included, believe that
using types explicitly can defeat the dynamicism of Python, which is
what makes Python so great.


-- 
CARL BANKS



More information about the Python-list mailing list