Tim
Tim

Reputation: 99428

What is the type of `function` and of `module`

>>> type(OptimizedRectangle) 
    <class 'type'>    
>>> type(OptimizedRectangle.get_area)
<class 'function'>

So a method of a class is an instance of class function.

>>> type(function)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'function' is not defined

Since function is a class and a class is an object, what is the type of function, i.e. what is it an instance of?

As the comments suggested

>>> type(type(OptimizedRectangle.get_area))
<class 'type'>

Then why does type(function) not work? Is function a class, of which a class's method is an instance?


Similarly, why does type(module) not work?

>>> type(builtins)
<class 'module'>
>>> type(module)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'module' is not defined

Upvotes: 2

Views: 424

Answers (2)

a_guest
a_guest

Reputation: 36249

The built-in module types stores all kind of different types that are used throughout the language. It contains also the FunctionType which corresponds to the instance method:

>>> class Foo:
...     def bar(self):
...         pass
>>> type(Foo.bar) is types.FunctionType
True

When calling type(Foo.bar) in the interpreter then the output is <class 'function'> however this does not necessarily mean that the class's name is 'function' but it is just the class's representation (__repr__):

>>> type(types.FunctionType).__repr__(type(Foo.bar))
"<class 'function'>"

As pointed out in the comments types.FunctionType also only holds a reference to the type of functions which is defined at the implementation level.

The type of FunctionType is type again, that is FunctionType is an instance of type (as it is the case for all classes).

Also note the peculiarity

>>> type(type) is type
True

which means that type is its own class (i.e. type.__class__ pointing to itself). This is achieved at the implementation level.

Upvotes: 3

Aditya Banerjee
Aditya Banerjee

Reputation: 372

A function is the simplest callable object in Python. read more here

Upvotes: 0

Related Questions