type() takes one or *three* arguments!?

Pedro Werneck pedro.werneck at terra.com.br
Sun Jan 30 15:41:34 EST 2005


Hi,

Up to Python 2.2, type() was just a function to return an object type.
>From 2.2 on, type have this behavior when called with only one argument
and is used to create a new type when called with 3 arguments.


>From http://www.python.org/2.2/descrintro.html :

"The signature of type() requires an explanation: traditionally, type(x)
returns the type of object x, and this usage is still supported.
However, type(name, bases, methods) is a new usage that creates a brand
new type object. (This gets into metaclass programming, and I won't go
into this further here except to note that this signature is the same as
that used by the Don Beaudry hook of metaclass fame.)"



So, an example:

Foo = type('Foo', (object,), {})

and...

class Foo(object):
   pass

Are the same thing... 




On 30 Jan 2005 11:57:23 -0800
jamesthiele.usenet at gmail.com wrote:

> I was looking at Simon Burton's Povray.py code (part of pypov) and saw
> this line:
> globals()[name] = type( name, (KWItem,), {} ) # nifty :)
> 
> where 'KWItem' was a class. It did seem nifty, but it was unclear to
> me what was happening.
> 
> I went to python.org's online documentation which said that type()
> takes one argument. So I fired up python:
> >>> type(42)
> <type 'int'>
> >>> type("x", (type(42),), {})
> <class '__main__.x'>
> 
> OK, It appears that type() with 3 arguments constructs a class. Is
> this documented somewhere? If not can someone explain what is going
> on? james
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list