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
2
  • All of those seem correct. What do you expect type(function) to return? Commented Jul 11, 2014 at 22:01
  • 4
    possible duplicate of What are "first class" objects? Commented Jul 11, 2014 at 22:03

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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').

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.