0

Here's a piece of code that I cannot understand:

class COWMeta(type):
    pass

class COWDictMeta(COWMeta):
    ....

I know how to create a new class in python:

class MyClass(BaseClass):
    ...

But as the manual states, 'type' is function.

type(...)
Function of __builtin__ module
type(object) -> the object’s type type(name, bases, dict) -> a new type

How can a class inherit from a function? And what does that piece of code mean?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
ChenQi
  • 1,196
  • 2
  • 8
  • 9
  • 3
    And just below that it says "With three arguments, type() functions as a constructor as detailed below.", and "Return a new type object". – Martijn Pieters Aug 14 '12 at 08:35
  • 3
    `type` is the base type. It just happens to be callable (i.e. executable as a function). It's not a function object. Try `repr(type)` in the interpreter to see what it is. – Noufal Ibrahim Aug 14 '12 at 08:35
  • Why do you want to inherit from type? –  Aug 14 '12 at 08:37
  • @esaelPsnoroMoN: in Python, inheriting from `type` is a common pattern, and is basically the only way of creating metaclasses. – jsbueno Sep 07 '12 at 22:37

2 Answers2

4

type is the basic object type in python. Like many object types in python, it acts as a constructor for creating new types, but in it's simplest form it'll return the type of existing objects. It then looks like a function. Compare this to int() and list(), for example.

In python, you can create new types, also called metaclasses, allowing you to do all sorts of powerful and interesting tricks in Python. Basing a class definition on type means you are creating a new metaclass.

See What is a metaclass in Python? for an in-depth answer on what metaclasses are.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

type is not a function in the same way that, eg:

def foo():
    pass

is a function. It is callable like a function (and like many other objects in Python), but it is actually coded as a class. type itself can show you this difference:

>>> type(type)
<class 'type'>
>>> type(foo)
<class 'function'>

The docs call it a 'function' not because of how it is implemented, but because of how it is commonly used. This is broadly similar to, for example, itertools.permutations, which while not explicitly called a function by the docs is implied to be one:

Return successive r length permutations of elements in the iterable.

But itertools.permutations is implemented as a class:

>>> type(itertools.permutations)
<class 'type'>
lvc
  • 34,233
  • 10
  • 73
  • 98