@@ -2024,6 +2024,40 @@ PyAPI_FUNC(int) _PyUnicode_CheckConsistency(
20242024 int check_content);
20252025#endif
20262026
2027+ /* ******************** String Literals ****************************************/
2028+ /* This structure helps managing static strings. The basic usage goes like this:
2029+ Instead of doing
2030+
2031+ r = PyObject_CallMethod(o, "foo", "args", ...);
2032+
2033+ do
2034+
2035+ _Py_identifier(foo);
2036+ ...
2037+ r = _PyObject_CallMethodId(o, &PyId_foo, "args", ...);
2038+
2039+ PyId_foo is a static variable, either on block level or file level. On first
2040+ usage, the string "foo" is interned, and the structures are linked. On interpreter
2041+ shutdown, all strings are released (through _PyUnicode_ClearStaticStrings).
2042+
2043+ Alternatively, _Py_static_string allows to choose the variable name.
2044+ _PyUnicode_FromId returns a new reference to the interned string.
2045+ _PyObject_{Get,Set,Has}AttrId are __getattr__ versions using _Py_Identifier*.
2046+ */
2047+ typedef struct _Py_Identifier {
2048+ struct _Py_Identifier *next;
2049+ const char * string;
2050+ PyObject *object;
2051+ } _Py_Identifier;
2052+
2053+ #define _Py_static_string (varname, value ) static _Py_Identifier varname = { 0 , value, 0 };
2054+ #define _Py_identifier (varname ) _Py_static_string(PyId_##varname, #varname)
2055+
2056+ /* Return an interned Unicode object for an Identifier; may fail if there is no memory.*/
2057+ PyAPI_FUNC (PyObject*) _PyUnicode_FromId(_Py_Identifier*);
2058+ /* Clear all static strings. */
2059+ PyAPI_FUNC (void ) _PyUnicode_ClearStaticStrings(void );
2060+
20272061#ifdef __cplusplus
20282062}
20292063#endif
0 commit comments