Yes, in Python 3 everything is an object
and hence an instance of some class. We can check this explicitly with isinstance
.
def f(x):
return x
print(isinstance(f, object)) # True
Interestingly, the name function
is not defined in builtins, but we can use it just fine, as you've already identified, by saying
function = type(f)
It's worth noting that built-in functions and (bound) methods have different types than regular functions.
class A:
def foo(self):
pass
print(type(f)) # <class 'function'>
print(type(abs)) # <class 'builtin_function_or_method'>
print(type(A.foo) # <class 'function'>
print(type(A().foo) # <class 'method'>
We can use help(function)
(where function
is defined as above) to get some more info on the constructor.
class function(object)
| function(code, globals, name=None, argdefs=None, closure=None)
|
| Create a function object.
|
| code
| a code object
| globals
| the globals dictionary
| name
| a string that overrides the name from the code object
| argdefs
| a tuple that specifies the default argument values
| closure
| a tuple that supplies the bindings for free variables
|
| Methods defined here:
|
| __call__(self, /, *args, **kwargs)
| Call self as a function.
|
| __get__(self, instance, owner, /)
| Return an attribute of instance, which is of type owner.
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __annotations__
|
| __closure__
|
| __code__
|
| __defaults__
|
| __dict__
|
| __globals__
|
| __kwdefaults__
As has already been pointed out in the comments, actually calling this behemoth is nontrivial and I can't immediately find any good documentation on how to do so on Python's website.