cpython/Objects/funcobject.c


/* Function object implementation */

#include "Python.h"
#include "pycore_ceval.h"         // _PyEval_BuiltinsFromGlobals()
#include "pycore_long.h"          // _PyLong_GetOne()
#include "pycore_modsupport.h"    // _PyArg_NoKeywords()
#include "pycore_object.h"        // _PyObject_GC_UNTRACK()
#include "pycore_pyerrors.h"      // _PyErr_Occurred()


static const char *
func_event_name(PyFunction_WatchEvent event) {}

static void
notify_func_watchers(PyInterpreterState *interp, PyFunction_WatchEvent event,
                     PyFunctionObject *func, PyObject *new_value)
{}

static inline void
handle_func_event(PyFunction_WatchEvent event, PyFunctionObject *func,
                  PyObject *new_value)
{}

int
PyFunction_AddWatcher(PyFunction_WatchCallback callback)
{}

int
PyFunction_ClearWatcher(int watcher_id)
{}
PyFunctionObject *
_PyFunction_FromConstructor(PyFrameConstructor *constr)
{}

PyObject *
PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)
{}

/*
(This is purely internal documentation. There are no public APIs here.)

Function (and code) versions
----------------------------

The Tier 1 specializer generates CALL variants that can be invalidated
by changes to critical function attributes:

- __code__
- __defaults__
- __kwdefaults__
- __closure__

For this purpose function objects have a 32-bit func_version member
that the specializer writes to the specialized instruction's inline
cache and which is checked by a guard on the specialized instructions.

The MAKE_FUNCTION bytecode sets func_version from the code object's
co_version field.  The latter is initialized from a counter in the
interpreter state (interp->func_state.next_version) and never changes.
When this counter overflows, it remains zero and the specializer loses
the ability to specialize calls to new functions.

The func_version is reset to zero when any of the critical attributes
is modified; after this point the specializer will no longer specialize
calls to this function, and the guard will always fail.

The function and code version cache
-----------------------------------

The Tier 2 optimizer now has a problem, since it needs to find the
function and code objects given only the version number from the inline
cache.  Our solution is to maintain a cache mapping version numbers to
function and code objects.  To limit the cache size we could hash
the version number, but for now we simply use it modulo the table size.

There are some corner cases (e.g. generator expressions) where we will
be unable to find the function object in the cache but we can still
find the code object.  For this reason the cache stores both the
function object and the code object.

The cache doesn't contain strong references; cache entries are
invalidated whenever the function or code object is deallocated.

Invariants
----------

These should hold at any time except when one of the cache-mutating
functions is running.

- For any slot s at index i:
    - s->func == NULL or s->func->func_version % FUNC_VERSION_CACHE_SIZE == i
    - s->code == NULL or s->code->co_version % FUNC_VERSION_CACHE_SIZE == i
    if s->func != NULL, then s->func->func_code == s->code

*/

static inline struct _func_version_cache_item *
get_cache_item(PyInterpreterState *interp, uint32_t version)
{}

void
_PyFunction_SetVersion(PyFunctionObject *func, uint32_t version)
{}

static void
func_clear_version(PyInterpreterState *interp, PyFunctionObject *func)
{}

// Called when any of the critical function attributes are changed
static void
_PyFunction_ClearVersion(PyFunctionObject *func)
{}

void
_PyFunction_ClearCodeByVersion(uint32_t version)
{}

PyFunctionObject *
_PyFunction_LookupByVersion(uint32_t version, PyObject **p_code)
{}

uint32_t
_PyFunction_GetVersionForCurrentState(PyFunctionObject *func)
{}

PyObject *
PyFunction_New(PyObject *code, PyObject *globals)
{}

PyObject *
PyFunction_GetCode(PyObject *op)
{}

PyObject *
PyFunction_GetGlobals(PyObject *op)
{}

PyObject *
PyFunction_GetModule(PyObject *op)
{}

PyObject *
PyFunction_GetDefaults(PyObject *op)
{}

int
PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
{}

void
PyFunction_SetVectorcall(PyFunctionObject *func, vectorcallfunc vectorcall)
{}

PyObject *
PyFunction_GetKwDefaults(PyObject *op)
{}

int
PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults)
{}

PyObject *
PyFunction_GetClosure(PyObject *op)
{}

int
PyFunction_SetClosure(PyObject *op, PyObject *closure)
{}

