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

J

jamesthiele.usenet

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:<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
 
P

Pedro Werneck

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.


"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
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:<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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,219
Messages
2,571,117
Members
47,727
Latest member
PasqualePf

Latest Threads

Top