1.. highlight:: c 2 3.. _moduleobjects: 4 5Module Objects 6-------------- 7 8.. index:: object: module 9 10 11.. c:var:: PyTypeObject PyModule_Type 12 13 .. index:: single: ModuleType (in module types) 14 15 This instance of :c:type:`PyTypeObject` represents the Python module type. This 16 is exposed to Python programs as ``types.ModuleType``. 17 18 19.. c:function:: int PyModule_Check(PyObject *p) 20 21 Return true if *p* is a module object, or a subtype of a module object. 22 This function always succeeds. 23 24 25.. c:function:: int PyModule_CheckExact(PyObject *p) 26 27 Return true if *p* is a module object, but not a subtype of 28 :c:data:`PyModule_Type`. This function always succeeds. 29 30 31.. c:function:: PyObject* PyModule_NewObject(PyObject *name) 32 33 .. index:: 34 single: __name__ (module attribute) 35 single: __doc__ (module attribute) 36 single: __file__ (module attribute) 37 single: __package__ (module attribute) 38 single: __loader__ (module attribute) 39 40 Return a new module object with the :attr:`__name__` attribute set to *name*. 41 The module's :attr:`__name__`, :attr:`__doc__`, :attr:`__package__`, and 42 :attr:`__loader__` attributes are filled in (all but :attr:`__name__` are set 43 to ``None``); the caller is responsible for providing a :attr:`__file__` 44 attribute. 45 46 .. versionadded:: 3.3 47 48 .. versionchanged:: 3.4 49 :attr:`__package__` and :attr:`__loader__` are set to ``None``. 50 51 52.. c:function:: PyObject* PyModule_New(const char *name) 53 54 Similar to :c:func:`PyModule_NewObject`, but the name is a UTF-8 encoded 55 string instead of a Unicode object. 56 57 58.. c:function:: PyObject* PyModule_GetDict(PyObject *module) 59 60 .. index:: single: __dict__ (module attribute) 61 62 Return the dictionary object that implements *module*'s namespace; this object 63 is the same as the :attr:`~object.__dict__` attribute of the module object. 64 If *module* is not a module object (or a subtype of a module object), 65 :exc:`SystemError` is raised and ``NULL`` is returned. 66 67 It is recommended extensions use other :c:func:`PyModule_\*` and 68 :c:func:`PyObject_\*` functions rather than directly manipulate a module's 69 :attr:`~object.__dict__`. 70 71 72.. c:function:: PyObject* PyModule_GetNameObject(PyObject *module) 73 74 .. index:: 75 single: __name__ (module attribute) 76 single: SystemError (built-in exception) 77 78 Return *module*'s :attr:`__name__` value. If the module does not provide one, 79 or if it is not a string, :exc:`SystemError` is raised and ``NULL`` is returned. 80 81 .. versionadded:: 3.3 82 83 84.. c:function:: const char* PyModule_GetName(PyObject *module) 85 86 Similar to :c:func:`PyModule_GetNameObject` but return the name encoded to 87 ``'utf-8'``. 88 89.. c:function:: void* PyModule_GetState(PyObject *module) 90 91 Return the "state" of the module, that is, a pointer to the block of memory 92 allocated at module creation time, or ``NULL``. See 93 :c:member:`PyModuleDef.m_size`. 94 95 96.. c:function:: PyModuleDef* PyModule_GetDef(PyObject *module) 97 98 Return a pointer to the :c:type:`PyModuleDef` struct from which the module was 99 created, or ``NULL`` if the module wasn't created from a definition. 100 101 102.. c:function:: PyObject* PyModule_GetFilenameObject(PyObject *module) 103 104 .. index:: 105 single: __file__ (module attribute) 106 single: SystemError (built-in exception) 107 108 Return the name of the file from which *module* was loaded using *module*'s 109 :attr:`__file__` attribute. If this is not defined, or if it is not a 110 unicode string, raise :exc:`SystemError` and return ``NULL``; otherwise return 111 a reference to a Unicode object. 112 113 .. versionadded:: 3.2 114 115 116.. c:function:: const char* PyModule_GetFilename(PyObject *module) 117 118 Similar to :c:func:`PyModule_GetFilenameObject` but return the filename 119 encoded to 'utf-8'. 120 121 .. deprecated:: 3.2 122 :c:func:`PyModule_GetFilename` raises :c:type:`UnicodeEncodeError` on 123 unencodable filenames, use :c:func:`PyModule_GetFilenameObject` instead. 124 125 126.. _initializing-modules: 127 128Initializing C modules 129^^^^^^^^^^^^^^^^^^^^^^ 130 131Modules objects are usually created from extension modules (shared libraries 132which export an initialization function), or compiled-in modules 133(where the initialization function is added using :c:func:`PyImport_AppendInittab`). 134See :ref:`building` or :ref:`extending-with-embedding` for details. 135 136The initialization function can either pass a module definition instance 137to :c:func:`PyModule_Create`, and return the resulting module object, 138or request "multi-phase initialization" by returning the definition struct itself. 139 140.. c:type:: PyModuleDef 141 142 The module definition struct, which holds all information needed to create 143 a module object. There is usually only one statically initialized variable 144 of this type for each module. 145 146 .. c:member:: PyModuleDef_Base m_base 147 148 Always initialize this member to :const:`PyModuleDef_HEAD_INIT`. 149 150 .. c:member:: const char *m_name 151 152 Name for the new module. 153 154 .. c:member:: const char *m_doc 155 156 Docstring for the module; usually a docstring variable created with 157 :c:macro:`PyDoc_STRVAR` is used. 158 159 .. c:member:: Py_ssize_t m_size 160 161 Module state may be kept in a per-module memory area that can be 162 retrieved with :c:func:`PyModule_GetState`, rather than in static globals. 163 This makes modules safe for use in multiple sub-interpreters. 164 165 This memory area is allocated based on *m_size* on module creation, 166 and freed when the module object is deallocated, after the 167 :c:member:`m_free` function has been called, if present. 168 169 Setting ``m_size`` to ``-1`` means that the module does not support 170 sub-interpreters, because it has global state. 171 172 Setting it to a non-negative value means that the module can be 173 re-initialized and specifies the additional amount of memory it requires 174 for its state. Non-negative ``m_size`` is required for multi-phase 175 initialization. 176 177 See :PEP:`3121` for more details. 178 179 .. c:member:: PyMethodDef* m_methods 180 181 A pointer to a table of module-level functions, described by 182 :c:type:`PyMethodDef` values. Can be ``NULL`` if no functions are present. 183 184 .. c:member:: PyModuleDef_Slot* m_slots 185 186 An array of slot definitions for multi-phase initialization, terminated by 187 a ``{0, NULL}`` entry. 188 When using single-phase initialization, *m_slots* must be ``NULL``. 189 190 .. versionchanged:: 3.5 191 192 Prior to version 3.5, this member was always set to ``NULL``, 193 and was defined as: 194 195 .. c:member:: inquiry m_reload 196 197 .. c:member:: traverseproc m_traverse 198 199 A traversal function to call during GC traversal of the module object, or 200 ``NULL`` if not needed. 201 202 This function is not called if the module state was requested but is not 203 allocated yet. This is the case immediately after the module is created 204 and before the module is executed (:c:data:`Py_mod_exec` function). More 205 precisely, this function is not called if :c:member:`m_size` is greater 206 than 0 and the module state (as returned by :c:func:`PyModule_GetState`) 207 is ``NULL``. 208 209 .. versionchanged:: 3.9 210 No longer called before the module state is allocated. 211 212 .. c:member:: inquiry m_clear 213 214 A clear function to call during GC clearing of the module object, or 215 ``NULL`` if not needed. 216 217 This function is not called if the module state was requested but is not 218 allocated yet. This is the case immediately after the module is created 219 and before the module is executed (:c:data:`Py_mod_exec` function). More 220 precisely, this function is not called if :c:member:`m_size` is greater 221 than 0 and the module state (as returned by :c:func:`PyModule_GetState`) 222 is ``NULL``. 223 224 Like :c:member:`PyTypeObject.tp_clear`, this function is not *always* 225 called before a module is deallocated. For example, when reference 226 counting is enough to determine that an object is no longer used, 227 the cyclic garbage collector is not involved and 228 :c:member:`~PyModuleDef.m_free` is called directly. 229 230 .. versionchanged:: 3.9 231 No longer called before the module state is allocated. 232 233 .. c:member:: freefunc m_free 234 235 A function to call during deallocation of the module object, or ``NULL`` 236 if not needed. 237 238 This function is not called if the module state was requested but is not 239 allocated yet. This is the case immediately after the module is created 240 and before the module is executed (:c:data:`Py_mod_exec` function). More 241 precisely, this function is not called if :c:member:`m_size` is greater 242 than 0 and the module state (as returned by :c:func:`PyModule_GetState`) 243 is ``NULL``. 244 245 .. versionchanged:: 3.9 246 No longer called before the module state is allocated. 247 248Single-phase initialization 249........................... 250 251The module initialization function may create and return the module object 252directly. This is referred to as "single-phase initialization", and uses one 253of the following two module creation functions: 254 255.. c:function:: PyObject* PyModule_Create(PyModuleDef *def) 256 257 Create a new module object, given the definition in *def*. This behaves 258 like :c:func:`PyModule_Create2` with *module_api_version* set to 259 :const:`PYTHON_API_VERSION`. 260 261 262.. c:function:: PyObject* PyModule_Create2(PyModuleDef *def, int module_api_version) 263 264 Create a new module object, given the definition in *def*, assuming the 265 API version *module_api_version*. If that version does not match the version 266 of the running interpreter, a :exc:`RuntimeWarning` is emitted. 267 268 .. note:: 269 270 Most uses of this function should be using :c:func:`PyModule_Create` 271 instead; only use this if you are sure you need it. 272 273Before it is returned from in the initialization function, the resulting module 274object is typically populated using functions like :c:func:`PyModule_AddObjectRef`. 275 276.. _multi-phase-initialization: 277 278Multi-phase initialization 279.......................... 280 281An alternate way to specify extensions is to request "multi-phase initialization". 282Extension modules created this way behave more like Python modules: the 283initialization is split between the *creation phase*, when the module object 284is created, and the *execution phase*, when it is populated. 285The distinction is similar to the :py:meth:`__new__` and :py:meth:`__init__` methods 286of classes. 287 288Unlike modules created using single-phase initialization, these modules are not 289singletons: if the *sys.modules* entry is removed and the module is re-imported, 290a new module object is created, and the old module is subject to normal garbage 291collection -- as with Python modules. 292By default, multiple modules created from the same definition should be 293independent: changes to one should not affect the others. 294This means that all state should be specific to the module object (using e.g. 295using :c:func:`PyModule_GetState`), or its contents (such as the module's 296:attr:`__dict__` or individual classes created with :c:func:`PyType_FromSpec`). 297 298All modules created using multi-phase initialization are expected to support 299:ref:`sub-interpreters <sub-interpreter-support>`. Making sure multiple modules 300are independent is typically enough to achieve this. 301 302To request multi-phase initialization, the initialization function 303(PyInit_modulename) returns a :c:type:`PyModuleDef` instance with non-empty 304:c:member:`~PyModuleDef.m_slots`. Before it is returned, the ``PyModuleDef`` 305instance must be initialized with the following function: 306 307.. c:function:: PyObject* PyModuleDef_Init(PyModuleDef *def) 308 309 Ensures a module definition is a properly initialized Python object that 310 correctly reports its type and reference count. 311 312 Returns *def* cast to ``PyObject*``, or ``NULL`` if an error occurred. 313 314 .. versionadded:: 3.5 315 316The *m_slots* member of the module definition must point to an array of 317``PyModuleDef_Slot`` structures: 318 319.. c:type:: PyModuleDef_Slot 320 321 .. c:member:: int slot 322 323 A slot ID, chosen from the available values explained below. 324 325 .. c:member:: void* value 326 327 Value of the slot, whose meaning depends on the slot ID. 328 329 .. versionadded:: 3.5 330 331The *m_slots* array must be terminated by a slot with id 0. 332 333The available slot types are: 334 335.. c:macro:: Py_mod_create 336 337 Specifies a function that is called to create the module object itself. 338 The *value* pointer of this slot must point to a function of the signature: 339 340 .. c:function:: PyObject* create_module(PyObject *spec, PyModuleDef *def) 341 342 The function receives a :py:class:`~importlib.machinery.ModuleSpec` 343 instance, as defined in :PEP:`451`, and the module definition. 344 It should return a new module object, or set an error 345 and return ``NULL``. 346 347 This function should be kept minimal. In particular, it should not 348 call arbitrary Python code, as trying to import the same module again may 349 result in an infinite loop. 350 351 Multiple ``Py_mod_create`` slots may not be specified in one module 352 definition. 353 354 If ``Py_mod_create`` is not specified, the import machinery will create 355 a normal module object using :c:func:`PyModule_New`. The name is taken from 356 *spec*, not the definition, to allow extension modules to dynamically adjust 357 to their place in the module hierarchy and be imported under different 358 names through symlinks, all while sharing a single module definition. 359 360 There is no requirement for the returned object to be an instance of 361 :c:type:`PyModule_Type`. Any type can be used, as long as it supports 362 setting and getting import-related attributes. 363 However, only ``PyModule_Type`` instances may be returned if the 364 ``PyModuleDef`` has non-``NULL`` ``m_traverse``, ``m_clear``, 365 ``m_free``; non-zero ``m_size``; or slots other than ``Py_mod_create``. 366 367.. c:macro:: Py_mod_exec 368 369 Specifies a function that is called to *execute* the module. 370 This is equivalent to executing the code of a Python module: typically, 371 this function adds classes and constants to the module. 372 The signature of the function is: 373 374 .. c:function:: int exec_module(PyObject* module) 375 376 If multiple ``Py_mod_exec`` slots are specified, they are processed in the 377 order they appear in the *m_slots* array. 378 379See :PEP:`489` for more details on multi-phase initialization. 380 381Low-level module creation functions 382................................... 383 384The following functions are called under the hood when using multi-phase 385initialization. They can be used directly, for example when creating module 386objects dynamically. Note that both ``PyModule_FromDefAndSpec`` and 387``PyModule_ExecDef`` must be called to fully initialize a module. 388 389.. c:function:: PyObject * PyModule_FromDefAndSpec(PyModuleDef *def, PyObject *spec) 390 391 Create a new module object, given the definition in *module* and the 392 ModuleSpec *spec*. This behaves like :c:func:`PyModule_FromDefAndSpec2` 393 with *module_api_version* set to :const:`PYTHON_API_VERSION`. 394 395 .. versionadded:: 3.5 396 397.. c:function:: PyObject * PyModule_FromDefAndSpec2(PyModuleDef *def, PyObject *spec, int module_api_version) 398 399 Create a new module object, given the definition in *module* and the 400 ModuleSpec *spec*, assuming the API version *module_api_version*. 401 If that version does not match the version of the running interpreter, 402 a :exc:`RuntimeWarning` is emitted. 403 404 .. note:: 405 406 Most uses of this function should be using :c:func:`PyModule_FromDefAndSpec` 407 instead; only use this if you are sure you need it. 408 409 .. versionadded:: 3.5 410 411.. c:function:: int PyModule_ExecDef(PyObject *module, PyModuleDef *def) 412 413 Process any execution slots (:c:data:`Py_mod_exec`) given in *def*. 414 415 .. versionadded:: 3.5 416 417.. c:function:: int PyModule_SetDocString(PyObject *module, const char *docstring) 418 419 Set the docstring for *module* to *docstring*. 420 This function is called automatically when creating a module from 421 ``PyModuleDef``, using either ``PyModule_Create`` or 422 ``PyModule_FromDefAndSpec``. 423 424 .. versionadded:: 3.5 425 426.. c:function:: int PyModule_AddFunctions(PyObject *module, PyMethodDef *functions) 427 428 Add the functions from the ``NULL`` terminated *functions* array to *module*. 429 Refer to the :c:type:`PyMethodDef` documentation for details on individual 430 entries (due to the lack of a shared module namespace, module level 431 "functions" implemented in C typically receive the module as their first 432 parameter, making them similar to instance methods on Python classes). 433 This function is called automatically when creating a module from 434 ``PyModuleDef``, using either ``PyModule_Create`` or 435 ``PyModule_FromDefAndSpec``. 436 437 .. versionadded:: 3.5 438 439Support functions 440................. 441 442The module initialization function (if using single phase initialization) or 443a function called from a module execution slot (if using multi-phase 444initialization), can use the following functions to help initialize the module 445state: 446 447.. c:function:: int PyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value) 448 449 Add an object to *module* as *name*. This is a convenience function which 450 can be used from the module's initialization function. 451 452 On success, return ``0``. On error, raise an exception and return ``-1``. 453 454 Return ``NULL`` if *value* is ``NULL``. It must be called with an exception 455 raised in this case. 456 457 Example usage:: 458 459 static int 460 add_spam(PyObject *module, int value) 461 { 462 PyObject *obj = PyLong_FromLong(value); 463 if (obj == NULL) { 464 return -1; 465 } 466 int res = PyModule_AddObjectRef(module, "spam", obj); 467 Py_DECREF(obj); 468 return res; 469 } 470 471 The example can also be written without checking explicitly if *obj* is 472 ``NULL``:: 473 474 static int 475 add_spam(PyObject *module, int value) 476 { 477 PyObject *obj = PyLong_FromLong(value); 478 int res = PyModule_AddObjectRef(module, "spam", obj); 479 Py_XDECREF(obj); 480 return res; 481 } 482 483 Note that ``Py_XDECREF()`` should be used instead of ``Py_DECREF()`` in 484 this case, since *obj* can be ``NULL``. 485 486 .. versionadded:: 3.10 487 488 489.. c:function:: int PyModule_AddObject(PyObject *module, const char *name, PyObject *value) 490 491 Similar to :c:func:`PyModule_AddObjectRef`, but steals a reference to 492 *value* on success (if it returns ``0``). 493 494 The new :c:func:`PyModule_AddObjectRef` function is recommended, since it is 495 easy to introduce reference leaks by misusing the 496 :c:func:`PyModule_AddObject` function. 497 498 .. note:: 499 500 Unlike other functions that steal references, ``PyModule_AddObject()`` 501 only decrements the reference count of *value* **on success**. 502 503 This means that its return value must be checked, and calling code must 504 :c:func:`Py_DECREF` *value* manually on error. 505 506 Example usage:: 507 508 static int 509 add_spam(PyObject *module, int value) 510 { 511 PyObject *obj = PyLong_FromLong(value); 512 if (obj == NULL) { 513 return -1; 514 } 515 if (PyModule_AddObject(module, "spam", obj) < 0) { 516 Py_DECREF(obj); 517 return -1; 518 } 519 // PyModule_AddObject() stole a reference to obj: 520 // Py_DECREF(obj) is not needed here 521 return 0; 522 } 523 524 The example can also be written without checking explicitly if *obj* is 525 ``NULL``:: 526 527 static int 528 add_spam(PyObject *module, int value) 529 { 530 PyObject *obj = PyLong_FromLong(value); 531 if (PyModule_AddObject(module, "spam", obj) < 0) { 532 Py_XDECREF(obj); 533 return -1; 534 } 535 // PyModule_AddObject() stole a reference to obj: 536 // Py_DECREF(obj) is not needed here 537 return 0; 538 } 539 540 Note that ``Py_XDECREF()`` should be used instead of ``Py_DECREF()`` in 541 this case, since *obj* can be ``NULL``. 542 543 544.. c:function:: int PyModule_AddIntConstant(PyObject *module, const char *name, long value) 545 546 Add an integer constant to *module* as *name*. This convenience function can be 547 used from the module's initialization function. Return ``-1`` on error, ``0`` on 548 success. 549 550 551.. c:function:: int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value) 552 553 Add a string constant to *module* as *name*. This convenience function can be 554 used from the module's initialization function. The string *value* must be 555 ``NULL``-terminated. Return ``-1`` on error, ``0`` on success. 556 557 558.. c:function:: int PyModule_AddIntMacro(PyObject *module, macro) 559 560 Add an int constant to *module*. The name and the value are taken from 561 *macro*. For example ``PyModule_AddIntMacro(module, AF_INET)`` adds the int 562 constant *AF_INET* with the value of *AF_INET* to *module*. 563 Return ``-1`` on error, ``0`` on success. 564 565 566.. c:function:: int PyModule_AddStringMacro(PyObject *module, macro) 567 568 Add a string constant to *module*. 569 570.. c:function:: int PyModule_AddType(PyObject *module, PyTypeObject *type) 571 572 Add a type object to *module*. 573 The type object is finalized by calling internally :c:func:`PyType_Ready`. 574 The name of the type object is taken from the last component of 575 :c:member:`~PyTypeObject.tp_name` after dot. 576 Return ``-1`` on error, ``0`` on success. 577 578 .. versionadded:: 3.9 579 580 581Module lookup 582^^^^^^^^^^^^^ 583 584Single-phase initialization creates singleton modules that can be looked up 585in the context of the current interpreter. This allows the module object to be 586retrieved later with only a reference to the module definition. 587 588These functions will not work on modules created using multi-phase initialization, 589since multiple such modules can be created from a single definition. 590 591.. c:function:: PyObject* PyState_FindModule(PyModuleDef *def) 592 593 Returns the module object that was created from *def* for the current interpreter. 594 This method requires that the module object has been attached to the interpreter state with 595 :c:func:`PyState_AddModule` beforehand. In case the corresponding module object is not 596 found or has not been attached to the interpreter state yet, it returns ``NULL``. 597 598.. c:function:: int PyState_AddModule(PyObject *module, PyModuleDef *def) 599 600 Attaches the module object passed to the function to the interpreter state. This allows 601 the module object to be accessible via :c:func:`PyState_FindModule`. 602 603 Only effective on modules created using single-phase initialization. 604 605 Python calls ``PyState_AddModule`` automatically after importing a module, 606 so it is unnecessary (but harmless) to call it from module initialization 607 code. An explicit call is needed only if the module's own init code 608 subsequently calls ``PyState_FindModule``. 609 The function is mainly intended for implementing alternative import 610 mechanisms (either by calling it directly, or by referring to its 611 implementation for details of the required state updates). 612 613 The caller must hold the GIL. 614 615 Return 0 on success or -1 on failure. 616 617 .. versionadded:: 3.3 618 619.. c:function:: int PyState_RemoveModule(PyModuleDef *def) 620 621 Removes the module object created from *def* from the interpreter state. 622 Return 0 on success or -1 on failure. 623 624 The caller must hold the GIL. 625 626 .. versionadded:: 3.3 627