모듈 객체¶
-
PyTypeObject PyModule_Type¶
- Part of the 안정 ABI.
이
PyTypeObject
인스턴스는 파이썬 모듈 형을 나타냅니다. 이것은types.ModuleType
으로 파이썬 프로그램에 노출됩니다.
-
int PyModule_CheckExact(PyObject *p)¶
p가 모듈 객체이지만,
PyModule_Type
의 서브 형이 아니면 참을 반환합니다. 이 함수는 항상 성공합니다.
-
PyObject *PyModule_NewObject(PyObject *name)¶
- 반환값: 새 참조. Part of the 안정 ABI 버전 3.7 이후로.
module.__name__
이 name으로 설정된 새 모듈 객체를 반환합니다. 모듈의__name__
,__doc__
,__package__
및__loader__
어트리뷰트가 채워집니다 (__name__
을 제외하고 모두None
으로 설정됩니다).__file__
어트리뷰트를 설정하는 것은 호출자의 책임입니다.Return
NULL
with an exception set on error.Added in version 3.3.
버전 3.4에서 변경:
__package__
와__loader__
가 이제None
으로 설정됩니다.
-
PyObject *PyModule_New(const char *name)¶
- 반환값: 새 참조. Part of the 안정 ABI.
PyModule_NewObject()
와 비슷하지만, name이 유니코드 객체 대신 UTF-8로 인코딩된 문자열입니다.
-
PyObject *PyModule_GetDict(PyObject *module)¶
- 반환값: 빌린 참조. Part of the 안정 ABI.
module의 이름 공간을 구현하는 딕셔너리 객체를 반환합니다; 이 객체는 모듈 객체의
__dict__
어트리뷰트와 같습니다. module이 모듈 객체(또는 모듈 객체의 서브 형)가 아니면,SystemError
가 발생하고NULL
이 반환됩니다.확장은 모듈의
__dict__
를 직접 조작하지 말고 다른PyModule_*
과PyObject_*
함수를 사용하는 것이 좋습니다.
-
PyObject *PyModule_GetNameObject(PyObject *module)¶
- 반환값: 새 참조. Part of the 안정 ABI 버전 3.7 이후로.
module의
__name__
값을 반환합니다. 모듈이 제공하지 않거나, 문자열이 아니면,SystemError
가 발생하고NULL
이 반환됩니다.Added in version 3.3.
-
const char *PyModule_GetName(PyObject *module)¶
- Part of the 안정 ABI.
PyModule_GetNameObject()
와 비슷하지만'utf-8'
로 인코딩된 이름을 반환합니다.
-
void *PyModule_GetState(PyObject *module)¶
- Part of the 안정 ABI.
모듈의 “상태”, 즉 모듈 생성 시 할당된 메모리 블록을 가리키는 포인터나
NULL
을 반환합니다.PyModuleDef.m_size
를 참조하십시오.
-
PyModuleDef *PyModule_GetDef(PyObject *module)¶
- Part of the 안정 ABI.
모듈이 만들어진
PyModuleDef
구조체에 대한 포인터나 모듈이 정의에서 만들어지지 않았으면NULL
을 반환합니다.
-
PyObject *PyModule_GetFilenameObject(PyObject *module)¶
- 반환값: 새 참조. Part of the 안정 ABI.
module의
__file__
어트리뷰트를 사용하여 module이 로드된 파일 이름을 반환합니다. 정의되지 않았거나 문자열이 아니면,SystemError
를 발생시키고NULL
을 반환합니다; 그렇지 않으면 유니코드 객체에 대한 참조를 반환합니다.Added in version 3.2.
-
const char *PyModule_GetFilename(PyObject *module)¶
- Part of the 안정 ABI.
PyModule_GetFilenameObject()
와 비슷하지만 ‘utf-8’로 인코딩된 파일명을 반환합니다.버전 3.2부터 폐지됨:
PyModule_GetFilename()
은 인코딩할 수 없는 파일명에 대해UnicodeEncodeError
를 발생시킵니다, 대신PyModule_GetFilenameObject()
를 사용하십시오.
Module definitions¶
The functions in the previous section work on any module object, including modules imported from Python code.
Modules defined using the C API typically use a module definition,
PyModuleDef
– a statically allocated, constant “description” of
how a module should be created.
The definition is usually used to define an extension’s “main” module object (see Defining extension modules for details). It is also used to create extension modules dynamically.
Unlike PyModule_New()
, the definition allows management of
module state – a piece of memory that is allocated and cleared together
with the module object.
Unlike the module’s Python attributes, Python code cannot replace or delete
data stored in module state.
-
type PyModuleDef¶
- Part of the 안정 ABI (including all members).
The module definition struct, which holds all information needed to create a module object. This structure must be statically allocated (or be otherwise guaranteed to be valid while any modules created from it exist). Usually, there is only one variable of this type for each extension module.
-
PyModuleDef_Base m_base¶
이 멤버를 항상
PyModuleDef_HEAD_INIT
로 초기화하십시오.
-
const char *m_name¶
새 모듈의 이름.
-
const char *m_doc¶
모듈의 독스트링; 일반적으로
PyDoc_STRVAR
로 만들어진 독스트링 변수가 사용됩니다.
-
Py_ssize_t m_size¶
모듈 상태는 정적 전역이 아닌
PyModule_GetState()
로 조회할 수 있는 모듈별 메모리 영역에 유지될 수 있습니다. 이것은 여러 서브 인터프리터에서 모듈을 사용하는 것을 안전하게 만듭니다.이 메모리 영역은 모듈 생성 시 m_size를 기준으로 할당되며, 모듈 객체가 할당 해제될 때 (있다면
m_free
함수가 호출된 후에) 해제됩니다.Setting it to a non-negative value means that the module can be re-initialized and specifies the additional amount of memory it requires for its state.
Setting
m_size
to-1
means that the module does not support sub-interpreters, because it has global state. Negativem_size
is only allowed when using legacy single-phase initialization or when creating modules dynamically.자세한 내용은 PEP 3121을 참조하십시오.
-
PyMethodDef *m_methods¶
PyMethodDef
값으로 기술되는 모듈 수준 함수 테이블에 대한 포인터. 함수가 없으면NULL
일 수 있습니다.
-
PyModuleDef_Slot *m_slots¶
An array of slot definitions for multi-phase initialization, terminated by a
{0, NULL}
entry. When using legacy single-phase initialization, m_slots must beNULL
.
-
traverseproc m_traverse¶
모듈 객체의 GC 탐색 중 호출할 탐색 함수나, 필요하지 않으면
NULL
.모듈 상태가 요청되었지만, 아직 할당되지 않았으면 이 함수가 호출되지 않습니다. 이것은 모듈이 만들이진 직후, 모듈이 실행되기 직전의 경우입니다 (
Py_mod_exec
함수). 더 정확하게는,m_size
가 0보다 크고 모듈 상태(PyModule_GetState()
가 반환하는)가NULL
이면 이 함수가 호출되지 않습니다.버전 3.9에서 변경: 모듈 상태가 할당되기 전에 더는 호출되지 않습니다.
-
inquiry m_clear¶
모듈 객체의 GC 정리 중에 호출할 정리(clear) 함수나, 필요하지 않으면
NULL
.모듈 상태가 요청되었지만, 아직 할당되지 않았으면 이 함수가 호출되지 않습니다. 이것은 모듈이 만들이진 직후, 모듈이 실행되기 직전의 경우입니다 (
Py_mod_exec
함수). 더 정확하게는,m_size
가 0보다 크고 모듈 상태(PyModule_GetState()
가 반환하는)가NULL
이면 이 함수가 호출되지 않습니다.Like
PyTypeObject.tp_clear
, this function is not always called before a module is deallocated. For example, when reference counting is enough to determine that an object is no longer used, the cyclic garbage collector is not involved andm_free
is called directly.버전 3.9에서 변경: 모듈 상태가 할당되기 전에 더는 호출되지 않습니다.
-
freefunc m_free¶
모듈 객체 할당 해제 중에 호출할 함수나, 필요하지 않으면
NULL
.모듈 상태가 요청되었지만, 아직 할당되지 않았으면 이 함수가 호출되지 않습니다. 이것은 모듈이 만들이진 직후, 모듈이 실행되기 직전의 경우입니다 (
Py_mod_exec
함수). 더 정확하게는,m_size
가 0보다 크고 모듈 상태(PyModule_GetState()
가 반환하는)가NULL
이면 이 함수가 호출되지 않습니다.버전 3.9에서 변경: 모듈 상태가 할당되기 전에 더는 호출되지 않습니다.
-
PyModuleDef_Base m_base¶
Module slots¶
-
type PyModuleDef_Slot¶
-
int slot¶
아래 설명된 사용 가능한 값 중에서 선택된, 슬롯 ID.
-
void *value¶
슬롯 ID에 따라 그 의미가 달라지는, 슬롯의 값.
Added in version 3.5.
-
int slot¶
사용 가능한 슬롯 형은 다음과 같습니다:
-
Py_mod_create¶
모듈 객체 자체를 만들기 위해 호출되는 함수를 지정합니다. 이 슬롯의 value 포인터는 다음과 같은 서명을 갖는 함수를 가리켜야 합니다:
-
PyObject *create_module(PyObject *spec, PyModuleDef *def)¶
이 함수는 PEP 451에 정의된 대로,
ModuleSpec
인스턴스와 모듈 정의를 받습니다. 새 모듈 객체를 반환하거나, 에러를 설정하고NULL
을 반환해야 합니다.이 함수는 최소한으로 유지해야 합니다. 특히 같은 모듈을 다시 임포트 하려고 시도하면 무한 루프가 발생할 수 있어서, 임의의 파이썬 코드를 호출하면 안 됩니다.
하나의 모듈 정의에서 여러
Py_mod_create
슬롯을 지정할 수 없습니다.Py_mod_create
를 지정하지 않으면, 임포트 절차는PyModule_New()
를 사용하여 일반 모듈 객체를 만듭니다. 이름은 정의가 아니라 spec에서 취합니다, 확장 모듈이 단일 모듈 정의를 공유하면서 모듈 계층 구조에서 해당 위치에 동적으로 조정되고 심볼릭 링크를 통해 다른 이름으로 임포트 될 수 있도록 하기 위함입니다.반환된 객체가
PyModule_Type
의 인스턴스 일 필요는 없습니다. 임포트 관련 어트리뷰트 설정과 읽기를 지원하는 한 모든 형을 사용할 수 있습니다. 그러나,PyModuleDef
에NULL
이 아닌m_traverse
,m_clear
,m_free
; 0이 아닌m_size
; 또는Py_mod_create
이외의 슬롯이 있으면,PyModule_Type
인스턴스 만 반환될 수 있습니다.-
PyObject *create_module(PyObject *spec, PyModuleDef *def)¶
-
Py_mod_exec¶
모듈을 실행하기 위해 호출되는 함수를 지정합니다. 이것은 파이썬 모듈의 코드를 실행하는 것과 동등합니다: 일반적으로, 이 함수는 클래스와 상수를 모듈에 추가합니다. 함수의 서명은 다음과 같습니다:
여러 개의
Py_mod_exec
슬롯이 지정되면, m_slots 배열에 나타나는 순서대로 처리됩니다.
-
Py_mod_multiple_interpreters¶
Specifies one of the following values:
-
Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED¶
The module does not support being imported in subinterpreters.
-
Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED¶
The module supports being imported in subinterpreters, but only when they share the main interpreter’s GIL. (See Isolating Extension Modules.)
-
Py_MOD_PER_INTERPRETER_GIL_SUPPORTED¶
The module supports being imported in subinterpreters, even when they have their own GIL. (See Isolating Extension Modules.)
This slot determines whether or not importing this module in a subinterpreter will fail.
하나의 모듈 정의에서 여러
Py_mod_multiple_interpreters
슬롯을 지정할 수 없습니다.If
Py_mod_multiple_interpreters
is not specified, the import machinery defaults toPy_MOD_MULTIPLE_INTERPRETERS_SUPPORTED
.Added in version 3.12.
-
Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED¶
-
Py_mod_gil¶
Specifies one of the following values:
-
Py_MOD_GIL_USED¶
The module depends on the presence of the global interpreter lock (GIL), and may access global state without synchronization.
-
Py_MOD_GIL_NOT_USED¶
The module is safe to run without an active GIL.
This slot is ignored by Python builds not configured with
--disable-gil
. Otherwise, it determines whether or not importing this module will cause the GIL to be automatically enabled. See Free-threaded CPython for more detail.하나의 모듈 정의에서 여러
Py_mod_gil
슬롯을 지정할 수 없습니다.If
Py_mod_gil
is not specified, the import machinery defaults toPy_MOD_GIL_USED
.Added in version 3.13.
-
Py_MOD_GIL_USED¶
Creating extension modules dynamically¶
The following functions may be used to create a module outside of an extension’s initialization function. They are also used in single-phase initialization.
-
PyObject *PyModule_Create(PyModuleDef *def)¶
- 반환값: 새 참조.
Create a new module object, given the definition in def. This is a macro that calls
PyModule_Create2()
with module_api_version set toPYTHON_API_VERSION
, or toPYTHON_ABI_VERSION
if using the limited API.
-
PyObject *PyModule_Create2(PyModuleDef *def, int module_api_version)¶
- 반환값: 새 참조. Part of the 안정 ABI.
def의 정의에 따라, API 버전 module_api_version을 가정하여 새 모듈 객체를 만듭니다. 해당 버전이 실행 중인 인터프리터 버전과 일치하지 않으면,
RuntimeWarning
을 발생시킵니다.Return
NULL
with an exception set on error.This function does not support slots. The
m_slots
member of def must beNULL
.참고
이 함수는 대부분
PyModule_Create()
를 대신 사용해야 합니다; 확실히 필요할 때만 사용하십시오.
-
PyObject *PyModule_FromDefAndSpec(PyModuleDef *def, PyObject *spec)¶
- 반환값: 새 참조.
This macro calls
PyModule_FromDefAndSpec2()
with module_api_version set toPYTHON_API_VERSION
, or toPYTHON_ABI_VERSION
if using the limited API.Added in version 3.5.
-
PyObject *PyModule_FromDefAndSpec2(PyModuleDef *def, PyObject *spec, int module_api_version)¶
- 반환값: 새 참조. Part of the 안정 ABI 버전 3.7 이후로.
API 버전 module_api_version을 가정하여, 주어진 def의 정의와 ModuleSpec spec으로 새 모듈 객체를 만듭니다. 해당 버전이 실행 중인 인터프리터 버전과 일치하지 않으면,
RuntimeWarning
을 발생시킵니다.Return
NULL
with an exception set on error.Note that this does not process execution slots (
Py_mod_exec
). BothPyModule_FromDefAndSpec
andPyModule_ExecDef
must be called to fully initialize a module.참고
이 함수는 대부분
PyModule_FromDefAndSpec()
을 대신 사용해야 합니다; 확실히 필요할 때만 사용하십시오.Added in version 3.5.
-
int PyModule_ExecDef(PyObject *module, PyModuleDef *def)¶
- Part of the 안정 ABI 버전 3.7 이후로.
def에 지정된 모든 실행 슬롯(
Py_mod_exec
)을 처리합니다.Added in version 3.5.
-
PYTHON_API_VERSION¶
The C API version. Defined for backwards compatibility.
Currently, this constant is not updated in new Python versions, and is not useful for versioning. This may change in the future.
-
PYTHON_ABI_VERSION¶
Defined as
3
for backwards compatibility.Currently, this constant is not updated in new Python versions, and is not useful for versioning. This may change in the future.
지원 함수¶
The following functions are provided to help initialize a module
state.
They are intended for a module’s execution slots (Py_mod_exec
),
the initialization function for legacy single-phase initialization,
or code that creates modules dynamically.
-
int PyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value)¶
- Part of the 안정 ABI 버전 3.10 이후로.
module에 객체를 name으로 추가합니다. 모듈의 초기화 함수에서 사용할 수 있는 편의 함수입니다.
성공하면,
0
을 반환합니다. 에러 시, 예외를 발생시키고-1
을 반환합니다.사용 예:
static int add_spam(PyObject *module, int value) { PyObject *obj = PyLong_FromLong(value); if (obj == NULL) { return -1; } int res = PyModule_AddObjectRef(module, "spam", obj); Py_DECREF(obj); return res; }
To be convenient, the function accepts
NULL
value with an exception set. In this case, return-1
and just leave the raised exception unchanged.The example can also be written without checking explicitly if obj is
NULL
:static int add_spam(PyObject *module, int value) { PyObject *obj = PyLong_FromLong(value); int res = PyModule_AddObjectRef(module, "spam", obj); Py_XDECREF(obj); return res; }
Note that
Py_XDECREF()
should be used instead ofPy_DECREF()
in this case, since obj can beNULL
.The number of different name strings passed to this function should be kept small, usually by only using statically allocated strings as name. For names that aren’t known at compile time, prefer calling
PyUnicode_FromString()
andPyObject_SetAttr()
directly. For more details, seePyUnicode_InternFromString()
, which may be used internally to create a key object.Added in version 3.10.
-
int PyModule_Add(PyObject *module, const char *name, PyObject *value)¶
- Part of the 안정 ABI 버전 3.13 이후로.
Similar to
PyModule_AddObjectRef()
, but “steals” a reference to value. It can be called with a result of function that returns a new reference without bothering to check its result or even saving it to a variable.사용 예:
if (PyModule_Add(module, "spam", PyBytes_FromString(value)) < 0) { goto error; }
Added in version 3.13.
-
int PyModule_AddObject(PyObject *module, const char *name, PyObject *value)¶
- Part of the 안정 ABI.
Similar to
PyModule_AddObjectRef()
, but steals a reference to value on success (if it returns0
).The new
PyModule_Add()
orPyModule_AddObjectRef()
functions are recommended, since it is easy to introduce reference leaks by misusing thePyModule_AddObject()
function.참고
참조를 훔치는 다른 함수와 달리,
PyModule_AddObject()
는 성공 시에만 value에 대한 참조를 해제합니다.이는 반환 값을 확인해야 하며, 에러 시 호출하는 코드가 수동으로 value를
Py_XDECREF()
해야 함을 뜻합니다.사용 예:
PyObject *obj = PyBytes_FromString(value); if (PyModule_AddObject(module, "spam", obj) < 0) { // 'obj' 가 NULL 이 아니고 PyModule_AddObject() 가 실패하면, // 'obj' 강한 참조는 Py_XDECREF() 로 삭제해야 합니다. // 'obj' 가 NULL 이면, Py_XDECREF() 는 아무것도 하지 않습니다. Py_XDECREF(obj); goto error; } // PyModule_AddObject() 는 obj 에 대한 참조를 훔칩니다: // 여기에서 Py_XDECREF(obj) 는 필요 없습니다.
버전 3.13부터 폐지됨:
PyModule_AddObject()
is soft deprecated.
-
int PyModule_AddIntConstant(PyObject *module, const char *name, long value)¶
- Part of the 안정 ABI.
module에 정수 상수를 name으로 추가합니다. 이 편의 함수는 모듈의 초기화 함수에서 사용할 수 있습니다. 에러 시 예외를 설정하고
-1
을, 성공하면0
을 반환합니다.This is a convenience function that calls
PyLong_FromLong()
andPyModule_AddObjectRef()
; see their documentation for details.
-
int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value)¶
- Part of the 안정 ABI.
module에 문자열 상수를 name으로 추가합니다. 이 편의 함수는 모듈의 초기화 함수에서 사용할 수 있습니다. 문자열 value는
NULL
로 끝나야 합니다. 에러 시 예외를 설정하고-1
을, 성공 시0
을 반환합니다.This is a convenience function that calls
PyUnicode_InternFromString()
andPyModule_AddObjectRef()
; see their documentation for details.
-
PyModule_AddIntMacro(module, macro)¶
module에 int 상수를 추가합니다. 이름과 값은 macro에서 취합니다. 예를 들어
PyModule_AddIntMacro(module, AF_INET)
은 AF_INET 값을 가진 int 상수 AF_INET을 module에 추가합니다. 에러 시 예외를 설정하고-1
을, 성공하면0
을 반환합니다.
-
PyModule_AddStringMacro(module, macro)¶
module에 문자열 상수를 추가합니다.
-
int PyModule_AddType(PyObject *module, PyTypeObject *type)¶
- Part of the 안정 ABI 버전 3.10 이후로.
module에 형 객체를 추가합니다. 내부적으로
PyType_Ready()
를 호출하여 형 객체를 파이널라이즈합니다. 형 객체의 이름은 점 뒤tp_name
의 마지막 구성 요소에서 가져옵니다. 에러가 발생하면 예외를 설정하고-1
을, 성공하면0
을 반환합니다.Added in version 3.9.
-
int PyModule_AddFunctions(PyObject *module, PyMethodDef *functions)¶
- Part of the 안정 ABI 버전 3.7 이후로.
Add the functions from the
NULL
terminated functions array to module. Refer to thePyMethodDef
documentation for details on individual entries (due to the lack of a shared module namespace, module level “functions” implemented in C typically receive the module as their first parameter, making them similar to instance methods on Python classes).This function is called automatically when creating a module from
PyModuleDef
(such as when using Multi-phase initialization,PyModule_Create
, orPyModule_FromDefAndSpec
). Some module authors may prefer defining functions in multiplePyMethodDef
arrays; in that case they should call this function directly.Added in version 3.5.
-
int PyModule_SetDocString(PyObject *module, const char *docstring)¶
- Part of the 안정 ABI 버전 3.7 이후로.
Set the docstring for module to docstring. This function is called automatically when creating a module from
PyModuleDef
(such as when using Multi-phase initialization,PyModule_Create
, orPyModule_FromDefAndSpec
).Added in version 3.5.
-
int PyUnstable_Module_SetGIL(PyObject *module, void *gil)¶
- 이것은 불안정 API. It may change without warning in minor releases.
Indicate that module does or does not support running without the global interpreter lock (GIL), using one of the values from
Py_mod_gil
. It must be called during module’s initialization function when using Legacy single-phase initialization. If this function is not called during module initialization, the import machinery assumes the module does not support running without the GIL. This function is only available in Python builds configured with--disable-gil
. Return-1
with an exception set on error,0
on success.Added in version 3.13.
Module lookup (single-phase initialization)¶
The legacy single-phase initialization initialization scheme creates singleton modules that can be looked up in the context of the current interpreter. This allows the module object to be retrieved later with only a reference to the module definition.
이 함수들은 다단계 초기화를 사용하여 만들어진 모듈에서는 작동하지 않습니다. 단일 정의에서 그러한 모듈이 여러 개 만들어질 수 있기 때문입니다.
-
PyObject *PyState_FindModule(PyModuleDef *def)¶
- 반환값: 빌린 참조. Part of the 안정 ABI.
현재 인터프리터에 대해 def에서 만들어진 모듈 객체를 반환합니다. 이 메서드를 사용하려면 먼저 모듈 객체가
PyState_AddModule()
로 인터프리터 상태에 연결되어 있어야 합니다. 해당 모듈 객체를 찾을 수 없거나 인터프리터 상태에 아직 연결되지 않았으면,NULL
을 반환합니다.
-
int PyState_AddModule(PyObject *module, PyModuleDef *def)¶
- Part of the 안정 ABI 버전 3.3 이후로.
함수에 전달된 모듈 객체를 인터프리터 상태에 연결합니다. 이는
PyState_FindModule()
을 통해 모듈 객체에 액세스 할 수 있도록 합니다.단단계 초기화를 사용하여 만든 모듈에만 효과가 있습니다.
Python calls
PyState_AddModule
automatically after importing a module that uses single-phase initialization, so it is unnecessary (but harmless) to call it from module initialization code. An explicit call is needed only if the module’s own init code subsequently callsPyState_FindModule
. The function is mainly intended for implementing alternative import mechanisms (either by calling it directly, or by referring to its implementation for details of the required state updates).If a module was attached previously using the same def, it is replaced by the new module.
The caller must have an attached thread state.
에러 시 예외를 설정하고
-1
을, 성공 시0
을 반환합니다.Added in version 3.3.
-
int PyState_RemoveModule(PyModuleDef *def)¶
- Part of the 안정 ABI 버전 3.3 이후로.
def에서 만들어진 모듈 객체를 인터프리터 상태에서 제거합니다. 에러 시 예외를 설정하고
-1
을, 성공 시0
을 반환합니다.The caller must have an attached thread state.
Added in version 3.3.