static PyObject *
func_get_annotation_dict(PyFunctionObject *op)
{}

PyObject *
PyFunction_GetAnnotations(PyObject *op)
{}

int
PyFunction_SetAnnotations(PyObject *op, PyObject *annotations)
{}

/* Methods */

#define OFF(x)

static PyMemberDef func_memberlist[] =;

static PyObject *
func_get_code(PyObject *self, void *Py_UNUSED(ignored))
{}

static int
func_set_code(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{}

static PyObject *
func_get_name(PyObject *self, void *Py_UNUSED(ignored))
{}

static int
func_set_name(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{}

static PyObject *
func_get_qualname(PyObject *self, void *Py_UNUSED(ignored))
{}

static int
func_set_qualname(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{}

static PyObject *
func_get_defaults(PyObject *self, void *Py_UNUSED(ignored))
{}

static int
func_set_defaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{}

static PyObject *
func_get_kwdefaults(PyObject *self, void *Py_UNUSED(ignored))
{}

static int
func_set_kwdefaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{}

static PyObject *
func_get_annotate(PyObject *self, void *Py_UNUSED(ignored))
{}

static int
func_set_annotate(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{}

static PyObject *
func_get_annotations(PyObject *self, void *Py_UNUSED(ignored))
{}

static int
func_set_annotations(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{}

static PyObject *
func_get_type_params(PyObject *self, void *Py_UNUSED(ignored))
{}

static int
func_set_type_params(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{}

PyObject *
_Py_set_function_type_params(PyThreadState *Py_UNUSED(ignored), PyObject *func,
                             PyObject *type_params)
{}

static PyGetSetDef func_getsetlist[] =;

/*[clinic input]
class function "PyFunctionObject *" "&PyFunction_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=70af9c90aa2e71b0]*/

#include "clinic/funcobject.c.h"

/* function.__new__() maintains the following invariants for closures.
   The closure must correspond to the free variables of the code object.

   if len(code.co_freevars) == 0:
       closure = NULL
   else:
       len(closure) == len(code.co_freevars)
   for every elt in closure, type(elt) == cell
*/

/*[clinic input]
@classmethod
function.__new__ as func_new
    code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
        a code object
    globals: object(subclass_of="&PyDict_Type")
        the globals dictionary
    name: object = None
        a string that overrides the name from the code object
    argdefs as defaults: object = None
        a tuple that specifies the default argument values
    closure: object = None
        a tuple that supplies the bindings for free variables
    kwdefaults: object = None
        a dictionary that specifies the default keyword argument values

Create a function object.
[clinic start generated code]*/

static PyObject *
func_new_impl(PyTypeObject *type, PyCodeObject *code, PyObject *globals,
              PyObject *name, PyObject *defaults, PyObject *closure,
              PyObject *kwdefaults)
/*[clinic end generated code: output=de72f4c22ac57144 input=20c9c9f04ad2d3f2]*/
{}

static int
func_clear(PyObject *self)
{}

static void
func_dealloc(PyObject *self)
{}

static PyObject*
func_repr(PyObject *self)
{}

static int
func_traverse(PyObject *self, visitproc visit, void *arg)
{}

/* Bind a function to an object */
static PyObject *
func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
{}

PyTypeObject PyFunction_Type =;


static int
functools_copy_attr(PyObject *wrapper, PyObject *wrapped, PyObject *name)
{}

// Similar to functools.wraps(wrapper, wrapped)
static int
functools_wraps(PyObject *wrapper, PyObject *wrapped)
{}

// Used for wrapping __annotations__ and __annotate__ on classmethod
// and staticmethod objects.
static PyObject *
descriptor_get_wrapped_attribute(PyObject *wrapped, PyObject *dict, PyObject *name)
{}

static int
descriptor_set_wrapped_attribute(PyObject *dict, PyObject *name, PyObject *value,
                                 char *type_name)
{}


/* Class method object */

/* A class method receives the class as implicit first argument,
   just like an instance method receives the instance.
   To declare a class method, use this idiom:

     class C:
         @classmethod
         def f(cls, arg1, arg2, argN):
             ...

   It can be called either on the class (e.g. C.f()) or on an instance
   (e.g. C().f()); the instance is ignored except for its class.
   If a class method is called for a derived class, the derived class
   object is passed as the implied first argument.

   Class methods are different than C++ or Java static methods.
   If you want those, see static methods below.
*/

classmethod;

#define _PyClassMethod_CAST(cm)

static void
cm_dealloc(PyObject *self)
{}

static int
cm_traverse(PyObject *self, visitproc visit, void *arg)
{}

static int
cm_clear(PyObject *self)
{}


static PyObject *
cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
{}

static int
cm_init(PyObject *self, PyObject *args, PyObject *kwds)
{}

static PyMemberDef cm_memberlist[] =;

static PyObject *
cm_get___isabstractmethod__(PyObject *self, void *closure)
{}

static PyObject *
cm_get___annotations__(PyObject *self, void *closure)
{}

static int
cm_set___annotations__(PyObject *self, PyObject *value, void *closure)
{}

static PyObject *
cm_get___annotate__(PyObject *self, void *closure)
{}

static int
cm_set___annotate__(PyObject *self, PyObject *value, void *closure)
{}


static PyGetSetDef cm_getsetlist[] =;

static PyObject*
cm_repr(PyObject *self)
{}

PyDoc_STRVAR(classmethod_doc,
"classmethod(function, /)\n\
--\n\
\n\
Convert a function to be a class method.\n\
\n\
A class method receives the class as implicit first argument,\n\
just like an instance method receives the instance.\n\
To declare a class method, use this idiom:\n\
\n\
  class C:\n\
      @classmethod\n\
      def f(cls, arg1, arg2, argN):\n\
          ...\n\
\n\
It can be called either on the class (e.g. C.f()) or on an instance\n\
(e.g. C().f()).  The instance is ignored except for its class.\n\
If a class method is called for a derived class, the derived class\n\
object is passed as the implied first argument.\n\
\n\
Class methods are different than C++ or Java static methods.\n\
If you want those, see the staticmethod builtin.");

PyTypeObject PyClassMethod_Type =;

PyObject *
PyClassMethod_New(PyObject *callable)
{}


/* Static method object */

/* A static method does not receive an implicit first argument.
   To declare a static method, use this idiom:

     class C:
         @staticmethod
         def f(arg1, arg2, argN):
             ...

   It can be called either on the class (e.g. C.f()) or on an instance
   (e.g. C().f()). Both the class and the instance are ignored, and
   neither is passed implicitly as the first argument to the method.

   Static methods in Python are similar to those found in Java or C++.
   For a more advanced concept, see class methods above.
*/

staticmethod;

#define _PyStaticMethod_CAST(cm)

static void
sm_dealloc(PyObject *self)
{}

static int
sm_traverse(PyObject *self, visitproc visit, void *arg)
{}

static int
sm_clear(PyObject *self)
{}

static PyObject *
sm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
{}

static int
sm_init(PyObject *self, PyObject *args, PyObject *kwds)
{}

static PyObject*
sm_call(PyObject *callable, PyObject *args, PyObject *kwargs)
{}

static PyMemberDef sm_memberlist[] =;

static PyObject *
sm_get___isabstractmethod__(PyObject *self, void *closure)
{}

static PyObject *
sm_get___annotations__(PyObject *self, void *closure)
{}

static int
sm_set___annotations__(PyObject *self, PyObject *value, void *closure)
{}

static PyObject *
sm_get___annotate__(PyObject *self, void *closure)
{}

static int
sm_set___annotate__(PyObject *self, PyObject *value, void *closure)
{}

static PyGetSetDef sm_getsetlist[] =;

static PyObject*
sm_repr(PyObject *self)
{}

PyDoc_STRVAR(staticmethod_doc,
"staticmethod(function, /)\n\
--\n\
\n\
Convert a function to be a static method.\n\
\n\
A static method does not receive an implicit first argument.\n\
To declare a static method, use this idiom:\n\
\n\
     class C:\n\
         @staticmethod\n\
         def f(arg1, arg2, argN):\n\
             ...\n\
\n\
It can be called either on the class (e.g. C.f()) or on an instance\n\
(e.g. C().f()). Both the class and the instance are ignored, and\n\
neither is passed implicitly as the first argument to the method.\n\
\n\
Static methods in Python are similar to those found in Java or C++.\n\
For a more advanced concept, see the classmethod builtin.");

PyTypeObject PyStaticMethod_Type =;

PyObject *
PyStaticMethod_New(PyObject *callable)
{}