Reputation: 1247
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
Upvotes: 5
Views: 1191
Reputation: 38173
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.
Upvotes: 5
Reputation: 41898
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.
Upvotes: 3