5

Given the following behaviour:

    def a():
       pass


    type(a)
    >> function

If type of a is function, what is type of function?

    type(function)
    >> NameError: name 'function' is not defined

And why does type of type from a is type?

    type(type(a))
    >> type

Lastly: if a is an object, why it cannot be inherited?

    isinstance(a, object)
    >> True

    class x(a):
       pass
    TypeError: Error when calling the metaclass bases
        function() argument 1 must be code, not str
Jonathan Simon Prates
  • 1,122
  • 2
  • 12
  • 28

2 Answers2

5

The type of any function is <type 'function'>. The type of the type of function is <type 'type'>, like you got with type(type(a)). The reason type(function) doesn't work is because type(function) is trying to get the type of an undeclared variable called function, not the type of an actual function (i.e. function is not a keyword).

You are getting the metaclass error during your class definition because a is of type function and you can't subclass functions in Python.

Plenty of good info in the docs.

Community
  • 1
  • 1
Alex W
  • 37,233
  • 13
  • 109
  • 109
3

The type of function is type, which is the base metaclass in Python. A metaclass is the class of a class. You can use type also as a function to tell you the type of the object, but this is an historical artifact.

The types module gives you direct references to most built in types.

>>> import types
>>> def a():
...    pass
>>> isinstance(a, types.FunctionType)
True
>>> type(a) is types.FunctionType

In principle, you may even instantiate the class types.FunctionType directly and create a function dynamically, although I can't imagine a real situation where it's reasonable to do that:

>>> import types
>>> a = types.FunctionType(compile('print "Hello World!"', '', 'exec'), {}, 'a')
>>> a
<function a at 0x01FCD630>
>>> a()
Hello World!
>>>

You can't subclass a function, that's why your last snippet fails, but you can't subclass types.FunctionType anyway.

Pedro Werneck
  • 40,902
  • 7
  • 64
  • 85
  • Why do I get the error `SyntaxError: 'return' outside function` if I do `a = types.FunctionType(compile('return 0', '', 'exec'), {}, 'a')` work? Also, note that in Python 3, your second example should be `a = types.FunctionType(compile('print("Hello World!")', '', 'exec'), {"print": print}, 'a')`. – nbro Feb 10 '21 at 16:01