top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the purpose of type() and the types module in python

0 votes
398 views

The type() builtin according to python docs, returns a "type object".
http://docs.python.org/2/library/types.html

And in this module is bunch of what I assume are "type objects". Is this correct?
http://docs.python.org/2/library/functions.html#type

And type(), aside from being used in as an alternative to a class statement to create a new type, really just returns the object class, doesn't it?

>>> import types
>>> a = type(1)
>>> b = (1).__class__
>>> c = int
>>> d = types.IntType
>>> a is b is c is d
True
>>> 

If type() didn't exist would it be much more of a matter than the following?:

def type(x): 
 return x.__class__

What is the purpose of type()?
What exactly is a "type object"? Is it a "class"?
What is the purpose of the types module?

I understand the purpose of isinstance and why it's recommended over something like (type(1) is int). Because isinstance will also return True if the object is an instance of a subclass.

>>> class xint(int):
 def __init__(self):
 pass

>>> x = xint()
>>> type(x) is int
False
>>> isinstance(x, int)
True
>>> 
posted Jun 27, 2013 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

type() does two things:

  • with a single argument, it returns the actual type of an object;
  • with three arguments, it creates new types.

For example, type(42) returns int, and type([]) returns list. Not the *strings* "int" and "list", but the actual int object and list object.

py> x = 42
py> type(x)("23")
23

The three argument form of type() creates new types, also known as classes. The class statement is just syntactic sugar, under the hood it calls type.

(Note: in Python 2 there is a slight complication due to the existence of so-called "old-style classes", also known as "classic classes". They are a bit of a special case, but otherwise don't really make any difference to what I'm saying.)

For example, the following:

class Spam(object):
 a = 42
 def method(self, x):
 return self.a + x

is syntactic sugar for the much longer:

def method(self, x):
 return self.a + x

d = {'method': method, 'a': 42}
Spam = type('Spam', (object,), d)
del d, method

(more or less, there may be slight differences).

answer Jun 27, 2013 by anonymous
Similar Questions
0 votes

I am trying to make an HTTPS connection and read that HTTPS support is only available if the socket module was compiled with SSL support.

http://www.jython.org/docs/library/httplib.html

Can someone elaborate on this? Where can I get the socket module for HTTPS, or how do I build one if I have to?

+2 votes

I saw three different types of quotes in python. For me all gave same result.
Can anyone explain what could be the reason of having three different quotes in python and which one is used in what circumstances ?

...