0

I am using python 3, and am wondering what 'function' is.

For example, here I create a function a and print its type.

def a():
    pass

print(type(a))

I get <class 'function'>.

When I try to use the type function, however, I get a NameError.

Here is an example:

function

or

fplaceholder=function

both give me a NameError, saying function is not defined.

What exactly is function, then?

user18798042
  • 107
  • 7
  • 4
    I believe it is `types.FunctionType` – Somebody Out There Aug 15 '22 at 23:05
  • 3
    In CPython, functions are implemented in C as [`PyFunctionObject`](https://docs.python.org/3/c-api/function.html#c.PyFunctionObject), which is exposed to the programmer as [`types.FunctionType`](https://docs.python.org/3/library/types.html#types.FunctionType). – wkl Aug 15 '22 at 23:08
  • 1
    @Vladimir Vilimaitis and @wkl, can I assume that `types.FunctionType` will behave as the nonexistent function in most cases? – user18798042 Aug 15 '22 at 23:14
  • @user18798042 - What do you mean by "nonexistent function"? There isn't such a thing. There is `None`, which is the general NULL object in python. But all variables and containers have to reference an object, even if that object is `None`. – tdelaney Aug 15 '22 at 23:36
  • @tdelaney, I was making a joke. It has to do with the fact that you get a `NameError` when attempting to reference `function` in Python (meaning it isn't defined). – user18798042 Aug 15 '22 at 23:50
  • @user18798042 - Its a type, not a function object. You can build your own function object via `fplaceholder = types.FunctionType(...)` but you also need to supply the initialization paramters. Perhaps just a `code` object that you could get via `compile(...)`. – tdelaney Aug 16 '22 at 00:47

0 Answers0