diff --git a/Makefile b/Makefile index 47c27746f..871a5aa93 100644 --- a/Makefile +++ b/Makefile @@ -19,7 +19,7 @@ # test build, we're building with the .rst files that generated our # .po files. -CPYTHON_CURRENT_COMMIT := 5df322e91a40909e6904bbdbc0c3a6b6a9eead39 +CPYTHON_CURRENT_COMMIT := dc3c075d9eebc82c63ec54bb3f217d67b2aea914 LANGUAGE := tr BRANCH := 3.12 diff --git a/c-api/arg.po b/c-api/arg.po index ac1871a67..3364d0bad 100644 --- a/c-api/arg.po +++ b/c-api/arg.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -602,6 +602,10 @@ msgid "" "*converter* function in turn is called as follows::" msgstr "" +#: c-api/arg.rst:316 +msgid "status = converter(object, address);" +msgstr "" + #: c-api/arg.rst:318 msgid "" "where *object* is the Python object to be converted and *address* is the :c:" @@ -818,12 +822,32 @@ msgid "" "the :mod:`!_weakref` helper module for weak references::" msgstr "" +#: c-api/arg.rst:477 +msgid "" +"static PyObject *\n" +"weakref_ref(PyObject *self, PyObject *args)\n" +"{\n" +" PyObject *object;\n" +" PyObject *callback = NULL;\n" +" PyObject *result = NULL;\n" +"\n" +" if (PyArg_UnpackTuple(args, \"ref\", 1, 2, &object, &callback)) {\n" +" result = PyWeakref_NewRef(object, callback);\n" +" }\n" +" return result;\n" +"}" +msgstr "" + #: c-api/arg.rst:490 msgid "" "The call to :c:func:`PyArg_UnpackTuple` in this example is entirely " "equivalent to this call to :c:func:`PyArg_ParseTuple`::" msgstr "" +#: c-api/arg.rst:493 +msgid "PyArg_ParseTuple(args, \"O|O:ref\", &object, &callback)" +msgstr "" + #: c-api/arg.rst:498 msgid "Building values" msgstr "" diff --git a/c-api/buffer.po b/c-api/buffer.po index ec087d4ed..fde899100 100644 --- a/c-api/buffer.po +++ b/c-api/buffer.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -512,6 +512,13 @@ msgid "" "dimensional array as follows:" msgstr "" +#: c-api/buffer.rst:368 +msgid "" +"ptr = (char *)buf + indices[0] * strides[0] + ... + indices[n-1] * " +"strides[n-1];\n" +"item = *((typeof(item) *)ptr);" +msgstr "" + #: c-api/buffer.rst:374 msgid "" "As noted above, :c:member:`~Py_buffer.buf` can point to any location within " @@ -519,6 +526,35 @@ msgid "" "this function:" msgstr "" +#: c-api/buffer.rst:378 +msgid "" +"def verify_structure(memlen, itemsize, ndim, shape, strides, offset):\n" +" \"\"\"Verify that the parameters represent a valid array within\n" +" the bounds of the allocated memory:\n" +" char *mem: start of the physical memory block\n" +" memlen: length of the physical memory block\n" +" offset: (char *)buf - mem\n" +" \"\"\"\n" +" if offset % itemsize:\n" +" return False\n" +" if offset < 0 or offset+itemsize > memlen:\n" +" return False\n" +" if any(v % itemsize for v in strides):\n" +" return False\n" +"\n" +" if ndim <= 0:\n" +" return ndim == 0 and not shape and not strides\n" +" if 0 in shape:\n" +" return True\n" +"\n" +" imin = sum(strides[j]*(shape[j]-1) for j in range(ndim)\n" +" if strides[j] <= 0)\n" +" imax = sum(strides[j]*(shape[j]-1) for j in range(ndim)\n" +" if strides[j] > 0)\n" +"\n" +" return 0 <= offset+imin and offset+imax+itemsize <= memlen" +msgstr "" + #: c-api/buffer.rst:408 msgid "PIL-style: shape, strides and suboffsets" msgstr "" @@ -541,6 +577,22 @@ msgid "" "strides and suboffsets::" msgstr "" +#: c-api/buffer.rst:423 +msgid "" +"void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides,\n" +" Py_ssize_t *suboffsets, Py_ssize_t *indices) {\n" +" char *pointer = (char*)buf;\n" +" int i;\n" +" for (i = 0; i < ndim; i++) {\n" +" pointer += strides[i] * indices[i];\n" +" if (suboffsets[i] >=0 ) {\n" +" pointer = *((char**)pointer) + suboffsets[i];\n" +" }\n" +" }\n" +" return (void*)pointer;\n" +"}" +msgstr "" + #: c-api/buffer.rst:438 msgid "Buffer-related functions" msgstr "" diff --git a/c-api/bytearray.po b/c-api/bytearray.po index d890bd173..51f07f90e 100644 --- a/c-api/bytearray.po +++ b/c-api/bytearray.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-09-18 19:05+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -57,44 +57,46 @@ msgid "" "`buffer protocol `." msgstr "" -#: c-api/bytearray.rst:48 -msgid "" -"Create a new bytearray object from *string* and its length, *len*. On " -"failure, ``NULL`` is returned." +#: c-api/bytearray.rst:52 c-api/bytearray.rst:59 +msgid "On failure, return ``NULL`` with an exception set." +msgstr "" + +#: c-api/bytearray.rst:50 +msgid "Create a new bytearray object from *string* and its length, *len*." msgstr "" -#: c-api/bytearray.rst:54 +#: c-api/bytearray.rst:57 msgid "" "Concat bytearrays *a* and *b* and return a new bytearray with the result." msgstr "" -#: c-api/bytearray.rst:59 +#: c-api/bytearray.rst:64 msgid "Return the size of *bytearray* after checking for a ``NULL`` pointer." msgstr "" -#: c-api/bytearray.rst:64 +#: c-api/bytearray.rst:69 msgid "" "Return the contents of *bytearray* as a char array after checking for a " "``NULL`` pointer. The returned array always has an extra null byte appended." msgstr "" -#: c-api/bytearray.rst:71 +#: c-api/bytearray.rst:76 msgid "Resize the internal buffer of *bytearray* to *len*." msgstr "" -#: c-api/bytearray.rst:74 +#: c-api/bytearray.rst:79 msgid "Macros" msgstr "" -#: c-api/bytearray.rst:76 +#: c-api/bytearray.rst:81 msgid "These macros trade safety for speed and they don't check pointers." msgstr "" -#: c-api/bytearray.rst:80 +#: c-api/bytearray.rst:85 msgid "Similar to :c:func:`PyByteArray_AsString`, but without error checking." msgstr "" -#: c-api/bytearray.rst:85 +#: c-api/bytearray.rst:90 msgid "Similar to :c:func:`PyByteArray_Size`, but without error checking." msgstr "" diff --git a/c-api/call.po b/c-api/call.po index f120214e9..4b7fbef36 100644 --- a/c-api/call.po +++ b/c-api/call.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-01 21:53+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -35,6 +35,11 @@ msgid "" "callable. The signature of the slot is::" msgstr "" +#: c-api/call.rst:17 +msgid "" +"PyObject *tp_call(PyObject *callable, PyObject *args, PyObject *kwargs);" +msgstr "" + #: c-api/call.rst:19 msgid "" "A call is made using a tuple for the positional arguments and a dict for the " @@ -215,6 +220,10 @@ msgid "" "Currently equivalent to::" msgstr "" +#: c-api/call.rst:153 +msgid "(Py_ssize_t)(nargsf & ~PY_VECTORCALL_ARGUMENTS_OFFSET)" +msgstr "" + #: c-api/call.rst:155 msgid "" "However, the function ``PyVectorcall_NARGS`` should be used to allow for " diff --git a/c-api/capsule.po b/c-api/capsule.po index bcd925fb1..377d894d2 100644 --- a/c-api/capsule.po +++ b/c-api/capsule.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-09-18 19:05+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -39,6 +39,10 @@ msgstr "" msgid "The type of a destructor callback for a capsule. Defined as::" msgstr "" +#: c-api/capsule.rst:29 +msgid "typedef void (*PyCapsule_Destructor)(PyObject *);" +msgstr "" + #: c-api/capsule.rst:31 msgid "" "See :c:func:`PyCapsule_New` for the semantics of PyCapsule_Destructor " diff --git a/c-api/code.po b/c-api/code.po index 3a966b453..63f6a0453 100644 --- a/c-api/code.po +++ b/c-api/code.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-02-24 17:22+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -119,9 +119,8 @@ msgstr "" #: c-api/code.rst:93 msgid "" -"For efficiently iterating over the line numbers in a code object, use `the " -"API described in PEP 626 `_." +"For efficiently iterating over the line numbers in a code object, use :pep:" +"`the API described in PEP 626 <0626#out-of-process-debuggers-and-profilers>`." msgstr "" #: c-api/code.rst:98 diff --git a/c-api/complex.po b/c-api/complex.po index 7fc84a4fd..b8a7e8fc6 100644 --- a/c-api/complex.po +++ b/c-api/complex.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -51,6 +51,14 @@ msgstr "" msgid "The structure is defined as::" msgstr "" +#: c-api/complex.rst:35 +msgid "" +"typedef struct {\n" +" double real;\n" +" double imag;\n" +"} Py_complex;" +msgstr "" + #: c-api/complex.rst:43 msgid "" "Return the sum of two complex numbers, using the C :c:type:`Py_complex` " diff --git a/c-api/contextvars.po b/c-api/contextvars.po index 2e822b59b..d255afa19 100644 --- a/c-api/contextvars.po +++ b/c-api/contextvars.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-04-01 00:17+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -27,6 +27,15 @@ msgid "" "`PyContext`, :c:type:`PyContextVar`, and :c:type:`PyContextToken`, e.g.::" msgstr "" +#: c-api/contextvars.rst:20 +msgid "" +"// in 3.7.0:\n" +"PyContext *PyContext_New(void);\n" +"\n" +"// in 3.7.1+:\n" +"PyObject *PyContext_New(void);" +msgstr "" + #: c-api/contextvars.rst:26 msgid "See :issue:`34762` for more details." msgstr "" diff --git a/c-api/datetime.po b/c-api/datetime.po index d9f151346..6ea226719 100644 --- a/c-api/datetime.po +++ b/c-api/datetime.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-09-18 19:05+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -297,11 +297,11 @@ msgstr "" #: c-api/datetime.rst:320 msgid "" "Create and return a new :class:`datetime.datetime` object given an argument " -"tuple suitable for passing to :meth:`datetime.datetime.fromtimestamp()`." +"tuple suitable for passing to :meth:`datetime.datetime.fromtimestamp`." msgstr "" #: c-api/datetime.rst:326 msgid "" "Create and return a new :class:`datetime.date` object given an argument " -"tuple suitable for passing to :meth:`datetime.date.fromtimestamp()`." +"tuple suitable for passing to :meth:`datetime.date.fromtimestamp`." msgstr "" diff --git a/c-api/dict.po b/c-api/dict.po index 3c0d031c0..2bf9e75bf 100644 --- a/c-api/dict.po +++ b/c-api/dict.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-09-18 22:33+0300\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -190,6 +190,17 @@ msgstr "" msgid "For example::" msgstr "" +#: c-api/dict.rst:181 +msgid "" +"PyObject *key, *value;\n" +"Py_ssize_t pos = 0;\n" +"\n" +"while (PyDict_Next(self->dict, &pos, &key, &value)) {\n" +" /* do something interesting with the values... */\n" +" ...\n" +"}" +msgstr "" + #: c-api/dict.rst:189 msgid "" "The dictionary *p* should not be mutated during iteration. It is safe to " @@ -197,6 +208,27 @@ msgid "" "so long as the set of keys does not change. For example::" msgstr "" +#: c-api/dict.rst:193 +msgid "" +"PyObject *key, *value;\n" +"Py_ssize_t pos = 0;\n" +"\n" +"while (PyDict_Next(self->dict, &pos, &key, &value)) {\n" +" long i = PyLong_AsLong(value);\n" +" if (i == -1 && PyErr_Occurred()) {\n" +" return -1;\n" +" }\n" +" PyObject *o = PyLong_FromLong(i + 1);\n" +" if (o == NULL)\n" +" return -1;\n" +" if (PyDict_SetItem(self->dict, key, o) < 0) {\n" +" Py_DECREF(o);\n" +" return -1;\n" +" }\n" +" Py_DECREF(o);\n" +"}" +msgstr "" + #: c-api/dict.rst:214 msgid "" "Iterate over mapping object *b* adding key-value pairs to dictionary *a*. " @@ -225,6 +257,14 @@ msgid "" "if an exception was raised. Equivalent Python (except for the return value)::" msgstr "" +#: c-api/dict.rst:240 +msgid "" +"def PyDict_MergeFromSeq2(a, seq2, override):\n" +" for key, value in seq2:\n" +" if override or key not in a:\n" +" a[key] = value" +msgstr "" + #: c-api/dict.rst:247 msgid "" "Register *callback* as a dictionary watcher. Return a non-negative integer " diff --git a/c-api/exceptions.po b/c-api/exceptions.po index aeee089b4..5af007709 100644 --- a/c-api/exceptions.po +++ b/c-api/exceptions.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-01 21:53+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -57,7 +57,7 @@ msgstr "" #: c-api/exceptions.rst:37 msgid "" -"The error indicator is **not** the result of :func:`sys.exc_info()`. The " +"The error indicator is **not** the result of :func:`sys.exc_info`. The " "former corresponds to an exception that is not yet caught (and is therefore " "still propagating), while the latter returns an exception after it is caught " "(and has therefore stopped propagating)." @@ -253,7 +253,7 @@ msgid "" msgstr "" #: c-api/exceptions.rst:229 c-api/exceptions.rst:250 c-api/exceptions.rst:268 -msgid ":ref:`Availability `: Windows." +msgid "Availability" msgstr "" #: c-api/exceptions.rst:226 @@ -464,6 +464,17 @@ msgstr "" msgid "For example::" msgstr "" +#: c-api/exceptions.rst:438 +msgid "" +"{\n" +" PyObject *exc = PyErr_GetRaisedException();\n" +"\n" +" /* ... code that might produce other errors ... */\n" +"\n" +" PyErr_SetRaisedException(exc);\n" +"}" +msgstr "" + #: c-api/exceptions.rst:446 msgid "" ":c:func:`PyErr_GetHandledException`, to save the exception currently being " @@ -499,6 +510,18 @@ msgid "" "exceptions or save and restore the error indicator temporarily." msgstr "" +#: c-api/exceptions.rst:482 +msgid "" +"{\n" +" PyObject *type, *value, *traceback;\n" +" PyErr_Fetch(&type, &value, &traceback);\n" +"\n" +" /* ... code that might produce other errors ... */\n" +"\n" +" PyErr_Restore(type, value, traceback);\n" +"}" +msgstr "" + #: c-api/exceptions.rst:496 msgid "Use :c:func:`PyErr_SetRaisedException` instead." msgstr "" @@ -546,6 +569,13 @@ msgid "" "appropriately is desired, the following additional snippet is needed::" msgstr "" +#: c-api/exceptions.rst:537 +msgid "" +"if (tb != NULL) {\n" +" PyException_SetTraceback(val, tb);\n" +"}" +msgstr "" + #: c-api/exceptions.rst:544 msgid "" "Retrieve the active exception instance, as would be returned by :func:`sys." @@ -737,9 +767,9 @@ msgstr "" #: c-api/exceptions.rst:723 msgid "" -"The :attr:`!__module__` attribute of the new class is set to the first part " -"(up to the last dot) of the *name* argument, and the class name is set to " -"the last part (after the last dot). The *base* argument can be used to " +"The :attr:`~type.__module__` attribute of the new class is set to the first " +"part (up to the last dot) of the *name* argument, and the class name is set " +"to the last part (after the last dot). The *base* argument can be used to " "specify alternate base classes; it can either be only one class or a tuple " "of classes. The *dict* argument can be used to specify a dictionary of class " "variables and methods." diff --git a/c-api/file.po b/c-api/file.po index a5d15fea7..2fafda9b4 100644 --- a/c-api/file.po +++ b/c-api/file.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -82,45 +82,47 @@ msgid "" msgstr "" #: c-api/file.rst:68 -msgid "The handler is a function of type:" +msgid "The *handler* is a function of type:" msgstr "" -#: c-api/file.rst:72 +#: c-api/file.rst:73 msgid "" "Equivalent of :c:expr:`PyObject *(\\*)(PyObject *path, void *userData)`, " "where *path* is guaranteed to be :c:type:`PyUnicodeObject`." msgstr "" -#: c-api/file.rst:76 +#: c-api/file.rst:77 msgid "" "The *userData* pointer is passed into the hook function. Since hook " "functions may be called from different runtimes, this pointer should not " "refer directly to Python state." msgstr "" -#: c-api/file.rst:80 +#: c-api/file.rst:81 msgid "" "As this hook is intentionally used during import, avoid importing new " "modules during its execution unless they are known to be frozen or available " "in ``sys.modules``." msgstr "" -#: c-api/file.rst:84 +#: c-api/file.rst:85 msgid "" "Once a hook has been set, it cannot be removed or replaced, and later calls " "to :c:func:`PyFile_SetOpenCodeHook` will fail. On failure, the function " "returns -1 and sets an exception if the interpreter has been initialized." msgstr "" -#: c-api/file.rst:88 +#: c-api/file.rst:89 msgid "This function is safe to call before :c:func:`Py_Initialize`." msgstr "" -#: c-api/file.rst:90 -msgid "Raises an auditing event setopencodehook with no arguments." +#: c-api/file.rst:91 +msgid "" +"Raises an :ref:`auditing event ` ``setopencodehook`` with no " +"arguments." msgstr "" -#: c-api/file.rst:100 +#: c-api/file.rst:101 msgid "" "Write object *obj* to file object *p*. The only supported flag for *flags* " "is :c:macro:`Py_PRINT_RAW`; if given, the :func:`str` of the object is " @@ -128,7 +130,7 @@ msgid "" "failure; the appropriate exception will be set." msgstr "" -#: c-api/file.rst:108 +#: c-api/file.rst:109 msgid "" "Write string *s* to file object *p*. Return ``0`` on success or ``-1`` on " "failure; the appropriate exception will be set." @@ -146,6 +148,6 @@ msgstr "" msgid "EOFError (built-in exception)" msgstr "" -#: c-api/file.rst:98 +#: c-api/file.rst:99 msgid "Py_PRINT_RAW (C macro)" msgstr "" diff --git a/c-api/gcsupport.po b/c-api/gcsupport.po index a7d2ce0c6..bc9542c4d 100644 --- a/c-api/gcsupport.po +++ b/c-api/gcsupport.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-01 21:53+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -258,6 +258,17 @@ msgid "" "macro, :c:member:`~PyTypeObject.tp_traverse` handlers look like::" msgstr "" +#: c-api/gcsupport.rst:190 +msgid "" +"static int\n" +"my_traverse(Noddy *self, visitproc visit, void *arg)\n" +"{\n" +" Py_VISIT(self->foo);\n" +" Py_VISIT(self->bar);\n" +" return 0;\n" +"}" +msgstr "" + #: c-api/gcsupport.rst:198 msgid "" "The :c:member:`~PyTypeObject.tp_clear` handler must be of the :c:type:" diff --git a/c-api/import.po b/c-api/import.po index b212820d0..15e5e8c97 100644 --- a/c-api/import.po +++ b/c-api/import.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-04-01 00:17+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -133,17 +133,17 @@ msgstr "" #: c-api/import.rst:123 msgid "" -"The module's :attr:`__spec__` and :attr:`__loader__` will be set, if not set " -"already, with the appropriate values. The spec's loader will be set to the " -"module's ``__loader__`` (if set) and to an instance of :class:`~importlib." -"machinery.SourceFileLoader` otherwise." +"The module's :attr:`~module.__spec__` and :attr:`~module.__loader__` will be " +"set, if not set already, with the appropriate values. The spec's loader " +"will be set to the module's :attr:`!__loader__` (if set) and to an instance " +"of :class:`~importlib.machinery.SourceFileLoader` otherwise." msgstr "" #: c-api/import.rst:128 msgid "" -"The module's :attr:`__file__` attribute will be set to the code object's :" -"attr:`~codeobject.co_filename`. If applicable, :attr:`__cached__` will also " -"be set." +"The module's :attr:`~module.__file__` attribute will be set to the code " +"object's :attr:`~codeobject.co_filename`. If applicable, :attr:`~module." +"__cached__` will also be set." msgstr "" #: c-api/import.rst:132 @@ -166,14 +166,14 @@ msgstr "" #: c-api/import.rst:141 msgid "" -"The setting of :attr:`__cached__` and :attr:`__loader__` is deprecated. See :" -"class:`~importlib.machinery.ModuleSpec` for alternatives." +"The setting of :attr:`~module.__cached__` and :attr:`~module.__loader__` is " +"deprecated. See :class:`~importlib.machinery.ModuleSpec` for alternatives." msgstr "" #: c-api/import.rst:149 msgid "" -"Like :c:func:`PyImport_ExecCodeModule`, but the :attr:`__file__` attribute " -"of the module object is set to *pathname* if it is non-``NULL``." +"Like :c:func:`PyImport_ExecCodeModule`, but the :attr:`~module.__file__` " +"attribute of the module object is set to *pathname* if it is non-``NULL``." msgstr "" #: c-api/import.rst:152 @@ -182,15 +182,15 @@ msgstr "" #: c-api/import.rst:157 msgid "" -"Like :c:func:`PyImport_ExecCodeModuleEx`, but the :attr:`__cached__` " +"Like :c:func:`PyImport_ExecCodeModuleEx`, but the :attr:`~module.__cached__` " "attribute of the module object is set to *cpathname* if it is non-``NULL``. " "Of the three functions, this is the preferred one to use." msgstr "" #: c-api/import.rst:163 msgid "" -"Setting :attr:`__cached__` is deprecated. See :class:`~importlib.machinery." -"ModuleSpec` for alternatives." +"Setting :attr:`~module.__cached__` is deprecated. See :class:`~importlib." +"machinery.ModuleSpec` for alternatives." msgstr "" #: c-api/import.rst:170 @@ -203,7 +203,7 @@ msgstr "" #: c-api/import.rst:176 msgid "" -"Uses :func:`!imp.source_from_cache()` in calculating the source path if only " +"Uses :func:`!imp.source_from_cache` in calculating the source path if only " "the bytecode path is provided." msgstr "" @@ -280,6 +280,16 @@ msgid "" "h`, is::" msgstr "" +#: c-api/import.rst:254 +msgid "" +"struct _frozen {\n" +" const char *name;\n" +" const unsigned char *code;\n" +" int size;\n" +" bool is_package;\n" +"};" +msgstr "" + #: c-api/import.rst:261 msgid "" "The new ``is_package`` field indicates whether the module is a package or " diff --git a/c-api/init.po b/c-api/init.po index 3f66600c8..e5fceca7a 100644 --- a/c-api/init.po +++ b/c-api/init.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -371,7 +371,7 @@ msgid "See :pep:`529` for more details." msgstr "" #: c-api/init.rst:240 -msgid ":ref:`Availability `: Windows." +msgid "Availability" msgstr "" #: c-api/init.rst:228 @@ -601,7 +601,8 @@ msgstr "" #: c-api/init.rst:421 msgid "" -"Raises an auditing event cpython._PySys_ClearAuditHooks with no arguments." +"Raises an :ref:`auditing event ` ``cpython." +"_PySys_ClearAuditHooks`` with no arguments." msgstr "" #: c-api/init.rst:427 @@ -834,6 +835,10 @@ msgid "" "something like ::" msgstr "" +#: c-api/init.rst:663 +msgid "\"3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \\n[GCC 4.2.3]\"" +msgstr "" + #: c-api/init.rst:667 msgid "" "The first word (up to the first space character) is the current Python " @@ -880,6 +885,10 @@ msgid "" "version, in square brackets, for example::" msgstr "" +#: c-api/init.rst:705 +msgid "\"[GCC 2.7.2.2]\"" +msgstr "" + #: c-api/init.rst:723 msgid "" "The returned string points into static storage; the caller should not modify " @@ -893,6 +902,10 @@ msgid "" "current Python interpreter instance, for example ::" msgstr "" +#: c-api/init.rst:719 +msgid "\"#67, Aug 1 1997, 22:34:28\"" +msgstr "" + #: c-api/init.rst:735 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." @@ -953,6 +966,10 @@ msgid "" "`PySys_SetArgv`, for example using::" msgstr "" +#: c-api/init.rst:776 +msgid "PyRun_SimpleString(\"import sys; sys.path.pop(0)\\n\");" +msgstr "" + #: c-api/init.rst:788 msgid "" "This API is kept for backward compatibility: setting :c:member:`PyConfig." @@ -1044,10 +1061,26 @@ msgid "" "structure::" msgstr "" +#: c-api/init.rst:882 +msgid "" +"Save the thread state in a local variable.\n" +"Release the global interpreter lock.\n" +"... Do some blocking I/O operation ...\n" +"Reacquire the global interpreter lock.\n" +"Restore the thread state from the local variable." +msgstr "" + #: c-api/init.rst:888 msgid "This is so common that a pair of macros exists to simplify it::" msgstr "" +#: c-api/init.rst:890 +msgid "" +"Py_BEGIN_ALLOW_THREADS\n" +"... Do some blocking I/O operation ...\n" +"Py_END_ALLOW_THREADS" +msgstr "" + #: c-api/init.rst:898 msgid "" "The :c:macro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a " @@ -1059,6 +1092,15 @@ msgstr "" msgid "The block above expands to the following code::" msgstr "" +#: c-api/init.rst:904 +msgid "" +"PyThreadState *_save;\n" +"\n" +"_save = PyEval_SaveThread();\n" +"... Do some blocking I/O operation ...\n" +"PyEval_RestoreThread(_save);" +msgstr "" + #: c-api/init.rst:914 msgid "" "Here is how these functions work: the global interpreter lock is used to " @@ -1112,6 +1154,19 @@ msgid "" "Python from a C thread is::" msgstr "" +#: c-api/init.rst:955 +msgid "" +"PyGILState_STATE gstate;\n" +"gstate = PyGILState_Ensure();\n" +"\n" +"/* Perform Python actions here. */\n" +"result = CallSomeFunction();\n" +"/* evaluate result or handle exception */\n" +"\n" +"/* Release the thread. No Python API allowed beyond this point. */\n" +"PyGILState_Release(gstate);" +msgstr "" + #: c-api/init.rst:965 msgid "" "Note that the ``PyGILState_*`` functions assume there is only one global " @@ -1399,7 +1454,8 @@ msgstr "" #: c-api/init.rst:1227 msgid "" -"Raises an auditing event cpython.PyInterpreterState_New with no arguments." +"Raises an :ref:`auditing event ` ``cpython." +"PyInterpreterState_New`` with no arguments." msgstr "" #: c-api/init.rst:1232 @@ -1410,7 +1466,8 @@ msgstr "" #: c-api/init.rst:1235 msgid "" -"Raises an auditing event cpython.PyInterpreterState_Clear with no arguments." +"Raises an :ref:`auditing event ` ``cpython." +"PyInterpreterState_Clear`` with no arguments." msgstr "" #: c-api/init.rst:1240 @@ -1449,7 +1506,7 @@ msgstr "" #: c-api/init.rst:1271 msgid "" "Destroy the current thread state and release the global interpreter lock. " -"Like :c:func:`PyThreadState_Delete`, the global interpreter lock need not be " +"Like :c:func:`PyThreadState_Delete`, the global interpreter lock must be " "held. The thread state must have been reset with a previous call to :c:func:" "`PyThreadState_Clear`." msgstr "" @@ -1839,6 +1896,20 @@ msgid "" "certain functionality restricted::" msgstr "" +#: c-api/init.rst:1638 +msgid "" +"PyInterpreterConfig config = {\n" +" .use_main_obmalloc = 0,\n" +" .allow_fork = 0,\n" +" .allow_exec = 0,\n" +" .allow_threads = 1,\n" +" .allow_daemon_threads = 0,\n" +" .check_multi_interp_extensions = 1,\n" +" .gil = PyInterpreterConfig_OWN_GIL,\n" +"};\n" +"PyThreadState *tstate = Py_NewInterpreterFromConfig(&config);" +msgstr "" + #: c-api/init.rst:1649 msgid "" "Note that the config is used only briefly and does not get modified. During " diff --git a/c-api/init_config.po b/c-api/init_config.po index c848cbe8c..93c4253a6 100644 --- a/c-api/init_config.po +++ b/c-api/init_config.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -70,6 +70,42 @@ msgstr "" msgid "Example of customized Python always running in isolated mode::" msgstr "" +#: c-api/init_config.rst:41 +msgid "" +"int main(int argc, char **argv)\n" +"{\n" +" PyStatus status;\n" +"\n" +" PyConfig config;\n" +" PyConfig_InitPythonConfig(&config);\n" +" config.isolated = 1;\n" +"\n" +" /* Decode command line arguments.\n" +" Implicitly preinitialize Python (in isolated mode). */\n" +" status = PyConfig_SetBytesArgv(&config, argc, argv);\n" +" if (PyStatus_Exception(status)) {\n" +" goto exception;\n" +" }\n" +"\n" +" status = Py_InitializeFromConfig(&config);\n" +" if (PyStatus_Exception(status)) {\n" +" goto exception;\n" +" }\n" +" PyConfig_Clear(&config);\n" +"\n" +" return Py_RunMain();\n" +"\n" +"exception:\n" +" PyConfig_Clear(&config);\n" +" if (PyStatus_IsExit(status)) {\n" +" return status.exitcode;\n" +" }\n" +" /* Display the error message and exit the process with\n" +" non-zero exit code */\n" +" Py_ExitStatusException(status);\n" +"}" +msgstr "" + #: c-api/init_config.rst:76 msgid "PyWideStringList" msgstr "" @@ -206,6 +242,29 @@ msgstr "" msgid "Example::" msgstr "" +#: c-api/init_config.rst:191 +msgid "" +"PyStatus alloc(void **ptr, size_t size)\n" +"{\n" +" *ptr = PyMem_RawMalloc(size);\n" +" if (*ptr == NULL) {\n" +" return PyStatus_NoMemory();\n" +" }\n" +" return PyStatus_Ok();\n" +"}\n" +"\n" +"int main(int argc, char **argv)\n" +"{\n" +" void *ptr;\n" +" PyStatus status = alloc(&ptr, 16);\n" +" if (PyStatus_Exception(status)) {\n" +" Py_ExitStatusException(status);\n" +" }\n" +" PyMem_Free(ptr);\n" +" return 0;\n" +"}" +msgstr "" + #: c-api/init_config.rst:213 msgid "PyPreConfig" msgstr "" @@ -360,7 +419,7 @@ msgstr "" #: c-api/init_config.rst:314 msgid "" -"Initialized the from :envvar:`PYTHONLEGACYWINDOWSFSENCODING` environment " +"Initialized from the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` environment " "variable value." msgstr "" @@ -503,6 +562,26 @@ msgid "" "`::" msgstr "" +#: c-api/init_config.rst:414 +msgid "" +"PyStatus status;\n" +"PyPreConfig preconfig;\n" +"PyPreConfig_InitPythonConfig(&preconfig);\n" +"\n" +"preconfig.utf8_mode = 1;\n" +"\n" +"status = Py_PreInitialize(&preconfig);\n" +"if (PyStatus_Exception(status)) {\n" +" Py_ExitStatusException(status);\n" +"}\n" +"\n" +"/* at this point, Python speaks UTF-8 */\n" +"\n" +"Py_Initialize();\n" +"/* ... use Python API here ... */\n" +"Py_Finalize();" +msgstr "" + #: c-api/init_config.rst:433 msgid "PyConfig" msgstr "" @@ -1678,6 +1757,35 @@ msgstr "" msgid "Example setting the program name::" msgstr "" +#: c-api/init_config.rst:1316 +msgid "" +"void init_python(void)\n" +"{\n" +" PyStatus status;\n" +"\n" +" PyConfig config;\n" +" PyConfig_InitPythonConfig(&config);\n" +"\n" +" /* Set the program name. Implicitly preinitialize Python. */\n" +" status = PyConfig_SetString(&config, &config.program_name,\n" +" L\"/path/to/my_program\");\n" +" if (PyStatus_Exception(status)) {\n" +" goto exception;\n" +" }\n" +"\n" +" status = Py_InitializeFromConfig(&config);\n" +" if (PyStatus_Exception(status)) {\n" +" goto exception;\n" +" }\n" +" PyConfig_Clear(&config);\n" +" return;\n" +"\n" +"exception:\n" +" PyConfig_Clear(&config);\n" +" Py_ExitStatusException(status);\n" +"}" +msgstr "" + #: c-api/init_config.rst:1342 msgid "" "More complete example modifying the default configuration, read the " @@ -1687,6 +1795,61 @@ msgid "" "called will be left unchanged by initialization::" msgstr "" +#: c-api/init_config.rst:1349 +msgid "" +"PyStatus init_python(const char *program_name)\n" +"{\n" +" PyStatus status;\n" +"\n" +" PyConfig config;\n" +" PyConfig_InitPythonConfig(&config);\n" +"\n" +" /* Set the program name before reading the configuration\n" +" (decode byte string from the locale encoding).\n" +"\n" +" Implicitly preinitialize Python. */\n" +" status = PyConfig_SetBytesString(&config, &config.program_name,\n" +" program_name);\n" +" if (PyStatus_Exception(status)) {\n" +" goto done;\n" +" }\n" +"\n" +" /* Read all configuration at once */\n" +" status = PyConfig_Read(&config);\n" +" if (PyStatus_Exception(status)) {\n" +" goto done;\n" +" }\n" +"\n" +" /* Specify sys.path explicitly */\n" +" /* If you want to modify the default set of paths, finish\n" +" initialization first and then use PySys_GetObject(\"path\") */\n" +" config.module_search_paths_set = 1;\n" +" status = PyWideStringList_Append(&config.module_search_paths,\n" +" L\"/path/to/stdlib\");\n" +" if (PyStatus_Exception(status)) {\n" +" goto done;\n" +" }\n" +" status = PyWideStringList_Append(&config.module_search_paths,\n" +" L\"/path/to/more/modules\");\n" +" if (PyStatus_Exception(status)) {\n" +" goto done;\n" +" }\n" +"\n" +" /* Override executable computed by PyConfig_Read() */\n" +" status = PyConfig_SetString(&config, &config.executable,\n" +" L\"/path/to/my_executable\");\n" +" if (PyStatus_Exception(status)) {\n" +" goto done;\n" +" }\n" +"\n" +" status = Py_InitializeFromConfig(&config);\n" +"\n" +"done:\n" +" PyConfig_Clear(&config);\n" +" return status;\n" +"}" +msgstr "" + #: c-api/init_config.rst:1405 msgid "Isolated Configuration" msgstr "" @@ -2089,3 +2252,40 @@ msgid "" "Example running Python code between \"Core\" and \"Main\" initialization " "phases::" msgstr "" + +#: c-api/init_config.rst:1611 +msgid "" +"void init_python(void)\n" +"{\n" +" PyStatus status;\n" +"\n" +" PyConfig config;\n" +" PyConfig_InitPythonConfig(&config);\n" +" config._init_main = 0;\n" +"\n" +" /* ... customize 'config' configuration ... */\n" +"\n" +" status = Py_InitializeFromConfig(&config);\n" +" PyConfig_Clear(&config);\n" +" if (PyStatus_Exception(status)) {\n" +" Py_ExitStatusException(status);\n" +" }\n" +"\n" +" /* Use sys.stderr because sys.stdout is only created\n" +" by _Py_InitializeMain() */\n" +" int res = PyRun_SimpleString(\n" +" \"import sys; \"\n" +" \"print('Run Python code before _Py_InitializeMain', \"\n" +" \"file=sys.stderr)\");\n" +" if (res < 0) {\n" +" exit(1);\n" +" }\n" +"\n" +" /* ... put more configuration code here ... */\n" +"\n" +" status = _Py_InitializeMain();\n" +" if (PyStatus_Exception(status)) {\n" +" Py_ExitStatusException(status);\n" +" }\n" +"}" +msgstr "" diff --git a/c-api/intro.po b/c-api/intro.po index 9d8431e2d..d5c449e39 100644 --- a/c-api/intro.po +++ b/c-api/intro.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-02-24 17:22+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -74,6 +74,12 @@ msgid "" "included in your code by the following line::" msgstr "" +#: c-api/intro.rst:51 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include " +msgstr "" + #: c-api/intro.rst:54 msgid "" "This implies inclusion of the following standard headers: ````, " @@ -167,6 +173,21 @@ msgid "" "item defined in the module file. Example::" msgstr "" +#: c-api/intro.rst:119 +msgid "" +"static struct PyModuleDef spam_module = {\n" +" PyModuleDef_HEAD_INIT,\n" +" .m_name = \"spam\",\n" +" ...\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_spam(void)\n" +"{\n" +" return PyModule_Create(&spam_module);\n" +"}" +msgstr "" + #: c-api/intro.rst:134 msgid "Return the absolute value of ``x``." msgstr "" @@ -202,6 +223,10 @@ msgstr "" msgid "It must be specified before the function return type. Usage::" msgstr "" +#: c-api/intro.rst:156 +msgid "static inline Py_ALWAYS_INLINE int random(void) { return 4; }" +msgstr "" + #: c-api/intro.rst:162 msgid "" "Argument must be a character or an integer in the range [-128, 127] or [0, " @@ -218,6 +243,10 @@ msgstr "" msgid "Example::" msgstr "" +#: c-api/intro.rst:172 +msgid "Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);" +msgstr "" + #: c-api/intro.rst:174 msgid "MSVC support was added." msgstr "" @@ -251,6 +280,10 @@ msgstr "" msgid "Usage::" msgstr "" +#: c-api/intro.rst:208 +msgid "Py_NO_INLINE static int random(void) { return 4; }" +msgstr "" + #: c-api/intro.rst:214 msgid "" "Convert ``x`` to a C string. E.g. ``Py_STRINGIFY(123)`` returns ``\"123\"``." @@ -304,6 +337,17 @@ msgid "" "without docstrings, as specified in :pep:`7`." msgstr "" +#: c-api/intro.rst:258 +msgid "" +"PyDoc_STRVAR(pop_doc, \"Remove and return the rightmost element.\");\n" +"\n" +"static PyMethodDef deque_methods[] = {\n" +" // ...\n" +" {\"pop\", (PyCFunction)deque_pop, METH_NOARGS, pop_doc},\n" +" // ...\n" +"}" +msgstr "" + #: c-api/intro.rst:268 msgid "" "Creates a docstring for the given input string or an empty string if " @@ -316,6 +360,15 @@ msgid "" "without docstrings, as specified in :pep:`7`." msgstr "" +#: c-api/intro.rst:276 +msgid "" +"static PyMethodDef pysqlite_row_methods[] = {\n" +" {\"keys\", (PyCFunction)pysqlite_row_keys, METH_NOARGS,\n" +" PyDoc_STR(\"Returns the keys of the row.\")},\n" +" {NULL, NULL}\n" +"};" +msgstr "" + #: c-api/intro.rst:286 msgid "Objects, Types and Reference Counts" msgstr "" @@ -465,6 +518,16 @@ msgid "" "below)::" msgstr "" +#: c-api/intro.rst:415 +msgid "" +"PyObject *t;\n" +"\n" +"t = PyTuple_New(3);\n" +"PyTuple_SetItem(t, 0, PyLong_FromLong(1L));\n" +"PyTuple_SetItem(t, 1, PyLong_FromLong(2L));\n" +"PyTuple_SetItem(t, 2, PyUnicode_FromString(\"three\"));" +msgstr "" + #: c-api/intro.rst:422 msgid "" "Here, :c:func:`PyLong_FromLong` returns a new reference which is immediately " @@ -496,6 +559,14 @@ msgid "" "be replaced by the following (which also takes care of the error checking)::" msgstr "" +#: c-api/intro.rst:441 +msgid "" +"PyObject *tuple, *list;\n" +"\n" +"tuple = Py_BuildValue(\"(iis)\", 1, 2, \"three\");\n" +"list = Py_BuildValue(\"[iis]\", 1, 2, \"three\");" +msgstr "" + #: c-api/intro.rst:446 msgid "" "It is much more common to use :c:func:`PyObject_SetItem` and friends with " @@ -507,6 +578,30 @@ msgid "" "sequence) to a given item::" msgstr "" +#: c-api/intro.rst:453 +msgid "" +"int\n" +"set_all(PyObject *target, PyObject *item)\n" +"{\n" +" Py_ssize_t i, n;\n" +"\n" +" n = PyObject_Length(target);\n" +" if (n < 0)\n" +" return -1;\n" +" for (i = 0; i < n; i++) {\n" +" PyObject *index = PyLong_FromSsize_t(i);\n" +" if (!index)\n" +" return -1;\n" +" if (PyObject_SetItem(target, index, item) < 0) {\n" +" Py_DECREF(index);\n" +" return -1;\n" +" }\n" +" Py_DECREF(index);\n" +" }\n" +" return 0;\n" +"}" +msgstr "" + #: c-api/intro.rst:476 msgid "" "The situation is slightly different for function return values. While " @@ -538,6 +633,62 @@ msgid "" "and once using :c:func:`PySequence_GetItem`. ::" msgstr "" +#: c-api/intro.rst:501 +msgid "" +"long\n" +"sum_list(PyObject *list)\n" +"{\n" +" Py_ssize_t i, n;\n" +" long total = 0, value;\n" +" PyObject *item;\n" +"\n" +" n = PyList_Size(list);\n" +" if (n < 0)\n" +" return -1; /* Not a list */\n" +" for (i = 0; i < n; i++) {\n" +" item = PyList_GetItem(list, i); /* Can't fail */\n" +" if (!PyLong_Check(item)) continue; /* Skip non-integers */\n" +" value = PyLong_AsLong(item);\n" +" if (value == -1 && PyErr_Occurred())\n" +" /* Integer too big to fit in a C long, bail out */\n" +" return -1;\n" +" total += value;\n" +" }\n" +" return total;\n" +"}" +msgstr "" + +#: c-api/intro.rst:527 +msgid "" +"long\n" +"sum_sequence(PyObject *sequence)\n" +"{\n" +" Py_ssize_t i, n;\n" +" long total = 0, value;\n" +" PyObject *item;\n" +" n = PySequence_Length(sequence);\n" +" if (n < 0)\n" +" return -1; /* Has no length */\n" +" for (i = 0; i < n; i++) {\n" +" item = PySequence_GetItem(sequence, i);\n" +" if (item == NULL)\n" +" return -1; /* Not a sequence, or other failure */\n" +" if (PyLong_Check(item)) {\n" +" value = PyLong_AsLong(item);\n" +" Py_DECREF(item);\n" +" if (value == -1 && PyErr_Occurred())\n" +" /* Integer too big to fit in a C long, bail out */\n" +" return -1;\n" +" total += value;\n" +" }\n" +" else {\n" +" Py_DECREF(item); /* Discard reference ownership */\n" +" }\n" +" }\n" +" return total;\n" +"}" +msgstr "" + #: c-api/intro.rst:561 msgid "Types" msgstr "" @@ -649,10 +800,66 @@ msgid "" "why you like Python, we show the equivalent Python code::" msgstr "" +#: c-api/intro.rst:655 +msgid "" +"def incr_item(dict, key):\n" +" try:\n" +" item = dict[key]\n" +" except KeyError:\n" +" item = 0\n" +" dict[key] = item + 1" +msgstr "" + #: c-api/intro.rst:664 msgid "Here is the corresponding C code, in all its glory::" msgstr "" +#: c-api/intro.rst:666 +msgid "" +"int\n" +"incr_item(PyObject *dict, PyObject *key)\n" +"{\n" +" /* Objects all initialized to NULL for Py_XDECREF */\n" +" PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;\n" +" int rv = -1; /* Return value initialized to -1 (failure) */\n" +"\n" +" item = PyObject_GetItem(dict, key);\n" +" if (item == NULL) {\n" +" /* Handle KeyError only: */\n" +" if (!PyErr_ExceptionMatches(PyExc_KeyError))\n" +" goto error;\n" +"\n" +" /* Clear the error and use zero: */\n" +" PyErr_Clear();\n" +" item = PyLong_FromLong(0L);\n" +" if (item == NULL)\n" +" goto error;\n" +" }\n" +" const_one = PyLong_FromLong(1L);\n" +" if (const_one == NULL)\n" +" goto error;\n" +"\n" +" incremented_item = PyNumber_Add(item, const_one);\n" +" if (incremented_item == NULL)\n" +" goto error;\n" +"\n" +" if (PyObject_SetItem(dict, key, incremented_item) < 0)\n" +" goto error;\n" +" rv = 0; /* Success */\n" +" /* Continue with cleanup code */\n" +"\n" +" error:\n" +" /* Cleanup code, shared by success and failure path */\n" +"\n" +" /* Use Py_XDECREF() to ignore NULL references */\n" +" Py_XDECREF(item);\n" +" Py_XDECREF(const_one);\n" +" Py_XDECREF(incremented_item);\n" +"\n" +" return rv; /* -1 for error, 0 for success */\n" +"}" +msgstr "" + #: c-api/intro.rst:716 msgid "" "This example represents an endorsed use of the ``goto`` statement in C! It " diff --git a/c-api/iter.po b/c-api/iter.po index 3ec33b3a4..bd06b346e 100644 --- a/c-api/iter.po +++ b/c-api/iter.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2022-12-17 01:28+0300\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -51,6 +51,32 @@ msgid "" "something like this::" msgstr "" +#: c-api/iter.rst:33 +msgid "" +"PyObject *iterator = PyObject_GetIter(obj);\n" +"PyObject *item;\n" +"\n" +"if (iterator == NULL) {\n" +" /* propagate error */\n" +"}\n" +"\n" +"while ((item = PyIter_Next(iterator))) {\n" +" /* do something with item */\n" +" ...\n" +" /* release reference when done */\n" +" Py_DECREF(item);\n" +"}\n" +"\n" +"Py_DECREF(iterator);\n" +"\n" +"if (PyErr_Occurred()) {\n" +" /* propagate error */\n" +"}\n" +"else {\n" +" /* continue doing useful work */\n" +"}" +msgstr "" + #: c-api/iter.rst:59 msgid "" "The enum value used to represent different results of :c:func:`PyIter_Send`." diff --git a/c-api/long.po b/c-api/long.po index 132b2cdff..076f15090 100644 --- a/c-api/long.po +++ b/c-api/long.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-02-24 17:22+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -330,10 +330,21 @@ msgid "" msgstr "" #: c-api/long.rst:329 +msgid "" +"On success, return a read only :term:`named tuple`, that holds information " +"about Python's internal representation of integers. See :data:`sys.int_info` " +"for description of individual fields." +msgstr "" + +#: c-api/long.rst:333 +msgid "On failure, return ``NULL`` with an exception set." +msgstr "" + +#: c-api/long.rst:340 msgid "Return 1 if *op* is compact, 0 otherwise." msgstr "" -#: c-api/long.rst:331 +#: c-api/long.rst:342 msgid "" "This function makes it possible for performance-critical code to implement a " "“fast path” for small integers. For compact values use :c:func:" @@ -342,23 +353,23 @@ msgid "" "` :meth:`int.to_bytes`." msgstr "" -#: c-api/long.rst:337 +#: c-api/long.rst:348 msgid "The speedup is expected to be negligible for most users." msgstr "" -#: c-api/long.rst:339 +#: c-api/long.rst:350 msgid "" "Exactly what values are considered compact is an implementation detail and " "is subject to change." msgstr "" -#: c-api/long.rst:344 +#: c-api/long.rst:358 msgid "" "If *op* is compact, as determined by :c:func:`PyUnstable_Long_IsCompact`, " "return its value." msgstr "" -#: c-api/long.rst:347 +#: c-api/long.rst:361 msgid "Otherwise, the return value is undefined." msgstr "" diff --git a/c-api/memory.po b/c-api/memory.po index 8b2e35b70..79940f62c 100644 --- a/c-api/memory.po +++ b/c-api/memory.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-01 21:53+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -69,6 +69,19 @@ msgid "" "in the following example::" msgstr "" +#: c-api/memory.rst:58 +msgid "" +"PyObject *res;\n" +"char *buf = (char *) malloc(BUFSIZ); /* for I/O */\n" +"\n" +"if (buf == NULL)\n" +" return PyErr_NoMemory();\n" +"...Do some I/O operation involving buf...\n" +"res = PyBytes_FromString(buf);\n" +"free(buf); /* malloc'ed */\n" +"return res;" +msgstr "" + #: c-api/memory.rst:68 msgid "" "In this example, the memory request for the I/O buffer is handled by the C " @@ -1038,10 +1051,36 @@ msgid "" "set::" msgstr "" +#: c-api/memory.rst:706 +msgid "" +"PyObject *res;\n" +"char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */\n" +"\n" +"if (buf == NULL)\n" +" return PyErr_NoMemory();\n" +"/* ...Do some I/O operation involving buf... */\n" +"res = PyBytes_FromString(buf);\n" +"PyMem_Free(buf); /* allocated with PyMem_Malloc */\n" +"return res;" +msgstr "" + #: c-api/memory.rst:716 msgid "The same code using the type-oriented function set::" msgstr "" +#: c-api/memory.rst:718 +msgid "" +"PyObject *res;\n" +"char *buf = PyMem_New(char, BUFSIZ); /* for I/O */\n" +"\n" +"if (buf == NULL)\n" +" return PyErr_NoMemory();\n" +"/* ...Do some I/O operation involving buf... */\n" +"res = PyBytes_FromString(buf);\n" +"PyMem_Del(buf); /* allocated with PyMem_New */\n" +"return res;" +msgstr "" + #: c-api/memory.rst:728 msgid "" "Note that in the two examples above, the buffer is always manipulated via " @@ -1052,6 +1091,17 @@ msgid "" "different allocators operating on different heaps. ::" msgstr "" +#: c-api/memory.rst:735 +msgid "" +"char *buf1 = PyMem_New(char, BUFSIZ);\n" +"char *buf2 = (char *) malloc(BUFSIZ);\n" +"char *buf3 = (char *) PyMem_Malloc(BUFSIZ);\n" +"...\n" +"PyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */\n" +"free(buf2); /* Right -- allocated via malloc() */\n" +"free(buf1); /* Fatal -- should be PyMem_Del() */" +msgstr "" + #: c-api/memory.rst:743 msgid "" "In addition to the functions aimed at handling raw memory blocks from the " diff --git a/c-api/module.po b/c-api/module.po index 3cbb39770..3669cf476 100644 --- a/c-api/module.po +++ b/c-api/module.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -40,28 +40,30 @@ msgstr "" #: c-api/module.rst:40 msgid "" -"Return a new module object with the :attr:`__name__` attribute set to " -"*name*. The module's :attr:`__name__`, :attr:`__doc__`, :attr:`__package__`, " -"and :attr:`__loader__` attributes are filled in (all but :attr:`__name__` " -"are set to ``None``); the caller is responsible for providing a :attr:" -"`__file__` attribute." +"Return a new module object with :attr:`module.__name__` set to *name*. The " +"module's :attr:`!__name__`, :attr:`~module.__doc__`, :attr:`~module." +"__package__` and :attr:`~module.__loader__` attributes are filled in (all " +"but :attr:`!__name__` are set to ``None``). The caller is responsible for " +"setting a :attr:`~module.__file__` attribute." msgstr "" -#: c-api/module.rst:270 c-api/module.rst:445 +#: c-api/module.rst:272 c-api/module.rst:447 msgid "Return ``NULL`` with an exception set on error." msgstr "" #: c-api/module.rst:50 -msgid ":attr:`__package__` and :attr:`__loader__` are set to ``None``." +msgid "" +":attr:`~module.__package__` and :attr:`~module.__loader__` are now set to " +"``None``." msgstr "" -#: c-api/module.rst:56 +#: c-api/module.rst:57 msgid "" "Similar to :c:func:`PyModule_NewObject`, but the name is a UTF-8 encoded " "string instead of a Unicode object." msgstr "" -#: c-api/module.rst:64 +#: c-api/module.rst:65 msgid "" "Return the dictionary object that implements *module*'s namespace; this " "object is the same as the :attr:`~object.__dict__` attribute of the module " @@ -69,64 +71,64 @@ msgid "" "object), :exc:`SystemError` is raised and ``NULL`` is returned." msgstr "" -#: c-api/module.rst:69 +#: c-api/module.rst:70 msgid "" "It is recommended extensions use other ``PyModule_*`` and ``PyObject_*`` " "functions rather than directly manipulate a module's :attr:`~object." "__dict__`." msgstr "" -#: c-api/module.rst:80 +#: c-api/module.rst:81 msgid "" -"Return *module*'s :attr:`__name__` value. If the module does not provide " -"one, or if it is not a string, :exc:`SystemError` is raised and ``NULL`` is " -"returned." +"Return *module*'s :attr:`~module.__name__` value. If the module does not " +"provide one, or if it is not a string, :exc:`SystemError` is raised and " +"``NULL`` is returned." msgstr "" -#: c-api/module.rst:88 +#: c-api/module.rst:90 msgid "" "Similar to :c:func:`PyModule_GetNameObject` but return the name encoded to " "``'utf-8'``." msgstr "" -#: c-api/module.rst:93 +#: c-api/module.rst:95 msgid "" "Return the \"state\" of the module, that is, a pointer to the block of " "memory allocated at module creation time, or ``NULL``. See :c:member:" "`PyModuleDef.m_size`." msgstr "" -#: c-api/module.rst:100 +#: c-api/module.rst:102 msgid "" "Return a pointer to the :c:type:`PyModuleDef` struct from which the module " "was created, or ``NULL`` if the module wasn't created from a definition." msgstr "" -#: c-api/module.rst:110 +#: c-api/module.rst:112 msgid "" "Return the name of the file from which *module* was loaded using *module*'s :" -"attr:`__file__` attribute. If this is not defined, or if it is not a " -"unicode string, raise :exc:`SystemError` and return ``NULL``; otherwise " -"return a reference to a Unicode object." +"attr:`~module.__file__` attribute. If this is not defined, or if it is not " +"a string, raise :exc:`SystemError` and return ``NULL``; otherwise return a " +"reference to a Unicode object." msgstr "" -#: c-api/module.rst:120 +#: c-api/module.rst:122 msgid "" "Similar to :c:func:`PyModule_GetFilenameObject` but return the filename " "encoded to 'utf-8'." msgstr "" -#: c-api/module.rst:123 +#: c-api/module.rst:125 msgid "" ":c:func:`PyModule_GetFilename` raises :exc:`UnicodeEncodeError` on " "unencodable filenames, use :c:func:`PyModule_GetFilenameObject` instead." msgstr "" -#: c-api/module.rst:131 +#: c-api/module.rst:133 msgid "Initializing C modules" msgstr "" -#: c-api/module.rst:133 +#: c-api/module.rst:135 msgid "" "Modules objects are usually created from extension modules (shared libraries " "which export an initialization function), or compiled-in modules (where the " @@ -134,55 +136,55 @@ msgid "" "See :ref:`building` or :ref:`extending-with-embedding` for details." msgstr "" -#: c-api/module.rst:138 +#: c-api/module.rst:140 msgid "" "The initialization function can either pass a module definition instance to :" "c:func:`PyModule_Create`, and return the resulting module object, or request " "\"multi-phase initialization\" by returning the definition struct itself." msgstr "" -#: c-api/module.rst:144 +#: c-api/module.rst:146 msgid "" "The module definition struct, which holds all information needed to create a " "module object. There is usually only one statically initialized variable of " "this type for each module." msgstr "" -#: c-api/module.rst:150 +#: c-api/module.rst:152 msgid "Always initialize this member to :c:macro:`PyModuleDef_HEAD_INIT`." msgstr "" -#: c-api/module.rst:154 +#: c-api/module.rst:156 msgid "Name for the new module." msgstr "" -#: c-api/module.rst:158 +#: c-api/module.rst:160 msgid "" "Docstring for the module; usually a docstring variable created with :c:macro:" "`PyDoc_STRVAR` is used." msgstr "" -#: c-api/module.rst:163 +#: c-api/module.rst:165 msgid "" "Module state may be kept in a per-module memory area that can be retrieved " "with :c:func:`PyModule_GetState`, rather than in static globals. This makes " "modules safe for use in multiple sub-interpreters." msgstr "" -#: c-api/module.rst:167 +#: c-api/module.rst:169 msgid "" "This memory area is allocated based on *m_size* on module creation, and " "freed when the module object is deallocated, after the :c:member:" "`~PyModuleDef.m_free` function has been called, if present." msgstr "" -#: c-api/module.rst:171 +#: c-api/module.rst:173 msgid "" "Setting ``m_size`` to ``-1`` means that the module does not support sub-" "interpreters, because it has global state." msgstr "" -#: c-api/module.rst:174 +#: c-api/module.rst:176 msgid "" "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 " @@ -190,36 +192,36 @@ msgid "" "initialization." msgstr "" -#: c-api/module.rst:179 +#: c-api/module.rst:181 msgid "See :PEP:`3121` for more details." msgstr "" -#: c-api/module.rst:183 +#: c-api/module.rst:185 msgid "" "A pointer to a table of module-level functions, described by :c:type:" "`PyMethodDef` values. Can be ``NULL`` if no functions are present." msgstr "" -#: c-api/module.rst:188 +#: c-api/module.rst:190 msgid "" "An array of slot definitions for multi-phase initialization, terminated by a " "``{0, NULL}`` entry. When using single-phase initialization, *m_slots* must " "be ``NULL``." msgstr "" -#: c-api/module.rst:194 +#: c-api/module.rst:196 msgid "" "Prior to version 3.5, this member was always set to ``NULL``, and was " "defined as:" msgstr "" -#: c-api/module.rst:201 +#: c-api/module.rst:203 msgid "" "A traversal function to call during GC traversal of the module object, or " "``NULL`` if not needed." msgstr "" -#: c-api/module.rst:219 c-api/module.rst:240 +#: c-api/module.rst:221 c-api/module.rst:242 msgid "" "This function is not called if the module state was requested but is not " "allocated yet. This is the case immediately after the module is created and " @@ -229,17 +231,17 @@ msgid "" "`PyModule_GetState`) is ``NULL``." msgstr "" -#: c-api/module.rst:232 c-api/module.rst:247 +#: c-api/module.rst:234 c-api/module.rst:249 msgid "No longer called before the module state is allocated." msgstr "" -#: c-api/module.rst:216 +#: c-api/module.rst:218 msgid "" "A clear function to call during GC clearing of the module object, or " "``NULL`` if not needed." msgstr "" -#: c-api/module.rst:226 +#: c-api/module.rst:228 msgid "" "Like :c:member:`PyTypeObject.tp_clear`, this function is not *always* called " "before a module is deallocated. For example, when reference counting is " @@ -248,55 +250,55 @@ msgid "" "directly." msgstr "" -#: c-api/module.rst:237 +#: c-api/module.rst:239 msgid "" "A function to call during deallocation of the module object, or ``NULL`` if " "not needed." msgstr "" -#: c-api/module.rst:251 +#: c-api/module.rst:253 msgid "Single-phase initialization" msgstr "" -#: c-api/module.rst:253 +#: c-api/module.rst:255 msgid "" "The module initialization function may create and return the module object " "directly. This is referred to as \"single-phase initialization\", and uses " "one of the following two module creation functions:" msgstr "" -#: c-api/module.rst:259 +#: c-api/module.rst:261 msgid "" "Create a new module object, given the definition in *def*. This behaves " "like :c:func:`PyModule_Create2` with *module_api_version* set to :c:macro:" "`PYTHON_API_VERSION`." msgstr "" -#: c-api/module.rst:266 +#: c-api/module.rst:268 msgid "" "Create a new module object, given the definition in *def*, assuming the API " "version *module_api_version*. If that version does not match the version of " "the running interpreter, a :exc:`RuntimeWarning` is emitted." msgstr "" -#: c-api/module.rst:274 +#: c-api/module.rst:276 msgid "" "Most uses of this function should be using :c:func:`PyModule_Create` " "instead; only use this if you are sure you need it." msgstr "" -#: c-api/module.rst:277 +#: c-api/module.rst:279 msgid "" "Before it is returned from in the initialization function, the resulting " "module object is typically populated using functions like :c:func:" "`PyModule_AddObjectRef`." msgstr "" -#: c-api/module.rst:283 +#: c-api/module.rst:285 msgid "Multi-phase initialization" msgstr "" -#: c-api/module.rst:285 +#: c-api/module.rst:287 msgid "" "An alternate way to specify extensions is to request \"multi-phase " "initialization\". Extension modules created this way behave more like Python " @@ -306,7 +308,7 @@ msgid "" "__init__` methods of classes." msgstr "" -#: c-api/module.rst:292 +#: c-api/module.rst:294 msgid "" "Unlike modules created using single-phase initialization, these modules are " "not singletons: if the *sys.modules* entry is removed and the module is re-" @@ -319,14 +321,14 @@ msgid "" "__dict__` or individual classes created with :c:func:`PyType_FromSpec`)." msgstr "" -#: c-api/module.rst:302 +#: c-api/module.rst:304 msgid "" "All modules created using multi-phase initialization are expected to " "support :ref:`sub-interpreters `. Making sure " "multiple modules are independent is typically enough to achieve this." msgstr "" -#: c-api/module.rst:306 +#: c-api/module.rst:308 msgid "" "To request multi-phase initialization, the initialization function " "(PyInit_modulename) returns a :c:type:`PyModuleDef` instance with non-empty :" @@ -334,65 +336,65 @@ msgid "" "instance must be initialized with the following function:" msgstr "" -#: c-api/module.rst:313 +#: c-api/module.rst:315 msgid "" "Ensures a module definition is a properly initialized Python object that " "correctly reports its type and reference count." msgstr "" -#: c-api/module.rst:316 +#: c-api/module.rst:318 msgid "Returns *def* cast to ``PyObject*``, or ``NULL`` if an error occurred." msgstr "" -#: c-api/module.rst:320 +#: c-api/module.rst:322 msgid "" "The *m_slots* member of the module definition must point to an array of " "``PyModuleDef_Slot`` structures:" msgstr "" -#: c-api/module.rst:327 +#: c-api/module.rst:329 msgid "A slot ID, chosen from the available values explained below." msgstr "" -#: c-api/module.rst:331 +#: c-api/module.rst:333 msgid "Value of the slot, whose meaning depends on the slot ID." msgstr "" -#: c-api/module.rst:335 +#: c-api/module.rst:337 msgid "The *m_slots* array must be terminated by a slot with id 0." msgstr "" -#: c-api/module.rst:337 +#: c-api/module.rst:339 msgid "The available slot types are:" msgstr "" -#: c-api/module.rst:341 +#: c-api/module.rst:343 msgid "" "Specifies a function that is called to create the module object itself. The " "*value* pointer of this slot must point to a function of the signature:" msgstr "" -#: c-api/module.rst:348 +#: c-api/module.rst:350 msgid "" "The function receives a :py:class:`~importlib.machinery.ModuleSpec` " "instance, as defined in :PEP:`451`, and the module definition. It should " "return a new module object, or set an error and return ``NULL``." msgstr "" -#: c-api/module.rst:353 +#: c-api/module.rst:355 msgid "" "This function should be kept minimal. In particular, it should not call " "arbitrary Python code, as trying to import the same module again may result " "in an infinite loop." msgstr "" -#: c-api/module.rst:357 +#: c-api/module.rst:359 msgid "" "Multiple ``Py_mod_create`` slots may not be specified in one module " "definition." msgstr "" -#: c-api/module.rst:360 +#: c-api/module.rst:362 msgid "" "If ``Py_mod_create`` is not specified, the import machinery will create a " "normal module object using :c:func:`PyModule_New`. The name is taken from " @@ -401,7 +403,7 @@ msgid "" "through symlinks, all while sharing a single module definition." msgstr "" -#: c-api/module.rst:366 +#: c-api/module.rst:368 msgid "" "There is no requirement for the returned object to be an instance of :c:type:" "`PyModule_Type`. Any type can be used, as long as it supports setting and " @@ -411,7 +413,7 @@ msgid "" "``Py_mod_create``." msgstr "" -#: c-api/module.rst:375 +#: c-api/module.rst:377 msgid "" "Specifies a function that is called to *execute* the module. This is " "equivalent to executing the code of a Python module: typically, this " @@ -419,59 +421,59 @@ msgid "" "function is:" msgstr "" -#: c-api/module.rst:384 +#: c-api/module.rst:386 msgid "" "If multiple ``Py_mod_exec`` slots are specified, they are processed in the " "order they appear in the *m_slots* array." msgstr "" -#: c-api/module.rst:389 +#: c-api/module.rst:391 msgid "Specifies one of the following values:" msgstr "" -#: c-api/module.rst:395 +#: c-api/module.rst:397 msgid "The module does not support being imported in subinterpreters." msgstr "" -#: c-api/module.rst:399 +#: c-api/module.rst:401 msgid "" "The module supports being imported in subinterpreters, but only when they " "share the main interpreter's GIL. (See :ref:`isolating-extensions-howto`.)" msgstr "" -#: c-api/module.rst:405 +#: c-api/module.rst:407 msgid "" "The module supports being imported in subinterpreters, even when they have " "their own GIL. (See :ref:`isolating-extensions-howto`.)" msgstr "" -#: c-api/module.rst:409 +#: c-api/module.rst:411 msgid "" "This slot determines whether or not importing this module in a " "subinterpreter will fail." msgstr "" -#: c-api/module.rst:412 +#: c-api/module.rst:414 msgid "" "Multiple ``Py_mod_multiple_interpreters`` slots may not be specified in one " "module definition." msgstr "" -#: c-api/module.rst:415 +#: c-api/module.rst:417 msgid "" "If ``Py_mod_multiple_interpreters`` is not specified, the import machinery " "defaults to ``Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED``." msgstr "" -#: c-api/module.rst:420 +#: c-api/module.rst:422 msgid "See :PEP:`489` for more details on multi-phase initialization." msgstr "" -#: c-api/module.rst:423 +#: c-api/module.rst:425 msgid "Low-level module creation functions" msgstr "" -#: c-api/module.rst:425 +#: c-api/module.rst:427 msgid "" "The following functions are called under the hood when using multi-phase " "initialization. They can be used directly, for example when creating module " @@ -479,14 +481,14 @@ msgid "" "``PyModule_ExecDef`` must be called to fully initialize a module." msgstr "" -#: c-api/module.rst:432 +#: c-api/module.rst:434 msgid "" "Create a new module object, given the definition in *def* and the ModuleSpec " "*spec*. This behaves like :c:func:`PyModule_FromDefAndSpec2` with " "*module_api_version* set to :c:macro:`PYTHON_API_VERSION`." msgstr "" -#: c-api/module.rst:440 +#: c-api/module.rst:442 msgid "" "Create a new module object, given the definition in *def* and the ModuleSpec " "*spec*, assuming the API version *module_api_version*. If that version does " @@ -494,24 +496,24 @@ msgid "" "emitted." msgstr "" -#: c-api/module.rst:449 +#: c-api/module.rst:451 msgid "" "Most uses of this function should be using :c:func:`PyModule_FromDefAndSpec` " "instead; only use this if you are sure you need it." msgstr "" -#: c-api/module.rst:456 +#: c-api/module.rst:458 msgid "Process any execution slots (:c:data:`Py_mod_exec`) given in *def*." msgstr "" -#: c-api/module.rst:462 +#: c-api/module.rst:464 msgid "" "Set the docstring for *module* to *docstring*. This function is called " "automatically when creating a module from ``PyModuleDef``, using either " "``PyModule_Create`` or ``PyModule_FromDefAndSpec``." msgstr "" -#: c-api/module.rst:471 +#: c-api/module.rst:473 msgid "" "Add the functions from the ``NULL`` terminated *functions* array to " "*module*. Refer to the :c:type:`PyMethodDef` documentation for details on " @@ -523,11 +525,11 @@ msgid "" "``PyModule_FromDefAndSpec``." msgstr "" -#: c-api/module.rst:483 +#: c-api/module.rst:485 msgid "Support functions" msgstr "" -#: c-api/module.rst:485 +#: c-api/module.rst:487 msgid "" "The module initialization function (if using single phase initialization) or " "a function called from a module execution slot (if using multi-phase " @@ -535,72 +537,150 @@ msgid "" "module state:" msgstr "" -#: c-api/module.rst:492 +#: c-api/module.rst:494 msgid "" "Add an object to *module* as *name*. This is a convenience function which " "can be used from the module's initialization function." msgstr "" -#: c-api/module.rst:495 +#: c-api/module.rst:497 msgid "" "On success, return ``0``. On error, raise an exception and return ``-1``." msgstr "" -#: c-api/module.rst:497 +#: c-api/module.rst:499 msgid "" "Return ``-1`` if *value* is ``NULL``. It must be called with an exception " "raised in this case." msgstr "" -#: c-api/module.rst:549 +#: c-api/module.rst:559 msgid "Example usage::" msgstr "" -#: c-api/module.rst:567 +#: c-api/module.rst:504 +msgid "" +"static int\n" +"add_spam(PyObject *module, int value)\n" +"{\n" +" PyObject *obj = PyLong_FromLong(value);\n" +" if (obj == NULL) {\n" +" return -1;\n" +" }\n" +" int res = PyModule_AddObjectRef(module, \"spam\", obj);\n" +" Py_DECREF(obj);\n" +" return res;\n" +" }" +msgstr "" + +#: c-api/module.rst:577 msgid "" "The example can also be written without checking explicitly if *obj* is " "``NULL``::" msgstr "" -#: c-api/module.rst:583 +#: c-api/module.rst:519 +msgid "" +"static int\n" +"add_spam(PyObject *module, int value)\n" +"{\n" +" PyObject *obj = PyLong_FromLong(value);\n" +" int res = PyModule_AddObjectRef(module, \"spam\", obj);\n" +" Py_XDECREF(obj);\n" +" return res;\n" +" }" +msgstr "" + +#: c-api/module.rst:593 msgid "" "Note that ``Py_XDECREF()`` should be used instead of ``Py_DECREF()`` in this " "case, since *obj* can be ``NULL``." msgstr "" -#: c-api/module.rst:534 +#: c-api/module.rst:531 +msgid "" +"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 :c:func:" +"`PyUnicode_FromString` and :c:func:`PyObject_SetAttr` directly. For more " +"details, see :c:func:`PyUnicode_InternFromString`, which may be used " +"internally to create a key object." +msgstr "" + +#: c-api/module.rst:544 msgid "" "Similar to :c:func:`PyModule_AddObjectRef`, but steals a reference to " "*value* on success (if it returns ``0``)." msgstr "" -#: c-api/module.rst:537 +#: c-api/module.rst:547 msgid "" "The new :c:func:`PyModule_AddObjectRef` function is recommended, since it is " "easy to introduce reference leaks by misusing the :c:func:" "`PyModule_AddObject` function." msgstr "" -#: c-api/module.rst:543 +#: c-api/module.rst:553 msgid "" "Unlike other functions that steal references, ``PyModule_AddObject()`` only " "releases the reference to *value* **on success**." msgstr "" -#: c-api/module.rst:546 +#: c-api/module.rst:556 msgid "" "This means that its return value must be checked, and calling code must :c:" "func:`Py_DECREF` *value* manually on error." msgstr "" -#: c-api/module.rst:589 +#: c-api/module.rst:561 +msgid "" +"static int\n" +"add_spam(PyObject *module, int value)\n" +"{\n" +" PyObject *obj = PyLong_FromLong(value);\n" +" if (obj == NULL) {\n" +" return -1;\n" +" }\n" +" if (PyModule_AddObject(module, \"spam\", obj) < 0) {\n" +" Py_DECREF(obj);\n" +" return -1;\n" +" }\n" +" // PyModule_AddObject() stole a reference to obj:\n" +" // Py_DECREF(obj) is not needed here\n" +" return 0;\n" +"}" +msgstr "" + +#: c-api/module.rst:580 +msgid "" +"static int\n" +"add_spam(PyObject *module, int value)\n" +"{\n" +" PyObject *obj = PyLong_FromLong(value);\n" +" if (PyModule_AddObject(module, \"spam\", obj) < 0) {\n" +" Py_XDECREF(obj);\n" +" return -1;\n" +" }\n" +" // PyModule_AddObject() stole a reference to obj:\n" +" // Py_DECREF(obj) is not needed here\n" +" return 0;\n" +"}" +msgstr "" + +#: c-api/module.rst:599 msgid "" "Add an integer constant to *module* as *name*. This convenience function " "can be used from the module's initialization function. Return ``-1`` with an " "exception set on error, ``0`` on success." msgstr "" -#: c-api/module.rst:596 +#: c-api/module.rst:603 +msgid "" +"This is a convenience function that calls :c:func:`PyLong_FromLong` and :c:" +"func:`PyModule_AddObjectRef`; see their documentation for details." +msgstr "" + +#: c-api/module.rst:609 msgid "" "Add a string constant to *module* as *name*. This convenience function can " "be used from the module's initialization function. The string *value* must " @@ -608,7 +688,14 @@ msgid "" "on success." msgstr "" -#: c-api/module.rst:604 +#: c-api/module.rst:614 +msgid "" +"This is a convenience function that calls :c:func:" +"`PyUnicode_InternFromString` and :c:func:`PyModule_AddObjectRef`; see their " +"documentation for details." +msgstr "" + +#: c-api/module.rst:621 msgid "" "Add an int constant to *module*. The name and the value are taken from " "*macro*. For example ``PyModule_AddIntMacro(module, AF_INET)`` adds the int " @@ -616,11 +703,11 @@ msgid "" "with an exception set on error, ``0`` on success." msgstr "" -#: c-api/module.rst:612 +#: c-api/module.rst:629 msgid "Add a string constant to *module*." msgstr "" -#: c-api/module.rst:616 +#: c-api/module.rst:633 msgid "" "Add a type object to *module*. The type object is finalized by calling " "internally :c:func:`PyType_Ready`. The name of the type object is taken from " @@ -628,25 +715,25 @@ msgid "" "``-1`` with an exception set on error, ``0`` on success." msgstr "" -#: c-api/module.rst:626 +#: c-api/module.rst:643 msgid "Module lookup" msgstr "" -#: c-api/module.rst:628 +#: c-api/module.rst:645 msgid "" "Single-phase initialization 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." msgstr "" -#: c-api/module.rst:632 +#: c-api/module.rst:649 msgid "" "These functions will not work on modules created using multi-phase " "initialization, since multiple such modules can be created from a single " "definition." msgstr "" -#: c-api/module.rst:637 +#: c-api/module.rst:654 msgid "" "Returns the module object that was created from *def* for the current " "interpreter. This method requires that the module object has been attached " @@ -655,18 +742,18 @@ msgid "" "to the interpreter state yet, it returns ``NULL``." msgstr "" -#: c-api/module.rst:644 +#: c-api/module.rst:661 msgid "" "Attaches the module object passed to the function to the interpreter state. " "This allows the module object to be accessible via :c:func:" "`PyState_FindModule`." msgstr "" -#: c-api/module.rst:647 +#: c-api/module.rst:664 msgid "Only effective on modules created using single-phase initialization." msgstr "" -#: c-api/module.rst:649 +#: c-api/module.rst:666 msgid "" "Python calls ``PyState_AddModule`` automatically after importing a module, " "so it is unnecessary (but harmless) to call it from module initialization " @@ -677,15 +764,15 @@ msgid "" "state updates)." msgstr "" -#: c-api/module.rst:668 +#: c-api/module.rst:685 msgid "The caller must hold the GIL." msgstr "" -#: c-api/module.rst:659 +#: c-api/module.rst:676 msgid "Return ``-1`` with an exception set on error, ``0`` on success." msgstr "" -#: c-api/module.rst:665 +#: c-api/module.rst:682 msgid "" "Removes the module object created from *def* from the interpreter state. " "Return ``-1`` with an exception set on error, ``0`` on success." @@ -703,7 +790,7 @@ msgstr "" msgid "ModuleType (in module types)" msgstr "" -#: c-api/module.rst:76 +#: c-api/module.rst:77 msgid "__name__ (module attribute)" msgstr "" @@ -711,7 +798,7 @@ msgstr "" msgid "__doc__ (module attribute)" msgstr "" -#: c-api/module.rst:106 +#: c-api/module.rst:108 msgid "__file__ (module attribute)" msgstr "" @@ -723,10 +810,10 @@ msgstr "" msgid "__loader__ (module attribute)" msgstr "" -#: c-api/module.rst:62 +#: c-api/module.rst:63 msgid "__dict__ (module attribute)" msgstr "" -#: c-api/module.rst:106 +#: c-api/module.rst:108 msgid "SystemError (built-in exception)" msgstr "" diff --git a/c-api/object.po b/c-api/object.po index d2ed376c3..90f26d646 100644 --- a/c-api/object.po +++ b/c-api/object.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -128,7 +128,17 @@ msgid "" "in favour of using :c:func:`PyObject_DelAttrString`." msgstr "" -#: c-api/object.rst:113 +#: c-api/object.rst:110 +msgid "" +"The number of different attribute names passed to this function should be " +"kept small, usually by using a statically allocated string as *attr_name*. " +"For attribute names that aren't known at compile time, prefer calling :c:" +"func:`PyUnicode_FromString` and :c:func:`PyObject_SetAttr` directly. For " +"more details, see :c:func:`PyUnicode_InternFromString`, which may be used " +"internally to create a key object." +msgstr "" + +#: c-api/object.rst:120 msgid "" "Generic attribute setter and deleter function that is meant to be put into a " "type object's :c:member:`~PyTypeObject.tp_setattro` slot. It looks for a " @@ -140,26 +150,36 @@ msgid "" "returned." msgstr "" -#: c-api/object.rst:125 +#: c-api/object.rst:132 msgid "" "Delete attribute named *attr_name*, for object *o*. Returns ``-1`` on " "failure. This is the equivalent of the Python statement ``del o.attr_name``." msgstr "" -#: c-api/object.rst:131 +#: c-api/object.rst:138 msgid "" "This is the same as :c:func:`PyObject_DelAttr`, but *attr_name* is specified " "as a :c:expr:`const char*` UTF-8 encoded bytes string, rather than a :c:expr:" "`PyObject*`." msgstr "" -#: c-api/object.rst:138 +#: c-api/object.rst:142 +msgid "" +"The number of different attribute names passed to this function should be " +"kept small, usually by using a statically allocated string as *attr_name*. " +"For attribute names that aren't known at compile time, prefer calling :c:" +"func:`PyUnicode_FromString` and :c:func:`PyObject_DelAttr` directly. For " +"more details, see :c:func:`PyUnicode_InternFromString`, which may be used " +"internally to create a key object for lookup." +msgstr "" + +#: c-api/object.rst:153 msgid "" "A generic implementation for the getter of a ``__dict__`` descriptor. It " "creates the dictionary if necessary." msgstr "" -#: c-api/object.rst:141 +#: c-api/object.rst:156 msgid "" "This function may also be called to get the :py:attr:`~object.__dict__` of " "the object *o*. Pass ``NULL`` for *context* when calling it. Since this " @@ -168,30 +188,30 @@ msgid "" "the object." msgstr "" -#: c-api/object.rst:147 +#: c-api/object.rst:162 msgid "On failure, returns ``NULL`` with an exception set." msgstr "" -#: c-api/object.rst:154 +#: c-api/object.rst:169 msgid "" "A generic implementation for the setter of a ``__dict__`` descriptor. This " "implementation does not allow the dictionary to be deleted." msgstr "" -#: c-api/object.rst:162 +#: c-api/object.rst:177 msgid "" "Return a pointer to :py:attr:`~object.__dict__` of the object *obj*. If " "there is no ``__dict__``, return ``NULL`` without setting an exception." msgstr "" -#: c-api/object.rst:165 +#: c-api/object.rst:180 msgid "" "This function may need to allocate memory for the dictionary, so it may be " "more efficient to call :c:func:`PyObject_GetAttr` when accessing an " "attribute on the object." msgstr "" -#: c-api/object.rst:172 +#: c-api/object.rst:187 msgid "" "Compare the values of *o1* and *o2* using the operation specified by *opid*, " "which must be one of :c:macro:`Py_LT`, :c:macro:`Py_LE`, :c:macro:`Py_EQ`, :" @@ -202,33 +222,33 @@ msgid "" "success, or ``NULL`` on failure." msgstr "" -#: c-api/object.rst:182 +#: c-api/object.rst:197 msgid "" "Compare the values of *o1* and *o2* using the operation specified by *opid*, " "like :c:func:`PyObject_RichCompare`, but returns ``-1`` on error, ``0`` if " "the result is false, ``1`` otherwise." msgstr "" -#: c-api/object.rst:187 +#: c-api/object.rst:202 msgid "" "If *o1* and *o2* are the same object, :c:func:`PyObject_RichCompareBool` " "will always return ``1`` for :c:macro:`Py_EQ` and ``0`` for :c:macro:`Py_NE`." msgstr "" -#: c-api/object.rst:192 +#: c-api/object.rst:207 msgid "" "Format *obj* using *format_spec*. This is equivalent to the Python " "expression ``format(obj, format_spec)``." msgstr "" -#: c-api/object.rst:195 +#: c-api/object.rst:210 msgid "" "*format_spec* may be ``NULL``. In this case the call is equivalent to " "``format(obj)``. Returns the formatted string on success, ``NULL`` on " "failure." msgstr "" -#: c-api/object.rst:203 +#: c-api/object.rst:218 msgid "" "Compute a string representation of object *o*. Returns the string " "representation on success, ``NULL`` on failure. This is the equivalent of " @@ -236,13 +256,13 @@ msgid "" "function." msgstr "" -#: c-api/object.rst:231 +#: c-api/object.rst:246 msgid "" "This function now includes a debug assertion to help ensure that it does not " "silently discard an active exception." msgstr "" -#: c-api/object.rst:215 +#: c-api/object.rst:230 msgid "" "As :c:func:`PyObject_Repr`, compute a string representation of object *o*, " "but escape the non-ASCII characters in the string returned by :c:func:" @@ -251,7 +271,7 @@ msgid "" "Called by the :func:`ascii` built-in function." msgstr "" -#: c-api/object.rst:226 +#: c-api/object.rst:241 msgid "" "Compute a string representation of object *o*. Returns the string " "representation on success, ``NULL`` on failure. This is the equivalent of " @@ -259,7 +279,7 @@ msgid "" "function and, therefore, by the :func:`print` function." msgstr "" -#: c-api/object.rst:240 +#: c-api/object.rst:255 msgid "" "Compute a bytes representation of object *o*. ``NULL`` is returned on " "failure and a bytes object on success. This is equivalent to the Python " @@ -268,73 +288,73 @@ msgid "" "bytes object." msgstr "" -#: c-api/object.rst:249 +#: c-api/object.rst:264 msgid "" "Return ``1`` if the class *derived* is identical to or derived from the " "class *cls*, otherwise return ``0``. In case of an error, return ``-1``." msgstr "" -#: c-api/object.rst:271 +#: c-api/object.rst:286 msgid "" "If *cls* is a tuple, the check will be done against every entry in *cls*. " "The result will be ``1`` when at least one of the checks returns ``1``, " "otherwise it will be ``0``." msgstr "" -#: c-api/object.rst:256 +#: c-api/object.rst:271 msgid "" -"If *cls* has a :meth:`~class.__subclasscheck__` method, it will be called to " +"If *cls* has a :meth:`~type.__subclasscheck__` method, it will be called to " "determine the subclass status as described in :pep:`3119`. Otherwise, " "*derived* is a subclass of *cls* if it is a direct or indirect subclass, i." -"e. contained in ``cls.__mro__``." +"e. contained in :attr:`cls.__mro__ `." msgstr "" -#: c-api/object.rst:261 +#: c-api/object.rst:276 msgid "" "Normally only class objects, i.e. instances of :class:`type` or a derived " "class, are considered classes. However, objects can override this by having " -"a :attr:`~class.__bases__` attribute (which must be a tuple of base classes)." +"a :attr:`~type.__bases__` attribute (which must be a tuple of base classes)." msgstr "" -#: c-api/object.rst:268 +#: c-api/object.rst:283 msgid "" "Return ``1`` if *inst* is an instance of the class *cls* or a subclass of " "*cls*, or ``0`` if not. On error, returns ``-1`` and sets an exception." msgstr "" -#: c-api/object.rst:275 +#: c-api/object.rst:290 msgid "" -"If *cls* has a :meth:`~class.__instancecheck__` method, it will be called to " +"If *cls* has a :meth:`~type.__instancecheck__` method, it will be called to " "determine the subclass status as described in :pep:`3119`. Otherwise, " "*inst* is an instance of *cls* if its class is a subclass of *cls*." msgstr "" -#: c-api/object.rst:279 +#: c-api/object.rst:294 msgid "" "An instance *inst* can override what is considered its class by having a :" -"attr:`~instance.__class__` attribute." +"attr:`~object.__class__` attribute." msgstr "" -#: c-api/object.rst:282 +#: c-api/object.rst:297 msgid "" "An object *cls* can override if it is considered a class, and what its base " -"classes are, by having a :attr:`~class.__bases__` attribute (which must be a " +"classes are, by having a :attr:`~type.__bases__` attribute (which must be a " "tuple of base classes)." msgstr "" -#: c-api/object.rst:291 +#: c-api/object.rst:306 msgid "" "Compute and return the hash value of an object *o*. On failure, return " "``-1``. This is the equivalent of the Python expression ``hash(o)``." msgstr "" -#: c-api/object.rst:294 +#: c-api/object.rst:309 msgid "" "The return type is now Py_hash_t. This is a signed integer the same size " "as :c:type:`Py_ssize_t`." msgstr "" -#: c-api/object.rst:301 +#: c-api/object.rst:316 msgid "" "Set a :exc:`TypeError` indicating that ``type(o)`` is not :term:`hashable` " "and return ``-1``. This function receives special treatment when stored in a " @@ -342,21 +362,21 @@ msgid "" "that it is not hashable." msgstr "" -#: c-api/object.rst:309 +#: c-api/object.rst:324 msgid "" "Returns ``1`` if the object *o* is considered to be true, and ``0`` " "otherwise. This is equivalent to the Python expression ``not not o``. On " "failure, return ``-1``." msgstr "" -#: c-api/object.rst:316 +#: c-api/object.rst:331 msgid "" "Returns ``0`` if the object *o* is considered to be true, and ``1`` " "otherwise. This is equivalent to the Python expression ``not o``. On " "failure, return ``-1``." msgstr "" -#: c-api/object.rst:325 +#: c-api/object.rst:340 msgid "" "When *o* is non-``NULL``, returns a type object corresponding to the object " "type of object *o*. On failure, raises :exc:`SystemError` and returns " @@ -367,13 +387,13 @@ msgid "" "when a new :term:`strong reference` is needed." msgstr "" -#: c-api/object.rst:337 +#: c-api/object.rst:352 msgid "" "Return non-zero if the object *o* is of type *type* or a subtype of *type*, " "and ``0`` otherwise. Both parameters must be non-``NULL``." msgstr "" -#: c-api/object.rst:346 +#: c-api/object.rst:361 msgid "" "Return the length of object *o*. If the object *o* provides either the " "sequence and mapping protocols, the sequence length is returned. On error, " @@ -381,7 +401,7 @@ msgid "" "``len(o)``." msgstr "" -#: c-api/object.rst:353 +#: c-api/object.rst:368 msgid "" "Return an estimated length for the object *o*. First try to return its " "actual length, then an estimate using :meth:`~object.__length_hint__`, and " @@ -390,26 +410,26 @@ msgid "" "defaultvalue)``." msgstr "" -#: c-api/object.rst:363 +#: c-api/object.rst:378 msgid "" "Return element of *o* corresponding to the object *key* or ``NULL`` on " "failure. This is the equivalent of the Python expression ``o[key]``." msgstr "" -#: c-api/object.rst:369 +#: c-api/object.rst:384 msgid "" "Map the object *key* to the value *v*. Raise an exception and return ``-1`` " "on failure; return ``0`` on success. This is the equivalent of the Python " "statement ``o[key] = v``. This function *does not* steal a reference to *v*." msgstr "" -#: c-api/object.rst:377 +#: c-api/object.rst:392 msgid "" "Remove the mapping for the object *key* from the object *o*. Return ``-1`` " "on failure. This is equivalent to the Python statement ``del o[key]``." msgstr "" -#: c-api/object.rst:383 +#: c-api/object.rst:398 msgid "" "This is equivalent to the Python expression ``dir(o)``, returning a " "(possibly empty) list of strings appropriate for the object argument, or " @@ -419,7 +439,7 @@ msgid "" "`PyErr_Occurred` will return false." msgstr "" -#: c-api/object.rst:392 +#: c-api/object.rst:407 msgid "" "This is equivalent to the Python expression ``iter(o)``. It returns a new " "iterator for the object argument, or the object itself if the object is " @@ -427,7 +447,7 @@ msgid "" "object cannot be iterated." msgstr "" -#: c-api/object.rst:400 +#: c-api/object.rst:415 msgid "" "This is the equivalent to the Python expression ``aiter(o)``. Takes an :" "class:`AsyncIterable` object and returns an :class:`AsyncIterator` for it. " @@ -436,88 +456,88 @@ msgid "" "``NULL`` if the object cannot be iterated." msgstr "" -#: c-api/object.rst:410 +#: c-api/object.rst:425 msgid "Get a pointer to subclass-specific data reserved for *cls*." msgstr "" -#: c-api/object.rst:412 +#: c-api/object.rst:427 msgid "" "The object *o* must be an instance of *cls*, and *cls* must have been " "created using negative :c:member:`PyType_Spec.basicsize`. Python does not " "check this." msgstr "" -#: c-api/object.rst:416 +#: c-api/object.rst:431 msgid "On error, set an exception and return ``NULL``." msgstr "" -#: c-api/object.rst:422 +#: c-api/object.rst:437 msgid "" "Return the size of the instance memory space reserved for *cls*, i.e. the " "size of the memory :c:func:`PyObject_GetTypeData` returns." msgstr "" -#: c-api/object.rst:425 +#: c-api/object.rst:440 msgid "" "This may be larger than requested using :c:member:`-PyType_Spec.basicsize " "`; it is safe to use this larger size (e.g. with :c:" "func:`!memset`)." msgstr "" -#: c-api/object.rst:428 +#: c-api/object.rst:443 msgid "" "The type *cls* **must** have been created using negative :c:member:" "`PyType_Spec.basicsize`. Python does not check this." msgstr "" -#: c-api/object.rst:432 +#: c-api/object.rst:447 msgid "On error, set an exception and return a negative value." msgstr "" -#: c-api/object.rst:438 +#: c-api/object.rst:453 msgid "" "Get a pointer to per-item data for a class with :c:macro:" "`Py_TPFLAGS_ITEMS_AT_END`." msgstr "" -#: c-api/object.rst:441 +#: c-api/object.rst:456 msgid "" "On error, set an exception and return ``NULL``. :py:exc:`TypeError` is " "raised if *o* does not have :c:macro:`Py_TPFLAGS_ITEMS_AT_END` set." msgstr "" -#: c-api/object.rst:213 c-api/object.rst:289 c-api/object.rst:344 +#: c-api/object.rst:228 c-api/object.rst:304 c-api/object.rst:359 msgid "built-in function" msgstr "" -#: c-api/object.rst:201 +#: c-api/object.rst:216 msgid "repr" msgstr "" -#: c-api/object.rst:213 +#: c-api/object.rst:228 msgid "ascii" msgstr "" -#: c-api/object.rst:221 +#: c-api/object.rst:236 msgid "string" msgstr "" -#: c-api/object.rst:221 +#: c-api/object.rst:236 msgid "PyObject_Str (C function)" msgstr "" -#: c-api/object.rst:238 +#: c-api/object.rst:253 msgid "bytes" msgstr "" -#: c-api/object.rst:289 +#: c-api/object.rst:304 msgid "hash" msgstr "" -#: c-api/object.rst:323 +#: c-api/object.rst:338 msgid "type" msgstr "" -#: c-api/object.rst:344 +#: c-api/object.rst:359 msgid "len" msgstr "" diff --git a/c-api/perfmaps.po b/c-api/perfmaps.po index 340edc1db..7596a5a47 100644 --- a/c-api/perfmaps.po +++ b/c-api/perfmaps.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-09-18 22:33+0300\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -67,6 +67,12 @@ msgid "" "thread safe. Here is what an example entry looks like::" msgstr "" +#: c-api/perfmaps.rst:38 +msgid "" +"# address size name\n" +"7f3529fcf759 b py::bar:/run/t.py" +msgstr "" + #: c-api/perfmaps.rst:41 msgid "" "Will call :c:func:`PyUnstable_PerfMapState_Init` before writing the entry, " diff --git a/c-api/refcounting.po b/c-api/refcounting.po index ef71edf57..a11509b38 100644 --- a/c-api/refcounting.po +++ b/c-api/refcounting.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-04-01 00:17+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -89,11 +89,10 @@ msgid "" "use :c:func:`Py_XINCREF`." msgstr "" -#: c-api/refcounting.rst:127 +#: c-api/refcounting.rst:61 msgid "" -"Do not expect this function to actually modify *o* in any way. For at least " -"`some objects `_, this function has no " -"effect." +"Do not expect this function to actually modify *o* in any way. For at least :" +"pep:`some objects <0683>`, this function has no effect." msgstr "" #: c-api/refcounting.rst:71 @@ -128,10 +127,20 @@ msgstr "" msgid "For example::" msgstr "" +#: c-api/refcounting.rst:90 +msgid "" +"Py_INCREF(obj);\n" +"self->attr = obj;" +msgstr "" + #: c-api/refcounting.rst:93 msgid "can be written as::" msgstr "" +#: c-api/refcounting.rst:95 +msgid "self->attr = Py_NewRef(obj);" +msgstr "" + #: c-api/refcounting.rst:97 msgid "See also :c:func:`Py_INCREF`." msgstr "" @@ -169,6 +178,12 @@ msgid "" "use :c:func:`Py_XDECREF`." msgstr "" +#: c-api/refcounting.rst:127 +msgid "" +"Do not expect this function to actually modify *o* in any way. For at least :" +"pep:`some objects <683>`, this function has no effect." +msgstr "" + #: c-api/refcounting.rst:133 msgid "" "The deallocation function can cause arbitrary Python code to be invoked (e." @@ -234,10 +249,20 @@ msgstr "" msgid "As in case of :c:func:`Py_CLEAR`, \"the obvious\" code can be deadly::" msgstr "" +#: c-api/refcounting.rst:192 +msgid "" +"Py_DECREF(dst);\n" +"dst = src;" +msgstr "" + #: c-api/refcounting.rst:195 msgid "The safe way is::" msgstr "" +#: c-api/refcounting.rst:197 +msgid "Py_SETREF(dst, src);" +msgstr "" + #: c-api/refcounting.rst:199 msgid "" "That arranges to set *dst* to *src* _before_ releasing the reference to the " diff --git a/c-api/slice.po b/c-api/slice.po index f0da2a78d..67cd8a81a 100644 --- a/c-api/slice.po +++ b/c-api/slice.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -89,10 +89,26 @@ msgid "" "`PySlice_AdjustIndices` where ::" msgstr "" +#: c-api/slice.rst:64 +msgid "" +"if (PySlice_GetIndicesEx(slice, length, &start, &stop, &step, &slicelength) " +"< 0) {\n" +" // return error\n" +"}" +msgstr "" + #: c-api/slice.rst:68 msgid "is replaced by ::" msgstr "" +#: c-api/slice.rst:70 +msgid "" +"if (PySlice_Unpack(slice, &start, &stop, &step) < 0) {\n" +" // return error\n" +"}\n" +"slicelength = PySlice_AdjustIndices(length, &start, &stop, step);" +msgstr "" + #: c-api/slice.rst:79 msgid "" "If ``Py_LIMITED_API`` is not set or set to the value between ``0x03050400`` " diff --git a/c-api/structures.po b/c-api/structures.po index e3d8cd98c..a9f816dfe 100644 --- a/c-api/structures.po +++ b/c-api/structures.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-01 21:53+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -68,6 +68,10 @@ msgid "" "without a varying length. The PyObject_HEAD macro expands to::" msgstr "" +#: c-api/structures.rst:50 +msgid "PyObject ob_base;" +msgstr "" + #: c-api/structures.rst:52 msgid "See documentation of :c:type:`PyObject` above." msgstr "" @@ -79,6 +83,10 @@ msgid "" "expands to::" msgstr "" +#: c-api/structures.rst:61 +msgid "PyVarObject ob_base;" +msgstr "" + #: c-api/structures.rst:63 msgid "See documentation of :c:type:`PyVarObject` above." msgstr "" @@ -158,6 +166,12 @@ msgid "" "`PyObject` type. This macro expands to::" msgstr "" +#: c-api/structures.rst:148 +msgid "" +"_PyObject_EXTRA_INIT\n" +"1, type," +msgstr "" + #: c-api/structures.rst:154 msgid "" "This is a macro which expands to initialization values for a new :c:type:" @@ -165,6 +179,12 @@ msgid "" "This macro expands to::" msgstr "" +#: c-api/structures.rst:158 +msgid "" +"_PyObject_EXTRA_INIT\n" +"1, type, size," +msgstr "" + #: c-api/structures.rst:163 msgid "Implementing functions and methods" msgstr "" @@ -183,6 +203,12 @@ msgstr "" msgid "The function signature is::" msgstr "" +#: c-api/structures.rst:176 +msgid "" +"PyObject *PyCFunction(PyObject *self,\n" +" PyObject *args);" +msgstr "" + #: c-api/structures.rst:181 msgid "" "Type of the functions used to implement Python callables in C with " @@ -190,12 +216,26 @@ msgid "" "The function signature is::" msgstr "" +#: c-api/structures.rst:185 +msgid "" +"PyObject *PyCFunctionWithKeywords(PyObject *self,\n" +" PyObject *args,\n" +" PyObject *kwargs);" +msgstr "" + #: c-api/structures.rst:192 msgid "" "Type of the functions used to implement Python callables in C with " "signature :c:macro:`METH_FASTCALL`. The function signature is::" msgstr "" +#: c-api/structures.rst:196 +msgid "" +"PyObject *_PyCFunctionFast(PyObject *self,\n" +" PyObject *const *args,\n" +" Py_ssize_t nargs);" +msgstr "" + #: c-api/structures.rst:202 msgid "" "Type of the functions used to implement Python callables in C with " @@ -203,6 +243,14 @@ msgid "" "METH_KEYWORDS>`. The function signature is::" msgstr "" +#: c-api/structures.rst:206 +msgid "" +"PyObject *_PyCFunctionFastWithKeywords(PyObject *self,\n" +" PyObject *const *args,\n" +" Py_ssize_t nargs,\n" +" PyObject *kwnames);" +msgstr "" + #: c-api/structures.rst:213 msgid "" "Type of the functions used to implement Python callables in C with " @@ -210,6 +258,15 @@ msgid "" "METH_FASTCALL-METH_KEYWORDS>`. The function signature is::" msgstr "" +#: c-api/structures.rst:217 +msgid "" +"PyObject *PyCMethod(PyObject *self,\n" +" PyTypeObject *defining_class,\n" +" PyObject *const *args,\n" +" Py_ssize_t nargs,\n" +" PyObject *kwnames)" +msgstr "" + #: c-api/structures.rst:228 msgid "" "Structure used to describe a method of an extension type. This structure " @@ -507,6 +564,15 @@ msgid "" "``Py_T_PYSSIZET`` and ``Py_READONLY``, for example::" msgstr "" +#: c-api/structures.rst:490 +msgid "" +"static PyMemberDef spam_type_members[] = {\n" +" {\"__vectorcalloffset__\", Py_T_PYSSIZET,\n" +" offsetof(Spam_object, vectorcall), Py_READONLY},\n" +" {NULL} /* Sentinel */\n" +"};" +msgstr "" + #: c-api/structures.rst:496 msgid "(You may need to ``#include `` for :c:func:`!offsetof`.)" msgstr "" diff --git a/c-api/sys.po b/c-api/sys.po index d592e9c9a..5f11b18c9 100644 --- a/c-api/sys.po +++ b/c-api/sys.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -449,15 +449,6 @@ msgid "" "events table `. Details are in each function's documentation." msgstr "" -#: c-api/sys.rst:395 -msgid "" -"If the interpreter is initialized, this function raises an auditing event " -"sys.addaudithook with no arguments. If any existing hooks raise an exception " -"derived from Exception, the new hook will not be added and the exception is " -"cleared. As a result, callers cannot assume that their hook has been added " -"unless they control all existing hooks." -msgstr "" - #: c-api/sys.rst:397 msgid "" "If the interpreter is initialized, this function raises an auditing event " diff --git a/c-api/tuple.po b/c-api/tuple.po index 74fce3381..3d8cab8f8 100644 --- a/c-api/tuple.po +++ b/c-api/tuple.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-01 21:53+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -43,35 +43,37 @@ msgid "" msgstr "" #: c-api/tuple.rst:36 -msgid "Return a new tuple object of size *len*, or ``NULL`` on failure." +msgid "" +"Return a new tuple object of size *len*, or ``NULL`` with an exception set " +"on failure." msgstr "" -#: c-api/tuple.rst:41 +#: c-api/tuple.rst:42 msgid "" -"Return a new tuple object of size *n*, or ``NULL`` on failure. The tuple " -"values are initialized to the subsequent *n* C arguments pointing to Python " -"objects. ``PyTuple_Pack(2, a, b)`` is equivalent to " +"Return a new tuple object of size *n*, or ``NULL`` with an exception set on " +"failure. The tuple values are initialized to the subsequent *n* C arguments " +"pointing to Python objects. ``PyTuple_Pack(2, a, b)`` is equivalent to " "``Py_BuildValue(\"(OO)\", a, b)``." msgstr "" -#: c-api/tuple.rst:48 -msgid "Take a pointer to a tuple object, and return the size of that tuple." +#: c-api/tuple.rst:50 +msgid "" +"Take a pointer to a tuple object, and return the size of that tuple. On " +"error, return ``-1`` and with an exception set." msgstr "" -#: c-api/tuple.rst:53 -msgid "" -"Return the size of the tuple *p*, which must be non-``NULL`` and point to a " -"tuple; no error checking is performed." +#: c-api/tuple.rst:56 +msgid "Like :c:func:`PyTuple_Size`, but without error checking." msgstr "" -#: c-api/tuple.rst:59 +#: c-api/tuple.rst:61 msgid "" "Return the object at position *pos* in the tuple pointed to by *p*. If " "*pos* is negative or out of bounds, return ``NULL`` and set an :exc:" "`IndexError` exception." msgstr "" -#: c-api/tuple.rst:62 +#: c-api/tuple.rst:64 msgid "" "The returned reference is borrowed from the tuple *p* (that is: it is only " "valid as long as you hold a reference to *p*). To get a :term:`strong " @@ -79,44 +81,49 @@ msgid "" "func:`PySequence_GetItem`." msgstr "" -#: c-api/tuple.rst:71 +#: c-api/tuple.rst:73 msgid "Like :c:func:`PyTuple_GetItem`, but does no checking of its arguments." msgstr "" -#: c-api/tuple.rst:76 +#: c-api/tuple.rst:78 msgid "" "Return the slice of the tuple pointed to by *p* between *low* and *high*, or " -"``NULL`` on failure. This is the equivalent of the Python expression " -"``p[low:high]``. Indexing from the end of the tuple is not supported." +"``NULL`` with an exception set on failure." +msgstr "" + +#: c-api/tuple.rst:81 +msgid "" +"This is the equivalent of the Python expression ``p[low:high]``. Indexing " +"from the end of the tuple is not supported." msgstr "" -#: c-api/tuple.rst:83 +#: c-api/tuple.rst:87 msgid "" "Insert a reference to object *o* at position *pos* of the tuple pointed to " "by *p*. Return ``0`` on success. If *pos* is out of bounds, return ``-1`` " "and set an :exc:`IndexError` exception." msgstr "" -#: c-api/tuple.rst:89 +#: c-api/tuple.rst:93 msgid "" "This function \"steals\" a reference to *o* and discards a reference to an " "item already in the tuple at the affected position." msgstr "" -#: c-api/tuple.rst:95 +#: c-api/tuple.rst:99 msgid "" "Like :c:func:`PyTuple_SetItem`, but does no error checking, and should " "*only* be used to fill in brand new tuples." msgstr "" -#: c-api/tuple.rst:100 +#: c-api/tuple.rst:104 msgid "" "This function \"steals\" a reference to *o*, and, unlike :c:func:" "`PyTuple_SetItem`, does *not* discard a reference to any item that is being " "replaced; any reference in the tuple at position *pos* will be leaked." msgstr "" -#: c-api/tuple.rst:108 +#: c-api/tuple.rst:112 msgid "" "Can be used to resize a tuple. *newsize* will be the new length of the " "tuple. Because tuples are *supposed* to be immutable, this should only be " @@ -131,11 +138,11 @@ msgid "" "`SystemError`." msgstr "" -#: c-api/tuple.rst:123 +#: c-api/tuple.rst:127 msgid "Struct Sequence Objects" msgstr "" -#: c-api/tuple.rst:125 +#: c-api/tuple.rst:129 msgid "" "Struct sequence objects are the C equivalent of :func:`~collections." "namedtuple` objects, i.e. a sequence whose items can also be accessed " @@ -143,44 +150,50 @@ msgid "" "specific struct sequence type." msgstr "" -#: c-api/tuple.rst:132 +#: c-api/tuple.rst:136 msgid "" "Create a new struct sequence type from the data in *desc*, described below. " "Instances of the resulting type can be created with :c:func:" "`PyStructSequence_New`." msgstr "" -#: c-api/tuple.rst:138 +#: c-api/tuple.rst:208 +msgid "Return ``NULL`` with an exception set on failure." +msgstr "" + +#: c-api/tuple.rst:144 msgid "Initializes a struct sequence type *type* from *desc* in place." msgstr "" -#: c-api/tuple.rst:143 +#: c-api/tuple.rst:149 msgid "" -"The same as ``PyStructSequence_InitType``, but returns ``0`` on success and " -"``-1`` on failure." +"Like :c:func:`PyStructSequence_InitType`, but returns ``0`` on success and " +"``-1`` with an exception set on failure." msgstr "" -#: c-api/tuple.rst:151 +#: c-api/tuple.rst:157 msgid "Contains the meta information of a struct sequence type to create." msgstr "" -#: c-api/tuple.rst:155 -msgid "Name of the struct sequence type." +#: c-api/tuple.rst:161 +msgid "" +"Fully qualified name of the type; null-terminated UTF-8 encoded. The name " +"must contain the module name." msgstr "" -#: c-api/tuple.rst:159 +#: c-api/tuple.rst:166 msgid "Pointer to docstring for the type or ``NULL`` to omit." msgstr "" -#: c-api/tuple.rst:163 +#: c-api/tuple.rst:170 msgid "Pointer to ``NULL``-terminated array with field names of the new type." msgstr "" -#: c-api/tuple.rst:167 +#: c-api/tuple.rst:174 msgid "Number of fields visible to the Python side (if used as tuple)." msgstr "" -#: c-api/tuple.rst:172 +#: c-api/tuple.rst:179 msgid "" "Describes a field of a struct sequence. As a struct sequence is modeled as a " "tuple, all fields are typed as :c:expr:`PyObject*`. The index in the :c:" @@ -189,52 +202,52 @@ msgid "" "described." msgstr "" -#: c-api/tuple.rst:180 +#: c-api/tuple.rst:187 msgid "" "Name for the field or ``NULL`` to end the list of named fields, set to :c:" "data:`PyStructSequence_UnnamedField` to leave unnamed." msgstr "" -#: c-api/tuple.rst:185 +#: c-api/tuple.rst:192 msgid "Field docstring or ``NULL`` to omit." msgstr "" -#: c-api/tuple.rst:190 +#: c-api/tuple.rst:197 msgid "Special value for a field name to leave it unnamed." msgstr "" -#: c-api/tuple.rst:192 +#: c-api/tuple.rst:199 msgid "The type was changed from ``char *``." msgstr "" -#: c-api/tuple.rst:198 +#: c-api/tuple.rst:205 msgid "" "Creates an instance of *type*, which must have been created with :c:func:" "`PyStructSequence_NewType`." msgstr "" -#: c-api/tuple.rst:204 +#: c-api/tuple.rst:213 msgid "" "Return the object at position *pos* in the struct sequence pointed to by " "*p*. No bounds checking is performed." msgstr "" -#: c-api/tuple.rst:210 +#: c-api/tuple.rst:219 msgid "Macro equivalent of :c:func:`PyStructSequence_GetItem`." msgstr "" -#: c-api/tuple.rst:215 +#: c-api/tuple.rst:224 msgid "" "Sets the field at index *pos* of the struct sequence *p* to value *o*. " "Like :c:func:`PyTuple_SET_ITEM`, this should only be used to fill in brand " "new instances." msgstr "" -#: c-api/tuple.rst:231 +#: c-api/tuple.rst:240 msgid "This function \"steals\" a reference to *o*." msgstr "" -#: c-api/tuple.rst:226 +#: c-api/tuple.rst:235 msgid "" "Similar to :c:func:`PyStructSequence_SetItem`, but implemented as a static " "inlined function." diff --git a/c-api/type.po b/c-api/type.po index caf70584f..e1315de41 100644 --- a/c-api/type.po +++ b/c-api/type.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-11-04 18:33+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -64,32 +64,32 @@ msgstr "" #: c-api/type.rst:55 msgid "" "Return the type object's internal namespace, which is otherwise only exposed " -"via a read-only proxy (``cls.__dict__``). This is a replacement for " -"accessing :c:member:`~PyTypeObject.tp_dict` directly. The returned " -"dictionary must be treated as read-only." +"via a read-only proxy (:attr:`cls.__dict__ `). This is a " +"replacement for accessing :c:member:`~PyTypeObject.tp_dict` directly. The " +"returned dictionary must be treated as read-only." msgstr "" -#: c-api/type.rst:60 +#: c-api/type.rst:61 msgid "" "This function is meant for specific embedding and language-binding cases, " "where direct access to the dict is necessary and indirect access (e.g. via " "the proxy or :c:func:`PyObject_GetAttr`) isn't adequate." msgstr "" -#: c-api/type.rst:64 +#: c-api/type.rst:65 msgid "" "Extension modules should continue to use ``tp_dict``, directly or " "indirectly, when setting up their own types." msgstr "" -#: c-api/type.rst:72 +#: c-api/type.rst:73 msgid "" "Invalidate the internal lookup cache for the type and all of its subtypes. " "This function must be called after any manual modification of the attributes " "or base classes of the type." msgstr "" -#: c-api/type.rst:79 +#: c-api/type.rst:80 msgid "" "Register *callback* as a type watcher. Return a non-negative integer ID " "which must be passed to future calls to :c:func:`PyType_Watch`. In case of " @@ -97,21 +97,21 @@ msgid "" "exception." msgstr "" -#: c-api/type.rst:89 +#: c-api/type.rst:90 msgid "" "Clear watcher identified by *watcher_id* (previously returned from :c:func:" "`PyType_AddWatcher`). Return ``0`` on success, ``-1`` on error (e.g. if " "*watcher_id* was never registered.)" msgstr "" -#: c-api/type.rst:93 +#: c-api/type.rst:94 msgid "" "An extension should never call ``PyType_ClearWatcher`` with a *watcher_id* " "that was not returned to it by a previous call to :c:func:" "`PyType_AddWatcher`." msgstr "" -#: c-api/type.rst:102 +#: c-api/type.rst:103 msgid "" "Mark *type* as watched. The callback granted *watcher_id* by :c:func:" "`PyType_AddWatcher` will be called whenever :c:func:`PyType_Modified` " @@ -121,61 +121,61 @@ msgid "" "detail and subject to change.)" msgstr "" -#: c-api/type.rst:109 +#: c-api/type.rst:110 msgid "" "An extension should never call ``PyType_Watch`` with a *watcher_id* that was " "not returned to it by a previous call to :c:func:`PyType_AddWatcher`." msgstr "" -#: c-api/type.rst:117 +#: c-api/type.rst:118 msgid "Type of a type-watcher callback function." msgstr "" -#: c-api/type.rst:119 +#: c-api/type.rst:120 msgid "" "The callback must not modify *type* or cause :c:func:`PyType_Modified` to be " "called on *type* or any type in its MRO; violating this rule could cause " "infinite recursion." msgstr "" -#: c-api/type.rst:128 +#: c-api/type.rst:129 msgid "" "Return non-zero if the type object *o* sets the feature *feature*. Type " "features are denoted by single bit flags." msgstr "" -#: c-api/type.rst:134 +#: c-api/type.rst:135 msgid "" "Return true if the type object includes support for the cycle detector; this " "tests the type flag :c:macro:`Py_TPFLAGS_HAVE_GC`." msgstr "" -#: c-api/type.rst:140 +#: c-api/type.rst:141 msgid "Return true if *a* is a subtype of *b*." msgstr "" -#: c-api/type.rst:142 +#: c-api/type.rst:143 msgid "" -"This function only checks for actual subtypes, which means that :meth:" -"`~class.__subclasscheck__` is not called on *b*. Call :c:func:" -"`PyObject_IsSubclass` to do the same check that :func:`issubclass` would do." +"This function only checks for actual subtypes, which means that :meth:`~type." +"__subclasscheck__` is not called on *b*. Call :c:func:`PyObject_IsSubclass` " +"to do the same check that :func:`issubclass` would do." msgstr "" -#: c-api/type.rst:150 +#: c-api/type.rst:151 msgid "" "Generic handler for the :c:member:`~PyTypeObject.tp_alloc` slot of a type " "object. Use Python's default memory allocation mechanism to allocate a new " "instance and initialize all its contents to ``NULL``." msgstr "" -#: c-api/type.rst:156 +#: c-api/type.rst:157 msgid "" "Generic handler for the :c:member:`~PyTypeObject.tp_new` slot of a type " "object. Create a new instance using the type's :c:member:`~PyTypeObject." "tp_alloc` slot." msgstr "" -#: c-api/type.rst:161 +#: c-api/type.rst:162 msgid "" "Finalize a type object. This should be called on all type objects to finish " "their initialization. This function is responsible for adding inherited " @@ -183,7 +183,7 @@ msgid "" "and sets an exception on error." msgstr "" -#: c-api/type.rst:167 +#: c-api/type.rst:168 msgid "" "If some of the base classes implements the GC protocol and the provided type " "does not include the :c:macro:`Py_TPFLAGS_HAVE_GC` in its flags, then the GC " @@ -194,19 +194,19 @@ msgid "" "handle." msgstr "" -#: c-api/type.rst:177 +#: c-api/type.rst:178 msgid "" -"Return the type's name. Equivalent to getting the type's ``__name__`` " -"attribute." +"Return the type's name. Equivalent to getting the type's :attr:`~type." +"__name__` attribute." msgstr "" -#: c-api/type.rst:183 +#: c-api/type.rst:185 msgid "" -"Return the type's qualified name. Equivalent to getting the type's " -"``__qualname__`` attribute." +"Return the type's qualified name. Equivalent to getting the type's :attr:" +"`~type.__qualname__` attribute." msgstr "" -#: c-api/type.rst:190 +#: c-api/type.rst:192 msgid "" "Return the function pointer stored in the given slot. If the result is " "``NULL``, this indicates that either the slot is ``NULL``, or that the " @@ -214,30 +214,30 @@ msgid "" "result pointer into the appropriate function type." msgstr "" -#: c-api/type.rst:196 +#: c-api/type.rst:198 msgid "" "See :c:member:`PyType_Slot.slot` for possible values of the *slot* argument." msgstr "" -#: c-api/type.rst:200 +#: c-api/type.rst:202 msgid "" ":c:func:`PyType_GetSlot` can now accept all types. Previously, it was " "limited to :ref:`heap types `." msgstr "" -#: c-api/type.rst:206 +#: c-api/type.rst:208 msgid "" "Return the module object associated with the given type when the type was " "created using :c:func:`PyType_FromModuleAndSpec`." msgstr "" -#: c-api/type.rst:229 +#: c-api/type.rst:231 msgid "" "If no module is associated with the given type, sets :py:class:`TypeError` " "and returns ``NULL``." msgstr "" -#: c-api/type.rst:212 +#: c-api/type.rst:214 msgid "" "This function is usually used to get the module in which a method is " "defined. Note that in such a method, ``PyType_GetModule(Py_TYPE(self))`` may " @@ -248,31 +248,31 @@ msgid "" "type:`!PyCMethod` cannot be used." msgstr "" -#: c-api/type.rst:225 +#: c-api/type.rst:227 msgid "" "Return the state of the module object associated with the given type. This " "is a shortcut for calling :c:func:`PyModule_GetState()` on the result of :c:" "func:`PyType_GetModule`." msgstr "" -#: c-api/type.rst:232 +#: c-api/type.rst:234 msgid "" "If the *type* has an associated module but its state is ``NULL``, returns " "``NULL`` without setting an exception." msgstr "" -#: c-api/type.rst:239 +#: c-api/type.rst:241 msgid "" "Find the first superclass whose module was created from the given :c:type:" "`PyModuleDef` *def*, and return that module." msgstr "" -#: c-api/type.rst:242 +#: c-api/type.rst:244 msgid "" "If no module is found, raises a :py:class:`TypeError` and returns ``NULL``." msgstr "" -#: c-api/type.rst:244 +#: c-api/type.rst:246 msgid "" "This function is intended to be used together with :c:func:" "`PyModule_GetState()` to get module state from slot methods (such as :c:" @@ -281,40 +281,40 @@ msgid "" "type:`PyCMethod` calling convention." msgstr "" -#: c-api/type.rst:254 +#: c-api/type.rst:256 msgid "Attempt to assign a version tag to the given type." msgstr "" -#: c-api/type.rst:256 +#: c-api/type.rst:258 msgid "" "Returns 1 if the type already had a valid version tag or a new one was " "assigned, or 0 if a new tag could not be assigned." msgstr "" -#: c-api/type.rst:263 +#: c-api/type.rst:265 msgid "Creating Heap-Allocated Types" msgstr "" -#: c-api/type.rst:265 +#: c-api/type.rst:267 msgid "" "The following functions and structs are used to create :ref:`heap types " "`." msgstr "" -#: c-api/type.rst:270 +#: c-api/type.rst:272 msgid "" "Create and return a :ref:`heap type ` from the *spec* (see :c:" "macro:`Py_TPFLAGS_HEAPTYPE`)." msgstr "" -#: c-api/type.rst:273 +#: c-api/type.rst:275 msgid "" "The metaclass *metaclass* is used to construct the resulting type object. " "When *metaclass* is ``NULL``, the metaclass is derived from *bases* (or " "*Py_tp_base[s]* slots if *bases* is ``NULL``, see below)." msgstr "" -#: c-api/type.rst:277 +#: c-api/type.rst:279 msgid "" "Metaclasses that override :c:member:`~PyTypeObject.tp_new` are not " "supported, except if ``tp_new`` is ``NULL``. (For backwards compatibility, " @@ -323,7 +323,7 @@ msgid "" "deprecated and in Python 3.14+ such metaclasses will not be supported.)" msgstr "" -#: c-api/type.rst:284 +#: c-api/type.rst:286 msgid "" "The *bases* argument can be used to specify base classes; it can either be " "only one class or a tuple of classes. If *bases* is ``NULL``, the " @@ -332,7 +332,7 @@ msgid "" "derives from :class:`object`." msgstr "" -#: c-api/type.rst:290 +#: c-api/type.rst:292 msgid "" "The *module* argument can be used to record the module in which the new " "class is defined. It must be a module object or ``NULL``. If not ``NULL``, " @@ -341,11 +341,11 @@ msgid "" "subclasses; it must be specified for each class individually." msgstr "" -#: c-api/type.rst:297 +#: c-api/type.rst:299 msgid "This function calls :c:func:`PyType_Ready` on the new type." msgstr "" -#: c-api/type.rst:299 +#: c-api/type.rst:301 msgid "" "Note that this function does *not* fully match the behavior of calling :py:" "class:`type() ` or using the :keyword:`class` statement. With user-" @@ -354,41 +354,41 @@ msgid "" "Specifically:" msgstr "" -#: c-api/type.rst:306 +#: c-api/type.rst:308 msgid "" ":py:meth:`~object.__new__` is not called on the new class (and it must be " "set to ``type.__new__``)." msgstr "" -#: c-api/type.rst:308 +#: c-api/type.rst:310 msgid ":py:meth:`~object.__init__` is not called on the new class." msgstr "" -#: c-api/type.rst:309 +#: c-api/type.rst:311 msgid ":py:meth:`~object.__init_subclass__` is not called on any bases." msgstr "" -#: c-api/type.rst:310 +#: c-api/type.rst:312 msgid ":py:meth:`~object.__set_name__` is not called on new descriptors." msgstr "" -#: c-api/type.rst:316 +#: c-api/type.rst:318 msgid "Equivalent to ``PyType_FromMetaclass(NULL, module, spec, bases)``." msgstr "" -#: c-api/type.rst:322 +#: c-api/type.rst:324 msgid "" "The function now accepts a single class as the *bases* argument and ``NULL`` " "as the ``tp_doc`` slot." msgstr "" -#: c-api/type.rst:344 +#: c-api/type.rst:346 msgid "" "The function now finds and uses a metaclass corresponding to the provided " "base classes. Previously, only :class:`type` instances were returned." msgstr "" -#: c-api/type.rst:347 c-api/type.rst:363 +#: c-api/type.rst:349 c-api/type.rst:365 msgid "" "The :c:member:`~PyTypeObject.tp_new` of the metaclass is *ignored*. which " "may result in incomplete initialization. Creating classes whose metaclass " @@ -396,42 +396,42 @@ msgid "" "it will be no longer allowed." msgstr "" -#: c-api/type.rst:338 +#: c-api/type.rst:340 msgid "Equivalent to ``PyType_FromMetaclass(NULL, NULL, spec, bases)``." msgstr "" -#: c-api/type.rst:355 +#: c-api/type.rst:357 msgid "Equivalent to ``PyType_FromMetaclass(NULL, NULL, spec, NULL)``." msgstr "" -#: c-api/type.rst:359 +#: c-api/type.rst:361 msgid "" "The function now finds and uses a metaclass corresponding to the base " "classes provided in *Py_tp_base[s]* slots. Previously, only :class:`type` " "instances were returned." msgstr "" -#: c-api/type.rst:380 +#: c-api/type.rst:382 msgid "Structure defining a type's behavior." msgstr "" -#: c-api/type.rst:384 +#: c-api/type.rst:386 msgid "Name of the type, used to set :c:member:`PyTypeObject.tp_name`." msgstr "" -#: c-api/type.rst:388 +#: c-api/type.rst:390 msgid "" "If positive, specifies the size of the instance in bytes. It is used to set :" "c:member:`PyTypeObject.tp_basicsize`." msgstr "" -#: c-api/type.rst:391 +#: c-api/type.rst:393 msgid "" "If zero, specifies that :c:member:`~PyTypeObject.tp_basicsize` should be " "inherited." msgstr "" -#: c-api/type.rst:394 +#: c-api/type.rst:396 msgid "" "If negative, the absolute value specifies how much space instances of the " "class need *in addition* to the superclass. Use :c:func:" @@ -439,17 +439,17 @@ msgid "" "this way." msgstr "" -#: c-api/type.rst:401 +#: c-api/type.rst:403 msgid "Previously, this field could not be negative." msgstr "" -#: c-api/type.rst:405 +#: c-api/type.rst:407 msgid "" "Size of one element of a variable-size type, in bytes. Used to set :c:member:" "`PyTypeObject.tp_itemsize`. See ``tp_itemsize`` documentation for caveats." msgstr "" -#: c-api/type.rst:409 +#: c-api/type.rst:411 msgid "" "If zero, :c:member:`~PyTypeObject.tp_itemsize` is inherited. Extending " "arbitrary variable-sized classes is dangerous, since some types use a fixed " @@ -458,58 +458,58 @@ msgid "" "only possible in the following situations:" msgstr "" -#: c-api/type.rst:416 +#: c-api/type.rst:418 msgid "" "The base is not variable-sized (its :c:member:`~PyTypeObject.tp_itemsize`)." msgstr "" -#: c-api/type.rst:418 +#: c-api/type.rst:420 msgid "" "The requested :c:member:`PyType_Spec.basicsize` is positive, suggesting that " "the memory layout of the base class is known." msgstr "" -#: c-api/type.rst:420 +#: c-api/type.rst:422 msgid "" "The requested :c:member:`PyType_Spec.basicsize` is zero, suggesting that the " "subclass does not access the instance's memory directly." msgstr "" -#: c-api/type.rst:423 +#: c-api/type.rst:425 msgid "With the :c:macro:`Py_TPFLAGS_ITEMS_AT_END` flag." msgstr "" -#: c-api/type.rst:427 +#: c-api/type.rst:429 msgid "Type flags, used to set :c:member:`PyTypeObject.tp_flags`." msgstr "" -#: c-api/type.rst:429 +#: c-api/type.rst:431 msgid "" "If the ``Py_TPFLAGS_HEAPTYPE`` flag is not set, :c:func:" "`PyType_FromSpecWithBases` sets it automatically." msgstr "" -#: c-api/type.rst:434 +#: c-api/type.rst:436 msgid "" "Array of :c:type:`PyType_Slot` structures. Terminated by the special slot " "value ``{0, NULL}``." msgstr "" -#: c-api/type.rst:437 +#: c-api/type.rst:439 msgid "Each slot ID should be specified at most once." msgstr "" -#: c-api/type.rst:447 +#: c-api/type.rst:449 msgid "" "Structure defining optional functionality of a type, containing a slot ID " "and a value pointer." msgstr "" -#: c-api/type.rst:452 +#: c-api/type.rst:454 msgid "A slot ID." msgstr "" -#: c-api/type.rst:454 +#: c-api/type.rst:456 msgid "" "Slot IDs are named like the field names of the structures :c:type:" "`PyTypeObject`, :c:type:`PyNumberMethods`, :c:type:`PySequenceMethods`, :c:" @@ -517,42 +517,42 @@ msgid "" "prefix. For example, use:" msgstr "" -#: c-api/type.rst:460 +#: c-api/type.rst:462 msgid "``Py_tp_dealloc`` to set :c:member:`PyTypeObject.tp_dealloc`" msgstr "" -#: c-api/type.rst:461 +#: c-api/type.rst:463 msgid "``Py_nb_add`` to set :c:member:`PyNumberMethods.nb_add`" msgstr "" -#: c-api/type.rst:462 +#: c-api/type.rst:464 msgid "``Py_sq_length`` to set :c:member:`PySequenceMethods.sq_length`" msgstr "" -#: c-api/type.rst:464 +#: c-api/type.rst:466 msgid "" "The following “offset” fields cannot be set using :c:type:`PyType_Slot`:" msgstr "" -#: c-api/type.rst:466 +#: c-api/type.rst:468 msgid "" ":c:member:`~PyTypeObject.tp_weaklistoffset` (use :c:macro:" "`Py_TPFLAGS_MANAGED_WEAKREF` instead if possible)" msgstr "" -#: c-api/type.rst:468 +#: c-api/type.rst:470 msgid "" ":c:member:`~PyTypeObject.tp_dictoffset` (use :c:macro:" "`Py_TPFLAGS_MANAGED_DICT` instead if possible)" msgstr "" -#: c-api/type.rst:470 +#: c-api/type.rst:472 msgid "" ":c:member:`~PyTypeObject.tp_vectorcall_offset` (use " "``\"__vectorcalloffset__\"`` in :ref:`PyMemberDef `)" msgstr "" -#: c-api/type.rst:474 +#: c-api/type.rst:476 msgid "" "If it is not possible to switch to a ``MANAGED`` flag (for example, for " "vectorcall or to support Python older than 3.12), specify the offset in :c:" @@ -560,48 +560,48 @@ msgid "" "documentation ` for details." msgstr "" -#: c-api/type.rst:480 +#: c-api/type.rst:482 msgid "The following fields cannot be set at all when creating a heap type:" msgstr "" -#: c-api/type.rst:482 +#: c-api/type.rst:484 msgid "" ":c:member:`~PyTypeObject.tp_vectorcall` (use :c:member:`~PyTypeObject." "tp_new` and/or :c:member:`~PyTypeObject.tp_init`)" msgstr "" -#: c-api/type.rst:486 +#: c-api/type.rst:488 msgid "" "Internal fields: :c:member:`~PyTypeObject.tp_dict`, :c:member:`~PyTypeObject." "tp_mro`, :c:member:`~PyTypeObject.tp_cache`, :c:member:`~PyTypeObject." "tp_subclasses`, and :c:member:`~PyTypeObject.tp_weaklist`." msgstr "" -#: c-api/type.rst:493 +#: c-api/type.rst:495 msgid "" "Setting :c:data:`Py_tp_bases` or :c:data:`Py_tp_base` may be problematic on " "some platforms. To avoid issues, use the *bases* argument of :c:func:" "`PyType_FromSpecWithBases` instead." msgstr "" -#: c-api/type.rst:500 +#: c-api/type.rst:502 msgid "Slots in :c:type:`PyBufferProcs` may be set in the unlimited API." msgstr "" -#: c-api/type.rst:502 +#: c-api/type.rst:504 msgid "" ":c:member:`~PyBufferProcs.bf_getbuffer` and :c:member:`~PyBufferProcs." "bf_releasebuffer` are now available under the :ref:`limited API `." msgstr "" -#: c-api/type.rst:509 +#: c-api/type.rst:511 msgid "" "The desired value of the slot. In most cases, this is a pointer to a " "function." msgstr "" -#: c-api/type.rst:512 +#: c-api/type.rst:514 msgid "Slots other than ``Py_tp_doc`` may not be ``NULL``." msgstr "" diff --git a/c-api/typehints.po b/c-api/typehints.po index 7ff967f9b..92fc1bd12 100644 --- a/c-api/typehints.po +++ b/c-api/typehints.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-09-18 19:05+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -46,6 +46,18 @@ msgstr "" msgid "Here's an example of how to make an extension type generic::" msgstr "" +#: c-api/typehints.rst:30 +msgid "" +"...\n" +"static PyMethodDef my_obj_methods[] = {\n" +" // Other methods.\n" +" ...\n" +" {\"__class_getitem__\", Py_GenericAlias, METH_O|METH_CLASS, \"See PEP " +"585\"}\n" +" ...\n" +"}" +msgstr "" + #: c-api/typehints.rst:38 msgid "The data model method :meth:`~object.__class_getitem__`." msgstr "" diff --git a/c-api/typeobj.po b/c-api/typeobj.po index 6bde2c3df..43276425f 100644 --- a/c-api/typeobj.po +++ b/c-api/typeobj.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -583,10 +583,29 @@ msgstr "" msgid "**\"D\"**: default (if slot is set to ``NULL``)" msgstr "" +#: c-api/typeobj.rst:172 +msgid "" +"X - PyType_Ready sets this value if it is NULL\n" +"~ - PyType_Ready always sets this value (it should be NULL)\n" +"? - PyType_Ready may set this value depending on other slots\n" +"\n" +"Also see the inheritance column (\"I\")." +msgstr "" + #: c-api/typeobj.rst:180 msgid "**\"I\"**: inheritance" msgstr "" +#: c-api/typeobj.rst:182 +msgid "" +"X - type slot is inherited via *PyType_Ready* if defined with a *NULL* " +"value\n" +"% - the slots of the sub-struct are inherited individually\n" +"G - inherited, but only in combination with other slots; see the slot's " +"description\n" +"? - it's complicated; see the slot's description" +msgstr "" + #: c-api/typeobj.rst:189 msgid "" "Note that some slots are effectively inherited through the normal attribute " @@ -1102,6 +1121,96 @@ msgid "" "definition found there:" msgstr "" +#: c-api/typeobj.rst:481 +msgid "" +"typedef struct _typeobject {\n" +" PyObject_VAR_HEAD\n" +" const char *tp_name; /* For printing, in format \".\" */\n" +" Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */\n" +"\n" +" /* Methods to implement standard operations */\n" +"\n" +" destructor tp_dealloc;\n" +" Py_ssize_t tp_vectorcall_offset;\n" +" getattrfunc tp_getattr;\n" +" setattrfunc tp_setattr;\n" +" PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)\n" +" or tp_reserved (Python 3) */\n" +" reprfunc tp_repr;\n" +"\n" +" /* Method suites for standard classes */\n" +"\n" +" PyNumberMethods *tp_as_number;\n" +" PySequenceMethods *tp_as_sequence;\n" +" PyMappingMethods *tp_as_mapping;\n" +"\n" +" /* More standard operations (here for binary compatibility) */\n" +"\n" +" hashfunc tp_hash;\n" +" ternaryfunc tp_call;\n" +" reprfunc tp_str;\n" +" getattrofunc tp_getattro;\n" +" setattrofunc tp_setattro;\n" +"\n" +" /* Functions to access object as input/output buffer */\n" +" PyBufferProcs *tp_as_buffer;\n" +"\n" +" /* Flags to define presence of optional/expanded features */\n" +" unsigned long tp_flags;\n" +"\n" +" const char *tp_doc; /* Documentation string */\n" +"\n" +" /* Assigned meaning in release 2.0 */\n" +" /* call function for all accessible objects */\n" +" traverseproc tp_traverse;\n" +"\n" +" /* delete references to contained objects */\n" +" inquiry tp_clear;\n" +"\n" +" /* Assigned meaning in release 2.1 */\n" +" /* rich comparisons */\n" +" richcmpfunc tp_richcompare;\n" +"\n" +" /* weak reference enabler */\n" +" Py_ssize_t tp_weaklistoffset;\n" +"\n" +" /* Iterators */\n" +" getiterfunc tp_iter;\n" +" iternextfunc tp_iternext;\n" +"\n" +" /* Attribute descriptor and subclassing stuff */\n" +" struct PyMethodDef *tp_methods;\n" +" struct PyMemberDef *tp_members;\n" +" struct PyGetSetDef *tp_getset;\n" +" // Strong reference on a heap type, borrowed reference on a static type\n" +" struct _typeobject *tp_base;\n" +" PyObject *tp_dict;\n" +" descrgetfunc tp_descr_get;\n" +" descrsetfunc tp_descr_set;\n" +" Py_ssize_t tp_dictoffset;\n" +" initproc tp_init;\n" +" allocfunc tp_alloc;\n" +" newfunc tp_new;\n" +" freefunc tp_free; /* Low-level free-memory routine */\n" +" inquiry tp_is_gc; /* For PyObject_IS_GC */\n" +" PyObject *tp_bases;\n" +" PyObject *tp_mro; /* method resolution order */\n" +" PyObject *tp_cache;\n" +" PyObject *tp_subclasses;\n" +" PyObject *tp_weaklist;\n" +" destructor tp_del;\n" +"\n" +" /* Type attribute cache version tag. Added in version 2.6 */\n" +" unsigned int tp_version_tag;\n" +"\n" +" destructor tp_finalize;\n" +" vectorcallfunc tp_vectorcall;\n" +"\n" +" /* bitset of which type-watchers care about this type */\n" +" unsigned char tp_watched;\n" +"} PyTypeObject;\n" +msgstr "" + #: c-api/typeobj.rst:485 msgid "PyObject Slots" msgstr "" @@ -1127,16 +1236,16 @@ msgid "" msgstr "" #: c-api/typeobj.rst:526 c-api/typeobj.rst:562 c-api/typeobj.rst:649 -#: c-api/typeobj.rst:749 c-api/typeobj.rst:783 c-api/typeobj.rst:825 -#: c-api/typeobj.rst:854 c-api/typeobj.rst:899 c-api/typeobj.rst:937 -#: c-api/typeobj.rst:984 c-api/typeobj.rst:1019 c-api/typeobj.rst:1069 -#: c-api/typeobj.rst:1089 c-api/typeobj.rst:1121 c-api/typeobj.rst:1159 -#: c-api/typeobj.rst:1194 c-api/typeobj.rst:1259 c-api/typeobj.rst:1308 -#: c-api/typeobj.rst:1356 c-api/typeobj.rst:1492 c-api/typeobj.rst:1589 -#: c-api/typeobj.rst:1637 c-api/typeobj.rst:1665 c-api/typeobj.rst:1709 -#: c-api/typeobj.rst:1767 c-api/typeobj.rst:1814 c-api/typeobj.rst:1875 -#: c-api/typeobj.rst:1938 c-api/typeobj.rst:1998 c-api/typeobj.rst:2021 -#: c-api/typeobj.rst:2055 c-api/typeobj.rst:2115 c-api/typeobj.rst:2138 +#: c-api/typeobj.rst:762 c-api/typeobj.rst:796 c-api/typeobj.rst:838 +#: c-api/typeobj.rst:867 c-api/typeobj.rst:912 c-api/typeobj.rst:950 +#: c-api/typeobj.rst:997 c-api/typeobj.rst:1032 c-api/typeobj.rst:1082 +#: c-api/typeobj.rst:1102 c-api/typeobj.rst:1134 c-api/typeobj.rst:1172 +#: c-api/typeobj.rst:1207 c-api/typeobj.rst:1272 c-api/typeobj.rst:1321 +#: c-api/typeobj.rst:1369 c-api/typeobj.rst:1505 c-api/typeobj.rst:1602 +#: c-api/typeobj.rst:1650 c-api/typeobj.rst:1678 c-api/typeobj.rst:1722 +#: c-api/typeobj.rst:1780 c-api/typeobj.rst:1827 c-api/typeobj.rst:1888 +#: c-api/typeobj.rst:1951 c-api/typeobj.rst:2011 c-api/typeobj.rst:2034 +#: c-api/typeobj.rst:2068 c-api/typeobj.rst:2117 c-api/typeobj.rst:2140 msgid "**Inheritance:**" msgstr "" @@ -1156,6 +1265,10 @@ msgid "" "doing anything else. This is typically done like this::" msgstr "" +#: c-api/typeobj.rst:519 +msgid "Foo_Type.ob_type = &PyType_Type;" +msgstr "" + #: c-api/typeobj.rst:521 msgid "" "This should be done before any instances of the type are created. :c:func:" @@ -1164,8 +1277,8 @@ msgid "" "class. :c:func:`PyType_Ready` will not change this field if it is non-zero." msgstr "" -#: c-api/typeobj.rst:710 c-api/typeobj.rst:919 c-api/typeobj.rst:1616 -#: c-api/typeobj.rst:1769 c-api/typeobj.rst:1860 c-api/typeobj.rst:2117 +#: c-api/typeobj.rst:723 c-api/typeobj.rst:932 c-api/typeobj.rst:1629 +#: c-api/typeobj.rst:1782 c-api/typeobj.rst:1873 c-api/typeobj.rst:2119 msgid "This field is inherited by subtypes." msgstr "" @@ -1242,15 +1355,15 @@ msgstr "" msgid "" "For :ref:`statically allocated type objects `, the *tp_name* " "field should contain a dot. Everything before the last dot is made " -"accessible as the :attr:`__module__` attribute, and everything after the " -"last dot is made accessible as the :attr:`~definition.__name__` attribute." +"accessible as the :attr:`~type.__module__` attribute, and everything after " +"the last dot is made accessible as the :attr:`~type.__name__` attribute." msgstr "" #: c-api/typeobj.rst:596 msgid "" "If no dot is present, the entire :c:member:`~PyTypeObject.tp_name` field is " -"made accessible as the :attr:`~definition.__name__` attribute, and the :attr:" -"`__module__` attribute is undefined (unless explicitly set in the " +"made accessible as the :attr:`~type.__name__` attribute, and the :attr:" +"`~type.__module__` attribute is undefined (unless explicitly set in the " "dictionary, as explained above). This means your type will be impossible to " "pickle. Additionally, it will not be listed in module documentations " "created with pydoc." @@ -1337,6 +1450,10 @@ msgid "" "The function signature is::" msgstr "" +#: c-api/typeobj.rst:663 +msgid "void tp_dealloc(PyObject *self);" +msgstr "" + #: c-api/typeobj.rst:665 msgid "" "The destructor function is called by the :c:func:`Py_DECREF` and :c:func:" @@ -1362,6 +1479,15 @@ msgid "" "`PyObject_GC_UnTrack` before clearing any member fields." msgstr "" +#: c-api/typeobj.rst:684 +msgid "" +"static void foo_dealloc(foo_object *self) {\n" +" PyObject_GC_UnTrack(self);\n" +" Py_CLEAR(self->ref);\n" +" Py_TYPE(self)->tp_free((PyObject *)self);\n" +"}" +msgstr "" + #: c-api/typeobj.rst:692 msgid "" "Finally, if the type is heap allocated (:c:macro:`Py_TPFLAGS_HEAPTYPE`), the " @@ -1370,28 +1496,51 @@ msgid "" "dangling pointers, the recommended way to achieve this is:" msgstr "" -#: c-api/typeobj.rst:715 +#: c-api/typeobj.rst:698 +msgid "" +"static void foo_dealloc(foo_object *self) {\n" +" PyTypeObject *tp = Py_TYPE(self);\n" +" // free references and buffers here\n" +" tp->tp_free(self);\n" +" Py_DECREF(tp);\n" +"}" +msgstr "" + +#: c-api/typeobj.rst:709 +msgid "" +"In a garbage collected Python, :c:member:`!tp_dealloc` may be called from " +"any Python thread, not just the thread which created the object (if the " +"object becomes part of a refcount cycle, that cycle might be collected by a " +"garbage collection on any thread). This is not a problem for Python API " +"calls, since the thread on which :c:member:`!tp_dealloc` is called will own " +"the Global Interpreter Lock (GIL). However, if the object being destroyed " +"in turn destroys objects from some other C or C++ library, care should be " +"taken to ensure that destroying those objects on the thread which called :c:" +"member:`!tp_dealloc` will not violate any assumptions of the library." +msgstr "" + +#: c-api/typeobj.rst:728 msgid "" "An optional offset to a per-instance function that implements calling the " "object using the :ref:`vectorcall protocol `, a more efficient " "alternative of the simpler :c:member:`~PyTypeObject.tp_call`." msgstr "" -#: c-api/typeobj.rst:720 +#: c-api/typeobj.rst:733 msgid "" "This field is only used if the flag :c:macro:`Py_TPFLAGS_HAVE_VECTORCALL` is " "set. If so, this must be a positive integer containing the offset in the " "instance of a :c:type:`vectorcallfunc` pointer." msgstr "" -#: c-api/typeobj.rst:724 +#: c-api/typeobj.rst:737 msgid "" "The *vectorcallfunc* pointer may be ``NULL``, in which case the instance " "behaves as if :c:macro:`Py_TPFLAGS_HAVE_VECTORCALL` was not set: calling the " "instance falls back to :c:member:`~PyTypeObject.tp_call`." msgstr "" -#: c-api/typeobj.rst:728 +#: c-api/typeobj.rst:741 msgid "" "Any class that sets ``Py_TPFLAGS_HAVE_VECTORCALL`` must also set :c:member:" "`~PyTypeObject.tp_call` and make sure its behaviour is consistent with the " @@ -1399,13 +1548,13 @@ msgid "" "`PyVectorcall_Call`." msgstr "" -#: c-api/typeobj.rst:735 +#: c-api/typeobj.rst:748 msgid "" "Before version 3.8, this slot was named ``tp_print``. In Python 2.x, it was " "used for printing to a file. In Python 3.0 to 3.7, it was unused." msgstr "" -#: c-api/typeobj.rst:741 +#: c-api/typeobj.rst:754 msgid "" "Before version 3.12, it was not recommended for :ref:`mutable heap types " "` to implement the vectorcall protocol. When a user sets :attr:" @@ -1415,7 +1564,7 @@ msgid "" "`Py_TPFLAGS_HAVE_VECTORCALL` flag." msgstr "" -#: c-api/typeobj.rst:751 +#: c-api/typeobj.rst:764 msgid "" "This field is always inherited. However, the :c:macro:" "`Py_TPFLAGS_HAVE_VECTORCALL` flag is not always inherited. If it's not set, " @@ -1423,11 +1572,11 @@ msgid "" "func:`PyVectorcall_Call` is explicitly called." msgstr "" -#: c-api/typeobj.rst:760 +#: c-api/typeobj.rst:773 msgid "An optional pointer to the get-attribute-string function." msgstr "" -#: c-api/typeobj.rst:762 +#: c-api/typeobj.rst:775 msgid "" "This field is deprecated. When it is defined, it should point to a function " "that acts the same as the :c:member:`~PyTypeObject.tp_getattro` function, " @@ -1435,13 +1584,13 @@ msgid "" "attribute name." msgstr "" -#: c-api/typeobj.rst:960 +#: c-api/typeobj.rst:973 msgid "" "Group: :c:member:`~PyTypeObject.tp_getattr`, :c:member:`~PyTypeObject." "tp_getattro`" msgstr "" -#: c-api/typeobj.rst:770 +#: c-api/typeobj.rst:783 msgid "" "This field is inherited by subtypes together with :c:member:`~PyTypeObject." "tp_getattro`: a subtype inherits both :c:member:`~PyTypeObject.tp_getattr` " @@ -1450,12 +1599,12 @@ msgid "" "tp_getattro` are both ``NULL``." msgstr "" -#: c-api/typeobj.rst:973 +#: c-api/typeobj.rst:986 msgid "" "An optional pointer to the function for setting and deleting attributes." msgstr "" -#: c-api/typeobj.rst:779 +#: c-api/typeobj.rst:792 msgid "" "This field is deprecated. When it is defined, it should point to a function " "that acts the same as the :c:member:`~PyTypeObject.tp_setattro` function, " @@ -1463,13 +1612,13 @@ msgid "" "attribute name." msgstr "" -#: c-api/typeobj.rst:986 +#: c-api/typeobj.rst:999 msgid "" "Group: :c:member:`~PyTypeObject.tp_setattr`, :c:member:`~PyTypeObject." "tp_setattro`" msgstr "" -#: c-api/typeobj.rst:787 +#: c-api/typeobj.rst:800 msgid "" "This field is inherited by subtypes together with :c:member:`~PyTypeObject." "tp_setattro`: a subtype inherits both :c:member:`~PyTypeObject.tp_setattr` " @@ -1478,34 +1627,38 @@ msgid "" "tp_setattro` are both ``NULL``." msgstr "" -#: c-api/typeobj.rst:794 +#: c-api/typeobj.rst:807 msgid "" "Pointer to an additional structure that contains fields relevant only to " "objects which implement :term:`awaitable` and :term:`asynchronous iterator` " "protocols at the C-level. See :ref:`async-structs` for details." msgstr "" -#: c-api/typeobj.rst:798 +#: c-api/typeobj.rst:811 msgid "Formerly known as ``tp_compare`` and ``tp_reserved``." msgstr "" -#: c-api/typeobj.rst:803 +#: c-api/typeobj.rst:816 msgid "" "The :c:member:`~PyTypeObject.tp_as_async` field is not inherited, but the " "contained fields are inherited individually." msgstr "" -#: c-api/typeobj.rst:811 +#: c-api/typeobj.rst:824 msgid "" "An optional pointer to a function that implements the built-in function :" "func:`repr`." msgstr "" -#: c-api/typeobj.rst:814 +#: c-api/typeobj.rst:827 msgid "The signature is the same as for :c:func:`PyObject_Repr`::" msgstr "" -#: c-api/typeobj.rst:818 +#: c-api/typeobj.rst:829 +msgid "PyObject *tp_repr(PyObject *self);" +msgstr "" + +#: c-api/typeobj.rst:831 msgid "" "The function must return a string or a Unicode object. Ideally, this " "function should return a string that, when passed to :func:`eval`, given a " @@ -1514,76 +1667,80 @@ msgid "" "``'>'`` from which both the type and the value of the object can be deduced." msgstr "" -#: c-api/typeobj.rst:941 c-api/typeobj.rst:992 c-api/typeobj.rst:1562 -#: c-api/typeobj.rst:1713 c-api/typeobj.rst:1821 c-api/typeobj.rst:1880 -#: c-api/typeobj.rst:1943 c-api/typeobj.rst:1974 +#: c-api/typeobj.rst:954 c-api/typeobj.rst:1005 c-api/typeobj.rst:1575 +#: c-api/typeobj.rst:1726 c-api/typeobj.rst:1834 c-api/typeobj.rst:1893 +#: c-api/typeobj.rst:1956 c-api/typeobj.rst:1987 msgid "**Default:**" msgstr "" -#: c-api/typeobj.rst:831 +#: c-api/typeobj.rst:844 msgid "" "When this field is not set, a string of the form ``<%s object at %p>`` is " "returned, where ``%s`` is replaced by the type name, and ``%p`` by the " "object's memory address." msgstr "" -#: c-api/typeobj.rst:838 +#: c-api/typeobj.rst:851 msgid "" "Pointer to an additional structure that contains fields relevant only to " "objects which implement the number protocol. These fields are documented " "in :ref:`number-structs`." msgstr "" -#: c-api/typeobj.rst:844 +#: c-api/typeobj.rst:857 msgid "" "The :c:member:`~PyTypeObject.tp_as_number` field is not inherited, but the " "contained fields are inherited individually." msgstr "" -#: c-api/typeobj.rst:850 +#: c-api/typeobj.rst:863 msgid "" "Pointer to an additional structure that contains fields relevant only to " "objects which implement the sequence protocol. These fields are documented " "in :ref:`sequence-structs`." msgstr "" -#: c-api/typeobj.rst:856 +#: c-api/typeobj.rst:869 msgid "" "The :c:member:`~PyTypeObject.tp_as_sequence` field is not inherited, but the " "contained fields are inherited individually." msgstr "" -#: c-api/typeobj.rst:862 +#: c-api/typeobj.rst:875 msgid "" "Pointer to an additional structure that contains fields relevant only to " "objects which implement the mapping protocol. These fields are documented " "in :ref:`mapping-structs`." msgstr "" -#: c-api/typeobj.rst:868 +#: c-api/typeobj.rst:881 msgid "" "The :c:member:`~PyTypeObject.tp_as_mapping` field is not inherited, but the " "contained fields are inherited individually." msgstr "" -#: c-api/typeobj.rst:876 +#: c-api/typeobj.rst:889 msgid "" "An optional pointer to a function that implements the built-in function :" "func:`hash`." msgstr "" -#: c-api/typeobj.rst:879 +#: c-api/typeobj.rst:892 msgid "The signature is the same as for :c:func:`PyObject_Hash`::" msgstr "" -#: c-api/typeobj.rst:883 +#: c-api/typeobj.rst:894 +msgid "Py_hash_t tp_hash(PyObject *);" +msgstr "" + +#: c-api/typeobj.rst:896 msgid "" "The value ``-1`` should not be returned as a normal return value; when an " "error occurs during the computation of the hash value, the function should " "set an exception and return ``-1``." msgstr "" -#: c-api/typeobj.rst:887 +#: c-api/typeobj.rst:900 msgid "" "When this field is not set (*and* :c:member:`~PyTypeObject.tp_richcompare` " "is not set), an attempt to take the hash of the object raises :exc:" @@ -1591,7 +1748,7 @@ msgid "" "`PyObject_HashNotImplemented`." msgstr "" -#: c-api/typeobj.rst:891 +#: c-api/typeobj.rst:904 msgid "" "This field can be set explicitly to :c:func:`PyObject_HashNotImplemented` to " "block inheritance of the hash method from a parent type. This is interpreted " @@ -1602,13 +1759,13 @@ msgid "" "`PyObject_HashNotImplemented`." msgstr "" -#: c-api/typeobj.rst:1555 +#: c-api/typeobj.rst:1568 msgid "" "Group: :c:member:`~PyTypeObject.tp_hash`, :c:member:`~PyTypeObject." "tp_richcompare`" msgstr "" -#: c-api/typeobj.rst:903 +#: c-api/typeobj.rst:916 msgid "" "This field is inherited by subtypes together with :c:member:`~PyTypeObject." "tp_richcompare`: a subtype inherits both of :c:member:`~PyTypeObject." @@ -1617,14 +1774,18 @@ msgid "" "are both ``NULL``." msgstr "" -#: c-api/typeobj.rst:911 +#: c-api/typeobj.rst:924 msgid "" "An optional pointer to a function that implements calling the object. This " "should be ``NULL`` if the object is not callable. The signature is the same " "as for :c:func:`PyObject_Call`::" msgstr "" -#: c-api/typeobj.rst:924 +#: c-api/typeobj.rst:928 +msgid "PyObject *tp_call(PyObject *self, PyObject *args, PyObject *kwargs);" +msgstr "" + +#: c-api/typeobj.rst:937 msgid "" "An optional pointer to a function that implements the built-in operation :" "func:`str`. (Note that :class:`str` is a type now, and :func:`str` calls " @@ -1633,11 +1794,15 @@ msgid "" "this handler.)" msgstr "" -#: c-api/typeobj.rst:929 +#: c-api/typeobj.rst:942 msgid "The signature is the same as for :c:func:`PyObject_Str`::" msgstr "" -#: c-api/typeobj.rst:933 +#: c-api/typeobj.rst:944 +msgid "PyObject *tp_str(PyObject *self);" +msgstr "" + +#: c-api/typeobj.rst:946 msgid "" "The function must return a string or a Unicode object. It should be a " "\"friendly\" string representation of the object, as this is the " @@ -1645,28 +1810,32 @@ msgid "" "function." msgstr "" -#: c-api/typeobj.rst:943 +#: c-api/typeobj.rst:956 msgid "" "When this field is not set, :c:func:`PyObject_Repr` is called to return a " "string representation." msgstr "" -#: c-api/typeobj.rst:949 +#: c-api/typeobj.rst:962 msgid "An optional pointer to the get-attribute function." msgstr "" -#: c-api/typeobj.rst:951 +#: c-api/typeobj.rst:964 msgid "The signature is the same as for :c:func:`PyObject_GetAttr`::" msgstr "" -#: c-api/typeobj.rst:955 +#: c-api/typeobj.rst:966 +msgid "PyObject *tp_getattro(PyObject *self, PyObject *attr);" +msgstr "" + +#: c-api/typeobj.rst:968 msgid "" "It is usually convenient to set this field to :c:func:" "`PyObject_GenericGetAttr`, which implements the normal way of looking for " "object attributes." msgstr "" -#: c-api/typeobj.rst:962 +#: c-api/typeobj.rst:975 msgid "" "This field is inherited by subtypes together with :c:member:`~PyTypeObject." "tp_getattr`: a subtype inherits both :c:member:`~PyTypeObject.tp_getattr` " @@ -1675,15 +1844,19 @@ msgid "" "tp_getattro` are both ``NULL``." msgstr "" -#: c-api/typeobj.rst:968 +#: c-api/typeobj.rst:981 msgid ":c:data:`PyBaseObject_Type` uses :c:func:`PyObject_GenericGetAttr`." msgstr "" -#: c-api/typeobj.rst:975 +#: c-api/typeobj.rst:988 msgid "The signature is the same as for :c:func:`PyObject_SetAttr`::" msgstr "" -#: c-api/typeobj.rst:979 +#: c-api/typeobj.rst:990 +msgid "int tp_setattro(PyObject *self, PyObject *attr, PyObject *value);" +msgstr "" + +#: c-api/typeobj.rst:992 msgid "" "In addition, setting *value* to ``NULL`` to delete an attribute must be " "supported. It is usually convenient to set this field to :c:func:" @@ -1691,7 +1864,7 @@ msgid "" "attributes." msgstr "" -#: c-api/typeobj.rst:988 +#: c-api/typeobj.rst:1001 msgid "" "This field is inherited by subtypes together with :c:member:`~PyTypeObject." "tp_setattr`: a subtype inherits both :c:member:`~PyTypeObject.tp_setattr` " @@ -1700,24 +1873,24 @@ msgid "" "tp_setattro` are both ``NULL``." msgstr "" -#: c-api/typeobj.rst:994 +#: c-api/typeobj.rst:1007 msgid ":c:data:`PyBaseObject_Type` uses :c:func:`PyObject_GenericSetAttr`." msgstr "" -#: c-api/typeobj.rst:999 +#: c-api/typeobj.rst:1012 msgid "" "Pointer to an additional structure that contains fields relevant only to " "objects which implement the buffer interface. These fields are documented " "in :ref:`buffer-structs`." msgstr "" -#: c-api/typeobj.rst:1005 +#: c-api/typeobj.rst:1018 msgid "" "The :c:member:`~PyTypeObject.tp_as_buffer` field is not inherited, but the " "contained fields are inherited individually." msgstr "" -#: c-api/typeobj.rst:1011 +#: c-api/typeobj.rst:1024 msgid "" "This field is a bit mask of various flags. Some flags indicate variant " "semantics for certain situations; others are used to indicate that certain " @@ -1729,7 +1902,7 @@ msgid "" "accessed and must be considered to have a zero or ``NULL`` value instead." msgstr "" -#: c-api/typeobj.rst:1021 +#: c-api/typeobj.rst:1034 msgid "" "Inheritance of this field is complicated. Most flag bits are inherited " "individually, i.e. if the base type has a flag bit set, the subtype inherits " @@ -1745,17 +1918,17 @@ msgid "" "*really* inherited individually?" msgstr "" -#: c-api/typeobj.rst:1035 +#: c-api/typeobj.rst:1048 msgid "" ":c:data:`PyBaseObject_Type` uses ``Py_TPFLAGS_DEFAULT | " "Py_TPFLAGS_BASETYPE``." msgstr "" -#: c-api/typeobj.rst:1038 +#: c-api/typeobj.rst:1051 msgid "**Bit Masks:**" msgstr "" -#: c-api/typeobj.rst:1042 +#: c-api/typeobj.rst:1055 msgid "" "The following bit masks are currently defined; these can be ORed together " "using the ``|`` operator to form the value of the :c:member:`~PyTypeObject." @@ -1764,7 +1937,7 @@ msgid "" "zero." msgstr "" -#: c-api/typeobj.rst:1049 +#: c-api/typeobj.rst:1062 msgid "" "This bit is set when the type object itself is allocated on the heap, for " "example, types created dynamically using :c:func:`PyType_FromSpec`. In this " @@ -1777,30 +1950,30 @@ msgid "" "reference cycle with their own module object." msgstr "" -#: c-api/typeobj.rst:1071 c-api/typeobj.rst:1091 c-api/typeobj.rst:1123 +#: c-api/typeobj.rst:1084 c-api/typeobj.rst:1104 c-api/typeobj.rst:1136 msgid "???" msgstr "" -#: c-api/typeobj.rst:1065 +#: c-api/typeobj.rst:1078 msgid "" "This bit is set when the type can be used as the base type of another type. " "If this bit is clear, the type cannot be subtyped (similar to a \"final\" " "class in Java)." msgstr "" -#: c-api/typeobj.rst:1076 +#: c-api/typeobj.rst:1089 msgid "" "This bit is set when the type object has been fully initialized by :c:func:" "`PyType_Ready`." msgstr "" -#: c-api/typeobj.rst:1086 +#: c-api/typeobj.rst:1099 msgid "" "This bit is set while :c:func:`PyType_Ready` is in the process of " "initializing the type object." msgstr "" -#: c-api/typeobj.rst:1096 +#: c-api/typeobj.rst:1109 msgid "" "This bit is set when the object supports garbage collection. If this bit is " "set, instances must be created using :c:macro:`PyObject_GC_New` and " @@ -1810,13 +1983,13 @@ msgid "" "tp_clear` are present in the type object." msgstr "" -#: c-api/typeobj.rst:1426 c-api/typeobj.rst:1494 +#: c-api/typeobj.rst:1439 c-api/typeobj.rst:1507 msgid "" "Group: :c:macro:`Py_TPFLAGS_HAVE_GC`, :c:member:`~PyTypeObject." "tp_traverse`, :c:member:`~PyTypeObject.tp_clear`" msgstr "" -#: c-api/typeobj.rst:1107 +#: c-api/typeobj.rst:1120 msgid "" "The :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is inherited together with the :c:" "member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` " @@ -1826,99 +1999,99 @@ msgid "" "values." msgstr "" -#: c-api/typeobj.rst:1117 +#: c-api/typeobj.rst:1130 msgid "" "This is a bitmask of all the bits that pertain to the existence of certain " "fields in the type object and its extension structures. Currently, it " "includes the following bits: :c:macro:`Py_TPFLAGS_HAVE_STACKLESS_EXTENSION`." msgstr "" -#: c-api/typeobj.rst:1128 +#: c-api/typeobj.rst:1141 msgid "This bit indicates that objects behave like unbound methods." msgstr "" -#: c-api/typeobj.rst:1130 +#: c-api/typeobj.rst:1143 msgid "If this flag is set for ``type(meth)``, then:" msgstr "" -#: c-api/typeobj.rst:1132 +#: c-api/typeobj.rst:1145 msgid "" "``meth.__get__(obj, cls)(*args, **kwds)`` (with ``obj`` not None) must be " "equivalent to ``meth(obj, *args, **kwds)``." msgstr "" -#: c-api/typeobj.rst:1135 +#: c-api/typeobj.rst:1148 msgid "" "``meth.__get__(None, cls)(*args, **kwds)`` must be equivalent to " "``meth(*args, **kwds)``." msgstr "" -#: c-api/typeobj.rst:1138 +#: c-api/typeobj.rst:1151 msgid "" "This flag enables an optimization for typical method calls like ``obj." "meth()``: it avoids creating a temporary \"bound method\" object for ``obj." "meth``." msgstr "" -#: c-api/typeobj.rst:1146 +#: c-api/typeobj.rst:1159 msgid "" "This flag is never inherited by types without the :c:macro:" "`Py_TPFLAGS_IMMUTABLETYPE` flag set. For extension types, it is inherited " "whenever :c:member:`~PyTypeObject.tp_descr_get` is inherited." msgstr "" -#: c-api/typeobj.rst:1152 +#: c-api/typeobj.rst:1165 msgid "" -"This bit indicates that instances of the class have a ``__dict__`` " +"This bit indicates that instances of the class have a `~object.__dict__` " "attribute, and that the space for the dictionary is managed by the VM." msgstr "" -#: c-api/typeobj.rst:1155 +#: c-api/typeobj.rst:1168 msgid "If this flag is set, :c:macro:`Py_TPFLAGS_HAVE_GC` should also be set." msgstr "" -#: c-api/typeobj.rst:1161 +#: c-api/typeobj.rst:1174 msgid "" "This flag is inherited unless the :c:member:`~PyTypeObject.tp_dictoffset` " "field is set in a superclass." msgstr "" -#: c-api/typeobj.rst:1167 +#: c-api/typeobj.rst:1180 msgid "" "This bit indicates that instances of the class should be weakly " "referenceable." msgstr "" -#: c-api/typeobj.rst:1174 +#: c-api/typeobj.rst:1187 msgid "" "This flag is inherited unless the :c:member:`~PyTypeObject." "tp_weaklistoffset` field is set in a superclass." msgstr "" -#: c-api/typeobj.rst:1180 +#: c-api/typeobj.rst:1193 msgid "" "Only usable with variable-size types, i.e. ones with non-zero :c:member:" "`~PyTypeObject.tp_itemsize`." msgstr "" -#: c-api/typeobj.rst:1183 +#: c-api/typeobj.rst:1196 msgid "" "Indicates that the variable-sized portion of an instance of this type is at " "the end of the instance's memory area, at an offset of ``Py_TYPE(obj)-" ">tp_basicsize`` (which may be different in each subclass)." msgstr "" -#: c-api/typeobj.rst:1188 +#: c-api/typeobj.rst:1201 msgid "" "When setting this flag, be sure that all superclasses either use this memory " "layout, or are not variable-sized. Python does not check this." msgstr "" -#: c-api/typeobj.rst:1196 +#: c-api/typeobj.rst:1209 msgid "This flag is inherited." msgstr "" -#: c-api/typeobj.rst:1210 +#: c-api/typeobj.rst:1223 msgid "" "These flags are used by functions such as :c:func:`PyLong_Check` to quickly " "determine if a type is a subclass of a built-in type; such specific checks " @@ -1928,90 +2101,90 @@ msgid "" "behave differently depending on what kind of check is used." msgstr "" -#: c-api/typeobj.rst:1221 +#: c-api/typeobj.rst:1234 msgid "" "This bit is set when the :c:member:`~PyTypeObject.tp_finalize` slot is " "present in the type structure." msgstr "" -#: c-api/typeobj.rst:1226 +#: c-api/typeobj.rst:1239 msgid "" "This flag isn't necessary anymore, as the interpreter assumes the :c:member:" "`~PyTypeObject.tp_finalize` slot is always present in the type structure." msgstr "" -#: c-api/typeobj.rst:1234 +#: c-api/typeobj.rst:1247 msgid "" "This bit is set when the class implements the :ref:`vectorcall protocol " "`. See :c:member:`~PyTypeObject.tp_vectorcall_offset` for " "details." msgstr "" -#: c-api/typeobj.rst:1240 +#: c-api/typeobj.rst:1253 msgid "" "This bit is inherited if :c:member:`~PyTypeObject.tp_call` is also inherited." msgstr "" -#: c-api/typeobj.rst:1247 +#: c-api/typeobj.rst:1260 msgid "" "This flag is now removed from a class when the class's :py:meth:`~object." "__call__` method is reassigned." msgstr "" -#: c-api/typeobj.rst:1250 +#: c-api/typeobj.rst:1263 msgid "This flag can now be inherited by mutable classes." msgstr "" -#: c-api/typeobj.rst:1254 +#: c-api/typeobj.rst:1267 msgid "" "This bit is set for type objects that are immutable: type attributes cannot " "be set nor deleted." msgstr "" -#: c-api/typeobj.rst:1256 +#: c-api/typeobj.rst:1269 msgid "" ":c:func:`PyType_Ready` automatically applies this flag to :ref:`static types " "`." msgstr "" -#: c-api/typeobj.rst:1261 +#: c-api/typeobj.rst:1274 msgid "This flag is not inherited." msgstr "" -#: c-api/typeobj.rst:1267 +#: c-api/typeobj.rst:1280 msgid "" "Disallow creating instances of the type: set :c:member:`~PyTypeObject." "tp_new` to NULL and don't create the ``__new__`` key in the type dictionary." msgstr "" -#: c-api/typeobj.rst:1271 +#: c-api/typeobj.rst:1284 msgid "" "The flag must be set before creating the type, not after. For example, it " "must be set before :c:func:`PyType_Ready` is called on the type." msgstr "" -#: c-api/typeobj.rst:1274 +#: c-api/typeobj.rst:1287 msgid "" "The flag is set automatically on :ref:`static types ` if :c:" "member:`~PyTypeObject.tp_base` is NULL or ``&PyBaseObject_Type`` and :c:" "member:`~PyTypeObject.tp_new` is NULL." msgstr "" -#: c-api/typeobj.rst:1280 +#: c-api/typeobj.rst:1293 msgid "" "This flag is not inherited. However, subclasses will not be instantiable " "unless they provide a non-NULL :c:member:`~PyTypeObject.tp_new` (which is " "only possible via the C API)." msgstr "" -#: c-api/typeobj.rst:1287 +#: c-api/typeobj.rst:1300 msgid "" "To disallow instantiating a class directly but allow instantiating its " "subclasses (e.g. for an :term:`abstract base class`), do not use this flag. " "Instead, make :c:member:`~PyTypeObject.tp_new` only succeed for subclasses." msgstr "" -#: c-api/typeobj.rst:1298 +#: c-api/typeobj.rst:1311 msgid "" "This bit indicates that instances of the class may match mapping patterns " "when used as the subject of a :keyword:`match` block. It is automatically " @@ -2019,23 +2192,23 @@ msgid "" "unset when registering :class:`collections.abc.Sequence`." msgstr "" -#: c-api/typeobj.rst:1327 +#: c-api/typeobj.rst:1340 msgid "" ":c:macro:`Py_TPFLAGS_MAPPING` and :c:macro:`Py_TPFLAGS_SEQUENCE` are " "mutually exclusive; it is an error to enable both flags simultaneously." msgstr "" -#: c-api/typeobj.rst:1310 +#: c-api/typeobj.rst:1323 msgid "" "This flag is inherited by types that do not already set :c:macro:" "`Py_TPFLAGS_SEQUENCE`." msgstr "" -#: c-api/typeobj.rst:1335 +#: c-api/typeobj.rst:1348 msgid ":pep:`634` -- Structural Pattern Matching: Specification" msgstr "" -#: c-api/typeobj.rst:1320 +#: c-api/typeobj.rst:1333 msgid "" "This bit indicates that instances of the class may match sequence patterns " "when used as the subject of a :keyword:`match` block. It is automatically " @@ -2043,49 +2216,53 @@ msgid "" "unset when registering :class:`collections.abc.Mapping`." msgstr "" -#: c-api/typeobj.rst:1332 +#: c-api/typeobj.rst:1345 msgid "" "This flag is inherited by types that do not already set :c:macro:" "`Py_TPFLAGS_MAPPING`." msgstr "" -#: c-api/typeobj.rst:1342 +#: c-api/typeobj.rst:1355 msgid "" "Internal. Do not set or unset this flag. To indicate that a class has " "changed call :c:func:`PyType_Modified`" msgstr "" -#: c-api/typeobj.rst:1346 +#: c-api/typeobj.rst:1359 msgid "" "This flag is present in header files, but is an internal feature and should " "not be used. It will be removed in a future version of CPython" msgstr "" -#: c-api/typeobj.rst:1352 +#: c-api/typeobj.rst:1365 msgid "" "An optional pointer to a NUL-terminated C string giving the docstring for " -"this type object. This is exposed as the :attr:`__doc__` attribute on the " -"type and instances of the type." +"this type object. This is exposed as the :attr:`~type.__doc__` attribute on " +"the type and instances of the type." msgstr "" -#: c-api/typeobj.rst:1358 +#: c-api/typeobj.rst:1371 msgid "This field is *not* inherited by subtypes." msgstr "" -#: c-api/typeobj.rst:1363 +#: c-api/typeobj.rst:1376 msgid "" "An optional pointer to a traversal function for the garbage collector. This " "is only used if the :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is set. The " "signature is::" msgstr "" -#: c-api/typeobj.rst:1489 +#: c-api/typeobj.rst:1379 +msgid "int tp_traverse(PyObject *self, visitproc visit, void *arg);" +msgstr "" + +#: c-api/typeobj.rst:1502 msgid "" "More information about Python's garbage collection scheme can be found in " "section :ref:`supporting-cycle-detection`." msgstr "" -#: c-api/typeobj.rst:1371 +#: c-api/typeobj.rst:1384 msgid "" "The :c:member:`~PyTypeObject.tp_traverse` pointer is used by the garbage " "collector to detect reference cycles. A typical implementation of a :c:" @@ -2095,7 +2272,19 @@ msgid "" "`!_thread` extension module::" msgstr "" -#: c-api/typeobj.rst:1386 +#: c-api/typeobj.rst:1390 +msgid "" +"static int\n" +"local_traverse(localobject *self, visitproc visit, void *arg)\n" +"{\n" +" Py_VISIT(self->args);\n" +" Py_VISIT(self->kw);\n" +" Py_VISIT(self->dict);\n" +" return 0;\n" +"}" +msgstr "" + +#: c-api/typeobj.rst:1399 msgid "" "Note that :c:func:`Py_VISIT` is called only on those members that can " "participate in reference cycles. Although there is also a ``self->key`` " @@ -2103,14 +2292,14 @@ msgid "" "part of a reference cycle." msgstr "" -#: c-api/typeobj.rst:1390 +#: c-api/typeobj.rst:1403 msgid "" "On the other hand, even if you know a member can never be part of a cycle, " "as a debugging aid you may want to visit it anyway just so the :mod:`gc` " "module's :func:`~gc.get_referents` function will include it." msgstr "" -#: c-api/typeobj.rst:1395 +#: c-api/typeobj.rst:1408 msgid "" "When implementing :c:member:`~PyTypeObject.tp_traverse`, only the members " "that the instance *owns* (by having :term:`strong references ` hold a reference to " "their type. Their traversal function must therefore either visit :c:func:" @@ -2139,14 +2328,14 @@ msgid "" "superclass). If they do not, the type object may not be garbage-collected." msgstr "" -#: c-api/typeobj.rst:1419 +#: c-api/typeobj.rst:1432 msgid "" "Heap-allocated types are expected to visit ``Py_TYPE(self)`` in " "``tp_traverse``. In earlier versions of Python, due to `bug 40217 `_, doing this may lead to crashes in subclasses." msgstr "" -#: c-api/typeobj.rst:1428 +#: c-api/typeobj.rst:1441 msgid "" "This field is inherited by subtypes together with :c:member:`~PyTypeObject." "tp_clear` and the :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit: the flag bit, :c:" @@ -2154,14 +2343,18 @@ msgid "" "are all inherited from the base type if they are all zero in the subtype." msgstr "" -#: c-api/typeobj.rst:1436 +#: c-api/typeobj.rst:1449 msgid "" "An optional pointer to a clear function for the garbage collector. This is " "only used if the :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is set. The " "signature is::" msgstr "" -#: c-api/typeobj.rst:1441 +#: c-api/typeobj.rst:1452 +msgid "int tp_clear(PyObject *);" +msgstr "" + +#: c-api/typeobj.rst:1454 msgid "" "The :c:member:`~PyTypeObject.tp_clear` member function is used to break " "reference cycles in cyclic garbage detected by the garbage collector. Taken " @@ -2176,7 +2369,7 @@ msgid "" "good reason to avoid implementing :c:member:`~PyTypeObject.tp_clear`." msgstr "" -#: c-api/typeobj.rst:1451 +#: c-api/typeobj.rst:1464 msgid "" "Implementations of :c:member:`~PyTypeObject.tp_clear` should drop the " "instance's references to those of its members that may be Python objects, " @@ -2184,7 +2377,20 @@ msgid "" "example::" msgstr "" -#: c-api/typeobj.rst:1465 +#: c-api/typeobj.rst:1468 +msgid "" +"static int\n" +"local_clear(localobject *self)\n" +"{\n" +" Py_CLEAR(self->key);\n" +" Py_CLEAR(self->args);\n" +" Py_CLEAR(self->kw);\n" +" Py_CLEAR(self->dict);\n" +" return 0;\n" +"}" +msgstr "" + +#: c-api/typeobj.rst:1478 msgid "" "The :c:func:`Py_CLEAR` macro should be used, because clearing references is " "delicate: the reference to the contained object must not be released (via :" @@ -2199,7 +2405,7 @@ msgid "" "performs the operations in a safe order." msgstr "" -#: c-api/typeobj.rst:1477 +#: c-api/typeobj.rst:1490 msgid "" "Note that :c:member:`~PyTypeObject.tp_clear` is not *always* called before " "an instance is deallocated. For example, when reference counting is enough " @@ -2207,7 +2413,7 @@ msgid "" "is not involved and :c:member:`~PyTypeObject.tp_dealloc` is called directly." msgstr "" -#: c-api/typeobj.rst:1483 +#: c-api/typeobj.rst:1496 msgid "" "Because the goal of :c:member:`~PyTypeObject.tp_clear` functions is to break " "reference cycles, it's not necessary to clear contained objects like Python " @@ -2217,7 +2423,7 @@ msgid "" "invoke :c:member:`~PyTypeObject.tp_clear`." msgstr "" -#: c-api/typeobj.rst:1496 +#: c-api/typeobj.rst:1509 msgid "" "This field is inherited by subtypes together with :c:member:`~PyTypeObject." "tp_traverse` and the :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit: the flag bit, :" @@ -2225,18 +2431,22 @@ msgid "" "are all inherited from the base type if they are all zero in the subtype." msgstr "" -#: c-api/typeobj.rst:1504 +#: c-api/typeobj.rst:1517 msgid "" "An optional pointer to the rich comparison function, whose signature is::" msgstr "" -#: c-api/typeobj.rst:1508 +#: c-api/typeobj.rst:1519 +msgid "PyObject *tp_richcompare(PyObject *self, PyObject *other, int op);" +msgstr "" + +#: c-api/typeobj.rst:1521 msgid "" "The first parameter is guaranteed to be an instance of the type that is " "defined by :c:type:`PyTypeObject`." msgstr "" -#: c-api/typeobj.rst:1511 +#: c-api/typeobj.rst:1524 msgid "" "The function should return the result of the comparison (usually ``Py_True`` " "or ``Py_False``). If the comparison is undefined, it must return " @@ -2244,50 +2454,50 @@ msgid "" "set an exception condition." msgstr "" -#: c-api/typeobj.rst:1516 +#: c-api/typeobj.rst:1529 msgid "" "The following constants are defined to be used as the third argument for :c:" "member:`~PyTypeObject.tp_richcompare` and for :c:func:`PyObject_RichCompare`:" msgstr "" -#: c-api/typeobj.rst:1522 +#: c-api/typeobj.rst:1535 msgid "Constant" msgstr "" -#: c-api/typeobj.rst:1522 +#: c-api/typeobj.rst:1535 msgid "Comparison" msgstr "" -#: c-api/typeobj.rst:1524 +#: c-api/typeobj.rst:1537 msgid "``<``" msgstr "" -#: c-api/typeobj.rst:1526 +#: c-api/typeobj.rst:1539 msgid "``<=``" msgstr "" -#: c-api/typeobj.rst:1528 +#: c-api/typeobj.rst:1541 msgid "``==``" msgstr "" -#: c-api/typeobj.rst:1530 +#: c-api/typeobj.rst:1543 msgid "``!=``" msgstr "" -#: c-api/typeobj.rst:1532 +#: c-api/typeobj.rst:1545 msgid "``>``" msgstr "" -#: c-api/typeobj.rst:1534 +#: c-api/typeobj.rst:1547 msgid "``>=``" msgstr "" -#: c-api/typeobj.rst:1537 +#: c-api/typeobj.rst:1550 msgid "" "The following macro is defined to ease writing rich comparison functions:" msgstr "" -#: c-api/typeobj.rst:1541 +#: c-api/typeobj.rst:1554 msgid "" "Return ``Py_True`` or ``Py_False`` from the function, depending on the " "result of a comparison. VAL_A and VAL_B must be orderable by C comparison " @@ -2295,15 +2505,15 @@ msgid "" "specifies the requested operation, as for :c:func:`PyObject_RichCompare`." msgstr "" -#: c-api/typeobj.rst:1547 +#: c-api/typeobj.rst:1560 msgid "The returned value is a new :term:`strong reference`." msgstr "" -#: c-api/typeobj.rst:1549 +#: c-api/typeobj.rst:1562 msgid "On error, sets an exception and returns ``NULL`` from the function." msgstr "" -#: c-api/typeobj.rst:1557 +#: c-api/typeobj.rst:1570 msgid "" "This field is inherited by subtypes together with :c:member:`~PyTypeObject." "tp_hash`: a subtype inherits :c:member:`~PyTypeObject.tp_richcompare` and :c:" @@ -2311,7 +2521,7 @@ msgid "" "tp_richcompare` and :c:member:`~PyTypeObject.tp_hash` are both ``NULL``." msgstr "" -#: c-api/typeobj.rst:1564 +#: c-api/typeobj.rst:1577 msgid "" ":c:data:`PyBaseObject_Type` provides a :c:member:`~PyTypeObject." "tp_richcompare` implementation, which may be inherited. However, if only :c:" @@ -2320,13 +2530,13 @@ msgid "" "comparisons." msgstr "" -#: c-api/typeobj.rst:1573 +#: c-api/typeobj.rst:1586 msgid "" "While this field is still supported, :c:macro:`Py_TPFLAGS_MANAGED_WEAKREF` " "should be used instead, if at all possible." msgstr "" -#: c-api/typeobj.rst:1576 +#: c-api/typeobj.rst:1589 msgid "" "If the instances of this type are weakly referenceable, this field is " "greater than zero and contains the offset in the instance structure of the " @@ -2336,19 +2546,19 @@ msgid "" "`PyObject*` which is initialized to ``NULL``." msgstr "" -#: c-api/typeobj.rst:1583 +#: c-api/typeobj.rst:1596 msgid "" "Do not confuse this field with :c:member:`~PyTypeObject.tp_weaklist`; that " "is the list head for weak references to the type object itself." msgstr "" -#: c-api/typeobj.rst:1586 +#: c-api/typeobj.rst:1599 msgid "" "It is an error to set both the :c:macro:`Py_TPFLAGS_MANAGED_WEAKREF` bit " "and :c:member:`~PyTypeObject.tp_weaklistoffset`." msgstr "" -#: c-api/typeobj.rst:1591 +#: c-api/typeobj.rst:1604 msgid "" "This field is inherited by subtypes, but see the rules listed below. A " "subtype may override this offset; this means that the subtype uses a " @@ -2357,7 +2567,7 @@ msgid "" "not be a problem." msgstr "" -#: c-api/typeobj.rst:1598 +#: c-api/typeobj.rst:1611 msgid "" "If the :c:macro:`Py_TPFLAGS_MANAGED_WEAKREF` bit is set in the :c:member:" "`~PyTypeObject.tp_flags` field, then :c:member:`~PyTypeObject." @@ -2365,24 +2575,32 @@ msgid "" "unsafe to use this field." msgstr "" -#: c-api/typeobj.rst:1606 +#: c-api/typeobj.rst:1619 msgid "" "An optional pointer to a function that returns an :term:`iterator` for the " "object. Its presence normally signals that the instances of this type are :" "term:`iterable` (although sequences may be iterable without this function)." msgstr "" -#: c-api/typeobj.rst:1610 +#: c-api/typeobj.rst:1623 msgid "This function has the same signature as :c:func:`PyObject_GetIter`::" msgstr "" -#: c-api/typeobj.rst:1621 +#: c-api/typeobj.rst:1625 +msgid "PyObject *tp_iter(PyObject *self);" +msgstr "" + +#: c-api/typeobj.rst:1634 msgid "" "An optional pointer to a function that returns the next item in an :term:" "`iterator`. The signature is::" msgstr "" -#: c-api/typeobj.rst:1626 +#: c-api/typeobj.rst:1637 +msgid "PyObject *tp_iternext(PyObject *self);" +msgstr "" + +#: c-api/typeobj.rst:1639 msgid "" "When the iterator is exhausted, it must return ``NULL``; a :exc:" "`StopIteration` exception may or may not be set. When another error occurs, " @@ -2390,74 +2608,74 @@ msgid "" "this type are iterators." msgstr "" -#: c-api/typeobj.rst:1631 +#: c-api/typeobj.rst:1644 msgid "" "Iterator types should also define the :c:member:`~PyTypeObject.tp_iter` " "function, and that function should return the iterator instance itself (not " "a new iterator instance)." msgstr "" -#: c-api/typeobj.rst:1635 +#: c-api/typeobj.rst:1648 msgid "This function has the same signature as :c:func:`PyIter_Next`." msgstr "" -#: c-api/typeobj.rst:1644 +#: c-api/typeobj.rst:1657 msgid "" "An optional pointer to a static ``NULL``-terminated array of :c:type:" "`PyMethodDef` structures, declaring regular methods of this type." msgstr "" -#: c-api/typeobj.rst:1647 +#: c-api/typeobj.rst:1660 msgid "" "For each entry in the array, an entry is added to the type's dictionary " "(see :c:member:`~PyTypeObject.tp_dict` below) containing a method descriptor." msgstr "" -#: c-api/typeobj.rst:1652 +#: c-api/typeobj.rst:1665 msgid "" "This field is not inherited by subtypes (methods are inherited through a " "different mechanism)." msgstr "" -#: c-api/typeobj.rst:1658 +#: c-api/typeobj.rst:1671 msgid "" "An optional pointer to a static ``NULL``-terminated array of :c:type:" "`PyMemberDef` structures, declaring regular data members (fields or slots) " "of instances of this type." msgstr "" -#: c-api/typeobj.rst:1662 +#: c-api/typeobj.rst:1675 msgid "" "For each entry in the array, an entry is added to the type's dictionary " "(see :c:member:`~PyTypeObject.tp_dict` below) containing a member descriptor." msgstr "" -#: c-api/typeobj.rst:1667 +#: c-api/typeobj.rst:1680 msgid "" "This field is not inherited by subtypes (members are inherited through a " "different mechanism)." msgstr "" -#: c-api/typeobj.rst:1673 +#: c-api/typeobj.rst:1686 msgid "" "An optional pointer to a static ``NULL``-terminated array of :c:type:" "`PyGetSetDef` structures, declaring computed attributes of instances of this " "type." msgstr "" -#: c-api/typeobj.rst:1676 +#: c-api/typeobj.rst:1689 msgid "" "For each entry in the array, an entry is added to the type's dictionary " "(see :c:member:`~PyTypeObject.tp_dict` below) containing a getset descriptor." msgstr "" -#: c-api/typeobj.rst:1681 +#: c-api/typeobj.rst:1694 msgid "" "This field is not inherited by subtypes (computed attributes are inherited " "through a different mechanism)." msgstr "" -#: c-api/typeobj.rst:1687 +#: c-api/typeobj.rst:1700 msgid "" "An optional pointer to a base type from which type properties are " "inherited. At this level, only single inheritance is supported; multiple " @@ -2465,7 +2683,7 @@ msgid "" "metatype." msgstr "" -#: c-api/typeobj.rst:1695 +#: c-api/typeobj.rst:1708 msgid "" "Slot initialization is subject to the rules of initializing globals. C99 " "requires the initializers to be \"address constants\". Function designators " @@ -2473,7 +2691,7 @@ msgid "" "valid C99 address constants." msgstr "" -#: c-api/typeobj.rst:1700 +#: c-api/typeobj.rst:1713 msgid "" "However, the unary '&' operator applied to a non-static variable like :c:" "data:`PyBaseObject_Type` is not required to produce an address constant. " @@ -2481,27 +2699,27 @@ msgid "" "strictly standard conforming in this particular behavior." msgstr "" -#: c-api/typeobj.rst:1706 +#: c-api/typeobj.rst:1719 msgid "" "Consequently, :c:member:`~PyTypeObject.tp_base` should be set in the " "extension module's init function." msgstr "" -#: c-api/typeobj.rst:1711 +#: c-api/typeobj.rst:1724 msgid "This field is not inherited by subtypes (obviously)." msgstr "" -#: c-api/typeobj.rst:1715 +#: c-api/typeobj.rst:1728 msgid "" "This field defaults to ``&PyBaseObject_Type`` (which to Python programmers " "is known as the type :class:`object`)." msgstr "" -#: c-api/typeobj.rst:1721 +#: c-api/typeobj.rst:1734 msgid "The type's dictionary is stored here by :c:func:`PyType_Ready`." msgstr "" -#: c-api/typeobj.rst:1723 +#: c-api/typeobj.rst:1736 msgid "" "This field should normally be initialized to ``NULL`` before PyType_Ready is " "called; it may also be initialized to a dictionary containing initial " @@ -2512,62 +2730,70 @@ msgid "" "be treated as read-only." msgstr "" -#: c-api/typeobj.rst:1731 +#: c-api/typeobj.rst:1744 msgid "" "Some types may not store their dictionary in this slot. Use :c:func:" "`PyType_GetDict` to retrieve the dictionary for an arbitrary type." msgstr "" -#: c-api/typeobj.rst:1737 +#: c-api/typeobj.rst:1750 msgid "" "Internals detail: For static builtin types, this is always ``NULL``. " "Instead, the dict for such types is stored on ``PyInterpreterState``. Use :c:" "func:`PyType_GetDict` to get the dict for an arbitrary type." msgstr "" -#: c-api/typeobj.rst:1743 +#: c-api/typeobj.rst:1756 msgid "" "This field is not inherited by subtypes (though the attributes defined in " "here are inherited through a different mechanism)." msgstr "" -#: c-api/typeobj.rst:1748 +#: c-api/typeobj.rst:1761 msgid "" "If this field is ``NULL``, :c:func:`PyType_Ready` will assign a new " "dictionary to it." msgstr "" -#: c-api/typeobj.rst:1753 +#: c-api/typeobj.rst:1766 msgid "" "It is not safe to use :c:func:`PyDict_SetItem` on or otherwise modify :c:" "member:`~PyTypeObject.tp_dict` with the dictionary C-API." msgstr "" -#: c-api/typeobj.rst:1759 +#: c-api/typeobj.rst:1772 msgid "An optional pointer to a \"descriptor get\" function." msgstr "" -#: c-api/typeobj.rst:1777 c-api/typeobj.rst:1871 c-api/typeobj.rst:1895 +#: c-api/typeobj.rst:1790 c-api/typeobj.rst:1884 c-api/typeobj.rst:1908 msgid "The function signature is::" msgstr "" -#: c-api/typeobj.rst:1774 +#: c-api/typeobj.rst:1776 +msgid "PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);" +msgstr "" + +#: c-api/typeobj.rst:1787 msgid "" "An optional pointer to a function for setting and deleting a descriptor's " "value." msgstr "" -#: c-api/typeobj.rst:1781 +#: c-api/typeobj.rst:1792 +msgid "int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);" +msgstr "" + +#: c-api/typeobj.rst:1794 msgid "The *value* argument is set to ``NULL`` to delete the value." msgstr "" -#: c-api/typeobj.rst:1792 +#: c-api/typeobj.rst:1805 msgid "" "While this field is still supported, :c:macro:`Py_TPFLAGS_MANAGED_DICT` " "should be used instead, if at all possible." msgstr "" -#: c-api/typeobj.rst:1795 +#: c-api/typeobj.rst:1808 msgid "" "If the instances of this type have a dictionary containing instance " "variables, this field is non-zero and contains the offset in the instances " @@ -2575,19 +2801,19 @@ msgid "" "func:`PyObject_GenericGetAttr`." msgstr "" -#: c-api/typeobj.rst:1800 +#: c-api/typeobj.rst:1813 msgid "" "Do not confuse this field with :c:member:`~PyTypeObject.tp_dict`; that is " "the dictionary for attributes of the type object itself." msgstr "" -#: c-api/typeobj.rst:1803 +#: c-api/typeobj.rst:1816 msgid "" "The value specifies the offset of the dictionary from the start of the " "instance structure." msgstr "" -#: c-api/typeobj.rst:1805 +#: c-api/typeobj.rst:1818 msgid "" "The :c:member:`~PyTypeObject.tp_dictoffset` should be regarded as write-" "only. To get the pointer to the dictionary call :c:func:" @@ -2596,13 +2822,13 @@ msgid "" "to call :c:func:`PyObject_GetAttr` when accessing an attribute on the object." msgstr "" -#: c-api/typeobj.rst:1811 +#: c-api/typeobj.rst:1824 msgid "" "It is an error to set both the :c:macro:`Py_TPFLAGS_MANAGED_WEAKREF` bit " "and :c:member:`~PyTypeObject.tp_dictoffset`." msgstr "" -#: c-api/typeobj.rst:1816 +#: c-api/typeobj.rst:1829 msgid "" "This field is inherited by subtypes. A subtype should not override this " "offset; doing so could be unsafe, if C code tries to access the dictionary " @@ -2610,25 +2836,25 @@ msgid "" "`Py_TPFLAGS_MANAGED_DICT`." msgstr "" -#: c-api/typeobj.rst:1823 +#: c-api/typeobj.rst:1836 msgid "" "This slot has no default. For :ref:`static types `, if the " "field is ``NULL`` then no :attr:`~object.__dict__` gets created for " "instances." msgstr "" -#: c-api/typeobj.rst:1826 +#: c-api/typeobj.rst:1839 msgid "" "If the :c:macro:`Py_TPFLAGS_MANAGED_DICT` bit is set in the :c:member:" "`~PyTypeObject.tp_dict` field, then :c:member:`~PyTypeObject.tp_dictoffset` " "will be set to ``-1``, to indicate that it is unsafe to use this field." msgstr "" -#: c-api/typeobj.rst:1834 +#: c-api/typeobj.rst:1847 msgid "An optional pointer to an instance initialization function." msgstr "" -#: c-api/typeobj.rst:1836 +#: c-api/typeobj.rst:1849 msgid "" "This function corresponds to the :meth:`~object.__init__` method of " "classes. Like :meth:`!__init__`, it is possible to create an instance " @@ -2636,14 +2862,18 @@ msgid "" "instance by calling its :meth:`!__init__` method again." msgstr "" -#: c-api/typeobj.rst:1845 +#: c-api/typeobj.rst:1856 +msgid "int tp_init(PyObject *self, PyObject *args, PyObject *kwds);" +msgstr "" + +#: c-api/typeobj.rst:1858 msgid "" "The self argument is the instance to be initialized; the *args* and *kwds* " "arguments represent positional and keyword arguments of the call to :meth:" "`~object.__init__`." msgstr "" -#: c-api/typeobj.rst:1849 +#: c-api/typeobj.rst:1862 msgid "" "The :c:member:`~PyTypeObject.tp_init` function, if not ``NULL``, is called " "when an instance is created normally by calling its type, after the type's :" @@ -2655,43 +2885,52 @@ msgid "" "subtype's :c:member:`~PyTypeObject.tp_init` is called." msgstr "" -#: c-api/typeobj.rst:1856 +#: c-api/typeobj.rst:1869 msgid "Returns ``0`` on success, ``-1`` and sets an exception on error." msgstr "" -#: c-api/typeobj.rst:1864 +#: c-api/typeobj.rst:1877 msgid "" "For :ref:`static types ` this field does not have a default." msgstr "" -#: c-api/typeobj.rst:1869 +#: c-api/typeobj.rst:1882 msgid "An optional pointer to an instance allocation function." msgstr "" -#: c-api/typeobj.rst:1877 +#: c-api/typeobj.rst:1886 +msgid "PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems);" +msgstr "" + +#: c-api/typeobj.rst:1890 msgid "" "This field is inherited by static subtypes, but not by dynamic subtypes " "(subtypes created by a class statement)." msgstr "" -#: c-api/typeobj.rst:1882 +#: c-api/typeobj.rst:1895 msgid "" "For dynamic subtypes, this field is always set to :c:func:" "`PyType_GenericAlloc`, to force a standard heap allocation strategy." msgstr "" -#: c-api/typeobj.rst:1886 +#: c-api/typeobj.rst:1899 msgid "" "For static subtypes, :c:data:`PyBaseObject_Type` uses :c:func:" "`PyType_GenericAlloc`. That is the recommended value for all statically " "defined types." msgstr "" -#: c-api/typeobj.rst:1893 +#: c-api/typeobj.rst:1906 msgid "An optional pointer to an instance creation function." msgstr "" -#: c-api/typeobj.rst:1899 +#: c-api/typeobj.rst:1910 +msgid "" +"PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds);" +msgstr "" + +#: c-api/typeobj.rst:1912 msgid "" "The *subtype* argument is the type of the object being created; the *args* " "and *kwds* arguments represent positional and keyword arguments of the call " @@ -2700,7 +2939,7 @@ msgid "" "that type (but not an unrelated type)." msgstr "" -#: c-api/typeobj.rst:1905 +#: c-api/typeobj.rst:1918 msgid "" "The :c:member:`~PyTypeObject.tp_new` function should call ``subtype-" ">tp_alloc(subtype, nitems)`` to allocate space for the object, and then do " @@ -2712,20 +2951,20 @@ msgid "" "be deferred to :c:member:`~PyTypeObject.tp_init`." msgstr "" -#: c-api/typeobj.rst:1913 +#: c-api/typeobj.rst:1926 msgid "" "Set the :c:macro:`Py_TPFLAGS_DISALLOW_INSTANTIATION` flag to disallow " "creating instances of the type in Python." msgstr "" -#: c-api/typeobj.rst:1918 +#: c-api/typeobj.rst:1931 msgid "" "This field is inherited by subtypes, except it is not inherited by :ref:" "`static types ` whose :c:member:`~PyTypeObject.tp_base` is " "``NULL`` or ``&PyBaseObject_Type``." msgstr "" -#: c-api/typeobj.rst:1924 +#: c-api/typeobj.rst:1937 msgid "" "For :ref:`static types ` this field has no default. This means " "if the slot is defined as ``NULL``, the type cannot be called to create new " @@ -2733,40 +2972,44 @@ msgid "" "factory function." msgstr "" -#: c-api/typeobj.rst:1932 +#: c-api/typeobj.rst:1945 msgid "" "An optional pointer to an instance deallocation function. Its signature is::" msgstr "" -#: c-api/typeobj.rst:1936 +#: c-api/typeobj.rst:1947 +msgid "void tp_free(void *self);" +msgstr "" + +#: c-api/typeobj.rst:1949 msgid "" "An initializer that is compatible with this signature is :c:func:" "`PyObject_Free`." msgstr "" -#: c-api/typeobj.rst:1940 +#: c-api/typeobj.rst:1953 msgid "" "This field is inherited by static subtypes, but not by dynamic subtypes " "(subtypes created by a class statement)" msgstr "" -#: c-api/typeobj.rst:1945 +#: c-api/typeobj.rst:1958 msgid "" "In dynamic subtypes, this field is set to a deallocator suitable to match :c:" "func:`PyType_GenericAlloc` and the value of the :c:macro:" "`Py_TPFLAGS_HAVE_GC` flag bit." msgstr "" -#: c-api/typeobj.rst:1949 +#: c-api/typeobj.rst:1962 msgid "" "For static subtypes, :c:data:`PyBaseObject_Type` uses :c:func:`PyObject_Del`." msgstr "" -#: c-api/typeobj.rst:1954 +#: c-api/typeobj.rst:1967 msgid "An optional pointer to a function called by the garbage collector." msgstr "" -#: c-api/typeobj.rst:1956 +#: c-api/typeobj.rst:1969 msgid "" "The garbage collector needs to know whether a particular object is " "collectible or not. Normally, it is sufficient to look at the object's " @@ -2778,87 +3021,91 @@ msgid "" "instance. The signature is::" msgstr "" -#: c-api/typeobj.rst:1966 +#: c-api/typeobj.rst:1977 +msgid "int tp_is_gc(PyObject *self);" +msgstr "" + +#: c-api/typeobj.rst:1979 msgid "" "(The only example of this are types themselves. The metatype, :c:data:" "`PyType_Type`, defines this function to distinguish between statically and :" "ref:`dynamically allocated types `.)" msgstr "" -#: c-api/typeobj.rst:1976 +#: c-api/typeobj.rst:1989 msgid "" "This slot has no default. If this field is ``NULL``, :c:macro:" "`Py_TPFLAGS_HAVE_GC` is used as the functional equivalent." msgstr "" -#: c-api/typeobj.rst:1982 +#: c-api/typeobj.rst:1995 msgid "Tuple of base types." msgstr "" -#: c-api/typeobj.rst:2008 +#: c-api/typeobj.rst:2021 msgid "" "This field should be set to ``NULL`` and treated as read-only. Python will " "fill it in when the type is :c:func:`initialized `." msgstr "" -#: c-api/typeobj.rst:1987 +#: c-api/typeobj.rst:2000 msgid "" "For dynamically created classes, the ``Py_tp_bases`` :c:type:`slot " "` can be used instead of the *bases* argument of :c:func:" "`PyType_FromSpecWithBases`. The argument form is preferred." msgstr "" -#: c-api/typeobj.rst:1994 +#: c-api/typeobj.rst:2007 msgid "" "Multiple inheritance does not work well for statically defined types. If you " "set ``tp_bases`` to a tuple, Python will not raise an error, but some slots " "will only be inherited from the first base." msgstr "" -#: c-api/typeobj.rst:2023 c-api/typeobj.rst:2057 c-api/typeobj.rst:2071 +#: c-api/typeobj.rst:2036 c-api/typeobj.rst:2070 c-api/typeobj.rst:2084 msgid "This field is not inherited." msgstr "" -#: c-api/typeobj.rst:2005 +#: c-api/typeobj.rst:2018 msgid "" "Tuple containing the expanded set of base types, starting with the type " "itself and ending with :class:`object`, in Method Resolution Order." msgstr "" -#: c-api/typeobj.rst:2013 +#: c-api/typeobj.rst:2026 msgid "" "This field is not inherited; it is calculated fresh by :c:func:" "`PyType_Ready`." msgstr "" -#: c-api/typeobj.rst:2019 +#: c-api/typeobj.rst:2032 msgid "Unused. Internal use only." msgstr "" -#: c-api/typeobj.rst:2028 +#: c-api/typeobj.rst:2041 msgid "" "A collection of subclasses. Internal use only. May be an invalid pointer." msgstr "" -#: c-api/typeobj.rst:2030 +#: c-api/typeobj.rst:2043 msgid "" -"To get a list of subclasses, call the Python method :py:meth:`~class." +"To get a list of subclasses, call the Python method :py:meth:`~type." "__subclasses__`." msgstr "" -#: c-api/typeobj.rst:2035 +#: c-api/typeobj.rst:2048 msgid "" "For some types, this field does not hold a valid :c:expr:`PyObject*`. The " "type was changed to :c:expr:`void*` to indicate this." msgstr "" -#: c-api/typeobj.rst:2045 +#: c-api/typeobj.rst:2058 msgid "" "Weak reference list head, for weak references to this type object. Not " "inherited. Internal use only." msgstr "" -#: c-api/typeobj.rst:2050 +#: c-api/typeobj.rst:2063 msgid "" "Internals detail: For the static builtin types this is always ``NULL``, even " "if weakrefs are added. Instead, the weakrefs for each are stored on " @@ -2866,21 +3113,25 @@ msgid "" "``_PyObject_GET_WEAKREFS_LISTPTR()`` macro to avoid the distinction." msgstr "" -#: c-api/typeobj.rst:2062 +#: c-api/typeobj.rst:2075 msgid "" "This field is deprecated. Use :c:member:`~PyTypeObject.tp_finalize` instead." msgstr "" -#: c-api/typeobj.rst:2067 +#: c-api/typeobj.rst:2080 msgid "Used to index into the method cache. Internal use only." msgstr "" -#: c-api/typeobj.rst:2076 +#: c-api/typeobj.rst:2089 msgid "" "An optional pointer to an instance finalization function. Its signature is::" msgstr "" -#: c-api/typeobj.rst:2080 +#: c-api/typeobj.rst:2091 +msgid "void tp_finalize(PyObject *self);" +msgstr "" + +#: c-api/typeobj.rst:2093 msgid "" "If :c:member:`~PyTypeObject.tp_finalize` is set, the interpreter calls it " "once when finalizing an instance. It is called either from the garbage " @@ -2890,38 +3141,42 @@ msgid "" "object in a sane state." msgstr "" -#: c-api/typeobj.rst:2087 +#: c-api/typeobj.rst:2100 msgid "" ":c:member:`~PyTypeObject.tp_finalize` should not mutate the current " "exception status; therefore, a recommended way to write a non-trivial " "finalizer is::" msgstr "" -#: c-api/typeobj.rst:2104 +#: c-api/typeobj.rst:2103 msgid "" -"Also, note that, in a garbage collected Python, :c:member:`~PyTypeObject." -"tp_dealloc` may be called from any Python thread, not just the thread which " -"created the object (if the object becomes part of a refcount cycle, that " -"cycle might be collected by a garbage collection on any thread). This is " -"not a problem for Python API calls, since the thread on which tp_dealloc is " -"called will own the Global Interpreter Lock (GIL). However, if the object " -"being destroyed in turn destroys objects from some other C or C++ library, " -"care should be taken to ensure that destroying those objects on the thread " -"which called tp_dealloc will not violate any assumptions of the library." +"static void\n" +"local_finalize(PyObject *self)\n" +"{\n" +" PyObject *error_type, *error_value, *error_traceback;\n" +"\n" +" /* Save the current exception, if any. */\n" +" PyErr_Fetch(&error_type, &error_value, &error_traceback);\n" +"\n" +" /* ... */\n" +"\n" +" /* Restore the saved exception. */\n" +" PyErr_Restore(error_type, error_value, error_traceback);\n" +"}" msgstr "" -#: c-api/typeobj.rst:2123 +#: c-api/typeobj.rst:2125 msgid "" "Before version 3.8 it was necessary to set the :c:macro:" "`Py_TPFLAGS_HAVE_FINALIZE` flags bit in order for this field to be used. " "This is no longer required." msgstr "" -#: c-api/typeobj.rst:2127 +#: c-api/typeobj.rst:2129 msgid "\"Safe object finalization\" (:pep:`442`)" msgstr "" -#: c-api/typeobj.rst:2132 +#: c-api/typeobj.rst:2134 msgid "" "Vectorcall function to use for calls of this type object. In other words, it " "is used to implement :ref:`vectorcall ` for ``type.__call__``. " @@ -2929,65 +3184,65 @@ msgid "" "meth:`~object.__new__` and :meth:`~object.__init__` is used." msgstr "" -#: c-api/typeobj.rst:2140 +#: c-api/typeobj.rst:2142 msgid "This field is never inherited." msgstr "" -#: c-api/typeobj.rst:2142 +#: c-api/typeobj.rst:2144 msgid "(the field exists since 3.8 but it's only used since 3.9)" msgstr "" -#: c-api/typeobj.rst:2147 +#: c-api/typeobj.rst:2149 msgid "Internal. Do not use." msgstr "" -#: c-api/typeobj.rst:2155 +#: c-api/typeobj.rst:2157 msgid "Static Types" msgstr "" -#: c-api/typeobj.rst:2157 +#: c-api/typeobj.rst:2159 msgid "" "Traditionally, types defined in C code are *static*, that is, a static :c:" "type:`PyTypeObject` structure is defined directly in code and initialized " "using :c:func:`PyType_Ready`." msgstr "" -#: c-api/typeobj.rst:2161 +#: c-api/typeobj.rst:2163 msgid "" "This results in types that are limited relative to types defined in Python:" msgstr "" -#: c-api/typeobj.rst:2163 +#: c-api/typeobj.rst:2165 msgid "" "Static types are limited to one base, i.e. they cannot use multiple " "inheritance." msgstr "" -#: c-api/typeobj.rst:2165 +#: c-api/typeobj.rst:2167 msgid "" "Static type objects (but not necessarily their instances) are immutable. It " "is not possible to add or modify the type object's attributes from Python." msgstr "" -#: c-api/typeobj.rst:2167 +#: c-api/typeobj.rst:2169 msgid "" "Static type objects are shared across :ref:`sub-interpreters `, so they should not include any subinterpreter-" "specific state." msgstr "" -#: c-api/typeobj.rst:2171 +#: c-api/typeobj.rst:2173 msgid "" "Also, since :c:type:`PyTypeObject` is only part of the :ref:`Limited API " "` as an opaque struct, any extension modules using static " "types must be compiled for a specific Python minor version." msgstr "" -#: c-api/typeobj.rst:2179 +#: c-api/typeobj.rst:2181 msgid "Heap Types" msgstr "" -#: c-api/typeobj.rst:2181 +#: c-api/typeobj.rst:2183 msgid "" "An alternative to :ref:`static types ` is *heap-allocated " "types*, or *heap types* for short, which correspond closely to classes " @@ -2995,29 +3250,75 @@ msgid "" "`Py_TPFLAGS_HEAPTYPE` flag set." msgstr "" -#: c-api/typeobj.rst:2186 +#: c-api/typeobj.rst:2188 msgid "" "This is done by filling a :c:type:`PyType_Spec` structure and calling :c:" "func:`PyType_FromSpec`, :c:func:`PyType_FromSpecWithBases`, :c:func:" "`PyType_FromModuleAndSpec`, or :c:func:`PyType_FromMetaclass`." msgstr "" -#: c-api/typeobj.rst:2194 +#: c-api/typeobj.rst:2196 msgid "Number Object Structures" msgstr "" -#: c-api/typeobj.rst:2201 +#: c-api/typeobj.rst:2203 msgid "" "This structure holds pointers to the functions which an object uses to " "implement the number protocol. Each function is used by the function of " "similar name documented in the :ref:`number` section." msgstr "" -#: c-api/typeobj.rst:2531 +#: c-api/typeobj.rst:2533 msgid "Here is the structure definition::" msgstr "" -#: c-api/typeobj.rst:2254 +#: c-api/typeobj.rst:2211 +msgid "" +"typedef struct {\n" +" binaryfunc nb_add;\n" +" binaryfunc nb_subtract;\n" +" binaryfunc nb_multiply;\n" +" binaryfunc nb_remainder;\n" +" binaryfunc nb_divmod;\n" +" ternaryfunc nb_power;\n" +" unaryfunc nb_negative;\n" +" unaryfunc nb_positive;\n" +" unaryfunc nb_absolute;\n" +" inquiry nb_bool;\n" +" unaryfunc nb_invert;\n" +" binaryfunc nb_lshift;\n" +" binaryfunc nb_rshift;\n" +" binaryfunc nb_and;\n" +" binaryfunc nb_xor;\n" +" binaryfunc nb_or;\n" +" unaryfunc nb_int;\n" +" void *nb_reserved;\n" +" unaryfunc nb_float;\n" +"\n" +" binaryfunc nb_inplace_add;\n" +" binaryfunc nb_inplace_subtract;\n" +" binaryfunc nb_inplace_multiply;\n" +" binaryfunc nb_inplace_remainder;\n" +" ternaryfunc nb_inplace_power;\n" +" binaryfunc nb_inplace_lshift;\n" +" binaryfunc nb_inplace_rshift;\n" +" binaryfunc nb_inplace_and;\n" +" binaryfunc nb_inplace_xor;\n" +" binaryfunc nb_inplace_or;\n" +"\n" +" binaryfunc nb_floor_divide;\n" +" binaryfunc nb_true_divide;\n" +" binaryfunc nb_inplace_floor_divide;\n" +" binaryfunc nb_inplace_true_divide;\n" +"\n" +" unaryfunc nb_index;\n" +"\n" +" binaryfunc nb_matrix_multiply;\n" +" binaryfunc nb_inplace_matrix_multiply;\n" +"} PyNumberMethods;" +msgstr "" + +#: c-api/typeobj.rst:2256 msgid "" "Binary and ternary functions must check the type of all their operands, and " "implement the necessary conversions (at least one of the operands is an " @@ -3027,31 +3328,31 @@ msgid "" "and set an exception." msgstr "" -#: c-api/typeobj.rst:2263 +#: c-api/typeobj.rst:2265 msgid "" "The :c:member:`~PyNumberMethods.nb_reserved` field should always be " "``NULL``. It was previously called :c:member:`!nb_long`, and was renamed in " "Python 3.0.1." msgstr "" -#: c-api/typeobj.rst:2308 +#: c-api/typeobj.rst:2310 msgid "Mapping Object Structures" msgstr "" -#: c-api/typeobj.rst:2315 +#: c-api/typeobj.rst:2317 msgid "" "This structure holds pointers to the functions which an object uses to " "implement the mapping protocol. It has three members:" msgstr "" -#: c-api/typeobj.rst:2320 +#: c-api/typeobj.rst:2322 msgid "" "This function is used by :c:func:`PyMapping_Size` and :c:func:" "`PyObject_Size`, and has the same signature. This slot may be set to " "``NULL`` if the object has no defined length." msgstr "" -#: c-api/typeobj.rst:2326 +#: c-api/typeobj.rst:2328 msgid "" "This function is used by :c:func:`PyObject_GetItem` and :c:func:" "`PySequence_GetSlice`, and has the same signature as :c:func:`!" @@ -3059,7 +3360,7 @@ msgid "" "`PyMapping_Check` function to return ``1``, it can be ``NULL`` otherwise." msgstr "" -#: c-api/typeobj.rst:2334 +#: c-api/typeobj.rst:2336 msgid "" "This function is used by :c:func:`PyObject_SetItem`, :c:func:" "`PyObject_DelItem`, :c:func:`PySequence_SetSlice` and :c:func:" @@ -3069,17 +3370,17 @@ msgid "" "deletion." msgstr "" -#: c-api/typeobj.rst:2345 +#: c-api/typeobj.rst:2347 msgid "Sequence Object Structures" msgstr "" -#: c-api/typeobj.rst:2352 +#: c-api/typeobj.rst:2354 msgid "" "This structure holds pointers to the functions which an object uses to " "implement the sequence protocol." msgstr "" -#: c-api/typeobj.rst:2357 +#: c-api/typeobj.rst:2359 msgid "" "This function is used by :c:func:`PySequence_Size` and :c:func:" "`PyObject_Size`, and has the same signature. It is also used for handling " @@ -3087,21 +3388,21 @@ msgid "" "member:`~PySequenceMethods.sq_ass_item` slots." msgstr "" -#: c-api/typeobj.rst:2364 +#: c-api/typeobj.rst:2366 msgid "" "This function is used by :c:func:`PySequence_Concat` and has the same " "signature. It is also used by the ``+`` operator, after trying the numeric " "addition via the :c:member:`~PyNumberMethods.nb_add` slot." msgstr "" -#: c-api/typeobj.rst:2370 +#: c-api/typeobj.rst:2372 msgid "" "This function is used by :c:func:`PySequence_Repeat` and has the same " "signature. It is also used by the ``*`` operator, after trying numeric " "multiplication via the :c:member:`~PyNumberMethods.nb_multiply` slot." msgstr "" -#: c-api/typeobj.rst:2376 +#: c-api/typeobj.rst:2378 msgid "" "This function is used by :c:func:`PySequence_GetItem` and has the same " "signature. It is also used by :c:func:`PyObject_GetItem`, after trying the " @@ -3110,7 +3411,7 @@ msgid "" "``1``, it can be ``NULL`` otherwise." msgstr "" -#: c-api/typeobj.rst:2382 +#: c-api/typeobj.rst:2384 msgid "" "Negative indexes are handled as follows: if the :c:member:" "`~PySequenceMethods.sq_length` slot is filled, it is called and the sequence " @@ -3119,7 +3420,7 @@ msgid "" "index is passed as is to the function." msgstr "" -#: c-api/typeobj.rst:2389 +#: c-api/typeobj.rst:2391 msgid "" "This function is used by :c:func:`PySequence_SetItem` and has the same " "signature. It is also used by :c:func:`PyObject_SetItem` and :c:func:" @@ -3128,14 +3429,14 @@ msgid "" "``NULL`` if the object does not support item assignment and deletion." msgstr "" -#: c-api/typeobj.rst:2398 +#: c-api/typeobj.rst:2400 msgid "" "This function may be used by :c:func:`PySequence_Contains` and has the same " "signature. This slot may be left to ``NULL``, in this case :c:func:`!" "PySequence_Contains` simply traverses the sequence until it finds a match." msgstr "" -#: c-api/typeobj.rst:2405 +#: c-api/typeobj.rst:2407 msgid "" "This function is used by :c:func:`PySequence_InPlaceConcat` and has the same " "signature. It should modify its first operand, and return it. This slot " @@ -3145,7 +3446,7 @@ msgid "" "c:member:`~PyNumberMethods.nb_inplace_add` slot." msgstr "" -#: c-api/typeobj.rst:2414 +#: c-api/typeobj.rst:2416 msgid "" "This function is used by :c:func:`PySequence_InPlaceRepeat` and has the same " "signature. It should modify its first operand, and return it. This slot " @@ -3155,70 +3456,74 @@ msgid "" "via the :c:member:`~PyNumberMethods.nb_inplace_multiply` slot." msgstr "" -#: c-api/typeobj.rst:2425 +#: c-api/typeobj.rst:2427 msgid "Buffer Object Structures" msgstr "" -#: c-api/typeobj.rst:2433 +#: c-api/typeobj.rst:2435 msgid "" "This structure holds pointers to the functions required by the :ref:`Buffer " "protocol `. The protocol defines how an exporter object can " "expose its internal data to consumer objects." msgstr "" -#: c-api/typeobj.rst:2488 c-api/typeobj.rst:2553 c-api/typeobj.rst:2575 +#: c-api/typeobj.rst:2490 c-api/typeobj.rst:2555 c-api/typeobj.rst:2577 msgid "The signature of this function is::" msgstr "" #: c-api/typeobj.rst:2443 +msgid "int (PyObject *exporter, Py_buffer *view, int flags);" +msgstr "" + +#: c-api/typeobj.rst:2445 msgid "" "Handle a request to *exporter* to fill in *view* as specified by *flags*. " "Except for point (3), an implementation of this function MUST take these " "steps:" msgstr "" -#: c-api/typeobj.rst:2447 +#: c-api/typeobj.rst:2449 msgid "" "Check if the request can be met. If not, raise :exc:`BufferError`, set :c:" "expr:`view->obj` to ``NULL`` and return ``-1``." msgstr "" -#: c-api/typeobj.rst:2450 +#: c-api/typeobj.rst:2452 msgid "Fill in the requested fields." msgstr "" -#: c-api/typeobj.rst:2452 +#: c-api/typeobj.rst:2454 msgid "Increment an internal counter for the number of exports." msgstr "" -#: c-api/typeobj.rst:2454 +#: c-api/typeobj.rst:2456 msgid "" "Set :c:expr:`view->obj` to *exporter* and increment :c:expr:`view->obj`." msgstr "" -#: c-api/typeobj.rst:2456 +#: c-api/typeobj.rst:2458 msgid "Return ``0``." msgstr "" -#: c-api/typeobj.rst:2458 +#: c-api/typeobj.rst:2460 msgid "" "If *exporter* is part of a chain or tree of buffer providers, two main " "schemes can be used:" msgstr "" -#: c-api/typeobj.rst:2461 +#: c-api/typeobj.rst:2463 msgid "" "Re-export: Each member of the tree acts as the exporting object and sets :c:" "expr:`view->obj` to a new reference to itself." msgstr "" -#: c-api/typeobj.rst:2464 +#: c-api/typeobj.rst:2466 msgid "" "Redirect: The buffer request is redirected to the root object of the tree. " "Here, :c:expr:`view->obj` will be a new reference to the root object." msgstr "" -#: c-api/typeobj.rst:2468 +#: c-api/typeobj.rst:2470 msgid "" "The individual fields of *view* are described in section :ref:`Buffer " "structure `, the rules how an exporter must react to " @@ -3226,7 +3531,7 @@ msgid "" "types>`." msgstr "" -#: c-api/typeobj.rst:2473 +#: c-api/typeobj.rst:2475 msgid "" "All memory pointed to in the :c:type:`Py_buffer` structure belongs to the " "exporter and must remain valid until there are no consumers left. :c:member:" @@ -3235,19 +3540,23 @@ msgid "" "internal` are read-only for the consumer." msgstr "" -#: c-api/typeobj.rst:2480 +#: c-api/typeobj.rst:2482 msgid "" ":c:func:`PyBuffer_FillInfo` provides an easy way of exposing a simple bytes " "buffer while dealing correctly with all request types." msgstr "" -#: c-api/typeobj.rst:2483 +#: c-api/typeobj.rst:2485 msgid "" ":c:func:`PyObject_GetBuffer` is the interface for the consumer that wraps " "this function." msgstr "" #: c-api/typeobj.rst:2492 +msgid "void (PyObject *exporter, Py_buffer *view);" +msgstr "" + +#: c-api/typeobj.rst:2494 msgid "" "Handle a request to release the resources of the buffer. If no resources " "need to be released, :c:member:`PyBufferProcs.bf_releasebuffer` may be " @@ -3255,15 +3564,15 @@ msgid "" "these optional steps:" msgstr "" -#: c-api/typeobj.rst:2497 +#: c-api/typeobj.rst:2499 msgid "Decrement an internal counter for the number of exports." msgstr "" -#: c-api/typeobj.rst:2499 +#: c-api/typeobj.rst:2501 msgid "If the counter is ``0``, free all memory associated with *view*." msgstr "" -#: c-api/typeobj.rst:2501 +#: c-api/typeobj.rst:2503 msgid "" "The exporter MUST use the :c:member:`~Py_buffer.internal` field to keep " "track of buffer-specific resources. This field is guaranteed to remain " @@ -3271,68 +3580,94 @@ msgid "" "*view* argument." msgstr "" -#: c-api/typeobj.rst:2507 +#: c-api/typeobj.rst:2509 msgid "" "This function MUST NOT decrement :c:expr:`view->obj`, since that is done " "automatically in :c:func:`PyBuffer_Release` (this scheme is useful for " "breaking reference cycles)." msgstr "" -#: c-api/typeobj.rst:2512 +#: c-api/typeobj.rst:2514 msgid "" ":c:func:`PyBuffer_Release` is the interface for the consumer that wraps this " "function." msgstr "" -#: c-api/typeobj.rst:2520 +#: c-api/typeobj.rst:2522 msgid "Async Object Structures" msgstr "" -#: c-api/typeobj.rst:2528 +#: c-api/typeobj.rst:2530 msgid "" "This structure holds pointers to the functions required to implement :term:" "`awaitable` and :term:`asynchronous iterator` objects." msgstr "" +#: c-api/typeobj.rst:2535 +msgid "" +"typedef struct {\n" +" unaryfunc am_await;\n" +" unaryfunc am_aiter;\n" +" unaryfunc am_anext;\n" +" sendfunc am_send;\n" +"} PyAsyncMethods;" +msgstr "" + #: c-api/typeobj.rst:2546 +msgid "PyObject *am_await(PyObject *self);" +msgstr "" + +#: c-api/typeobj.rst:2548 msgid "" "The returned object must be an :term:`iterator`, i.e. :c:func:`PyIter_Check` " "must return ``1`` for it." msgstr "" -#: c-api/typeobj.rst:2549 +#: c-api/typeobj.rst:2551 msgid "" "This slot may be set to ``NULL`` if an object is not an :term:`awaitable`." msgstr "" #: c-api/typeobj.rst:2557 +msgid "PyObject *am_aiter(PyObject *self);" +msgstr "" + +#: c-api/typeobj.rst:2559 msgid "" "Must return an :term:`asynchronous iterator` object. See :meth:`~object." "__anext__` for details." msgstr "" -#: c-api/typeobj.rst:2560 +#: c-api/typeobj.rst:2562 msgid "" "This slot may be set to ``NULL`` if an object does not implement " "asynchronous iteration protocol." msgstr "" #: c-api/typeobj.rst:2569 +msgid "PyObject *am_anext(PyObject *self);" +msgstr "" + +#: c-api/typeobj.rst:2571 msgid "" "Must return an :term:`awaitable` object. See :meth:`~object.__anext__` for " "details. This slot may be set to ``NULL``." msgstr "" #: c-api/typeobj.rst:2579 +msgid "PySendResult am_send(PyObject *self, PyObject *arg, PyObject **result);" +msgstr "" + +#: c-api/typeobj.rst:2581 msgid "" "See :c:func:`PyIter_Send` for details. This slot may be set to ``NULL``." msgstr "" -#: c-api/typeobj.rst:2588 +#: c-api/typeobj.rst:2590 msgid "Slot Type typedefs" msgstr "" -#: c-api/typeobj.rst:2592 +#: c-api/typeobj.rst:2594 msgid "" "The purpose of this function is to separate memory allocation from memory " "initialization. It should return a pointer to a block of memory of adequate " @@ -3346,80 +3681,80 @@ msgid "" "length of the block should be :c:member:`~PyTypeObject.tp_basicsize`." msgstr "" -#: c-api/typeobj.rst:2602 +#: c-api/typeobj.rst:2604 msgid "" "This function should not do any other instance initialization, not even to " "allocate additional memory; that should be done by :c:member:`~PyTypeObject." "tp_new`." msgstr "" -#: c-api/typeobj.rst:2609 +#: c-api/typeobj.rst:2611 msgid "See :c:member:`~PyTypeObject.tp_free`." msgstr "" -#: c-api/typeobj.rst:2613 +#: c-api/typeobj.rst:2615 msgid "See :c:member:`~PyTypeObject.tp_new`." msgstr "" -#: c-api/typeobj.rst:2617 +#: c-api/typeobj.rst:2619 msgid "See :c:member:`~PyTypeObject.tp_init`." msgstr "" -#: c-api/typeobj.rst:2621 +#: c-api/typeobj.rst:2623 msgid "See :c:member:`~PyTypeObject.tp_repr`." msgstr "" -#: c-api/typeobj.rst:2634 +#: c-api/typeobj.rst:2636 msgid "Return the value of the named attribute for the object." msgstr "" -#: c-api/typeobj.rst:2640 +#: c-api/typeobj.rst:2642 msgid "" "Set the value of the named attribute for the object. The value argument is " "set to ``NULL`` to delete the attribute." msgstr "" -#: c-api/typeobj.rst:2636 +#: c-api/typeobj.rst:2638 msgid "See :c:member:`~PyTypeObject.tp_getattro`." msgstr "" -#: c-api/typeobj.rst:2643 +#: c-api/typeobj.rst:2645 msgid "See :c:member:`~PyTypeObject.tp_setattro`." msgstr "" -#: c-api/typeobj.rst:2647 +#: c-api/typeobj.rst:2649 msgid "See :c:member:`~PyTypeObject.tp_descr_get`." msgstr "" -#: c-api/typeobj.rst:2651 +#: c-api/typeobj.rst:2653 msgid "See :c:member:`~PyTypeObject.tp_descr_set`." msgstr "" -#: c-api/typeobj.rst:2655 +#: c-api/typeobj.rst:2657 msgid "See :c:member:`~PyTypeObject.tp_hash`." msgstr "" -#: c-api/typeobj.rst:2659 +#: c-api/typeobj.rst:2661 msgid "See :c:member:`~PyTypeObject.tp_richcompare`." msgstr "" -#: c-api/typeobj.rst:2663 +#: c-api/typeobj.rst:2665 msgid "See :c:member:`~PyTypeObject.tp_iter`." msgstr "" -#: c-api/typeobj.rst:2667 +#: c-api/typeobj.rst:2669 msgid "See :c:member:`~PyTypeObject.tp_iternext`." msgstr "" -#: c-api/typeobj.rst:2681 +#: c-api/typeobj.rst:2683 msgid "See :c:member:`~PyAsyncMethods.am_send`." msgstr "" -#: c-api/typeobj.rst:2697 +#: c-api/typeobj.rst:2699 msgid "Examples" msgstr "" -#: c-api/typeobj.rst:2699 +#: c-api/typeobj.rst:2701 msgid "" "The following are simple examples of Python type definitions. They include " "common usage you may encounter. Some demonstrate tricky corner cases. For " @@ -3427,46 +3762,179 @@ msgid "" "and :ref:`new-types-topics`." msgstr "" -#: c-api/typeobj.rst:2704 +#: c-api/typeobj.rst:2706 msgid "A basic :ref:`static type `::" msgstr "" -#: c-api/typeobj.rst:2721 +#: c-api/typeobj.rst:2708 +msgid "" +"typedef struct {\n" +" PyObject_HEAD\n" +" const char *data;\n" +"} MyObject;\n" +"\n" +"static PyTypeObject MyObject_Type = {\n" +" PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"mymod.MyObject\",\n" +" .tp_basicsize = sizeof(MyObject),\n" +" .tp_doc = PyDoc_STR(\"My objects\"),\n" +" .tp_new = myobj_new,\n" +" .tp_dealloc = (destructor)myobj_dealloc,\n" +" .tp_repr = (reprfunc)myobj_repr,\n" +"};" +msgstr "" + +#: c-api/typeobj.rst:2723 msgid "" "You may also find older code (especially in the CPython code base) with a " "more verbose initializer::" msgstr "" -#: c-api/typeobj.rst:2765 +#: c-api/typeobj.rst:2726 +msgid "" +"static PyTypeObject MyObject_Type = {\n" +" PyVarObject_HEAD_INIT(NULL, 0)\n" +" \"mymod.MyObject\", /* tp_name */\n" +" sizeof(MyObject), /* tp_basicsize */\n" +" 0, /* tp_itemsize */\n" +" (destructor)myobj_dealloc, /* tp_dealloc */\n" +" 0, /* tp_vectorcall_offset */\n" +" 0, /* tp_getattr */\n" +" 0, /* tp_setattr */\n" +" 0, /* tp_as_async */\n" +" (reprfunc)myobj_repr, /* tp_repr */\n" +" 0, /* tp_as_number */\n" +" 0, /* tp_as_sequence */\n" +" 0, /* tp_as_mapping */\n" +" 0, /* tp_hash */\n" +" 0, /* tp_call */\n" +" 0, /* tp_str */\n" +" 0, /* tp_getattro */\n" +" 0, /* tp_setattro */\n" +" 0, /* tp_as_buffer */\n" +" 0, /* tp_flags */\n" +" PyDoc_STR(\"My objects\"), /* tp_doc */\n" +" 0, /* tp_traverse */\n" +" 0, /* tp_clear */\n" +" 0, /* tp_richcompare */\n" +" 0, /* tp_weaklistoffset */\n" +" 0, /* tp_iter */\n" +" 0, /* tp_iternext */\n" +" 0, /* tp_methods */\n" +" 0, /* tp_members */\n" +" 0, /* tp_getset */\n" +" 0, /* tp_base */\n" +" 0, /* tp_dict */\n" +" 0, /* tp_descr_get */\n" +" 0, /* tp_descr_set */\n" +" 0, /* tp_dictoffset */\n" +" 0, /* tp_init */\n" +" 0, /* tp_alloc */\n" +" myobj_new, /* tp_new */\n" +"};" +msgstr "" + +#: c-api/typeobj.rst:2767 msgid "A type that supports weakrefs, instance dicts, and hashing::" msgstr "" -#: c-api/typeobj.rst:2790 +#: c-api/typeobj.rst:2769 +msgid "" +"typedef struct {\n" +" PyObject_HEAD\n" +" const char *data;\n" +"} MyObject;\n" +"\n" +"static PyTypeObject MyObject_Type = {\n" +" PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"mymod.MyObject\",\n" +" .tp_basicsize = sizeof(MyObject),\n" +" .tp_doc = PyDoc_STR(\"My objects\"),\n" +" .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |\n" +" Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_MANAGED_DICT |\n" +" Py_TPFLAGS_MANAGED_WEAKREF,\n" +" .tp_new = myobj_new,\n" +" .tp_traverse = (traverseproc)myobj_traverse,\n" +" .tp_clear = (inquiry)myobj_clear,\n" +" .tp_alloc = PyType_GenericNew,\n" +" .tp_dealloc = (destructor)myobj_dealloc,\n" +" .tp_repr = (reprfunc)myobj_repr,\n" +" .tp_hash = (hashfunc)myobj_hash,\n" +" .tp_richcompare = PyBaseObject_Type.tp_richcompare,\n" +"};" +msgstr "" + +#: c-api/typeobj.rst:2792 msgid "" "A str subclass that cannot be subclassed and cannot be called to create " "instances (e.g. uses a separate factory func) using :c:macro:" "`Py_TPFLAGS_DISALLOW_INSTANTIATION` flag::" msgstr "" -#: c-api/typeobj.rst:2809 +#: c-api/typeobj.rst:2796 +msgid "" +"typedef struct {\n" +" PyUnicodeObject raw;\n" +" char *extra;\n" +"} MyStr;\n" +"\n" +"static PyTypeObject MyStr_Type = {\n" +" PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"mymod.MyStr\",\n" +" .tp_basicsize = sizeof(MyStr),\n" +" .tp_base = NULL, // set to &PyUnicode_Type in module init\n" +" .tp_doc = PyDoc_STR(\"my custom str\"),\n" +" .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,\n" +" .tp_repr = (reprfunc)myobj_repr,\n" +"};" +msgstr "" + +#: c-api/typeobj.rst:2811 msgid "" "The simplest :ref:`static type ` with fixed-length instances::" msgstr "" -#: c-api/typeobj.rst:2820 +#: c-api/typeobj.rst:2813 +msgid "" +"typedef struct {\n" +" PyObject_HEAD\n" +"} MyObject;\n" +"\n" +"static PyTypeObject MyObject_Type = {\n" +" PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"mymod.MyObject\",\n" +"};" +msgstr "" + +#: c-api/typeobj.rst:2822 msgid "" "The simplest :ref:`static type ` with variable-length " "instances::" msgstr "" -#: c-api/typeobj.rst:874 +#: c-api/typeobj.rst:2824 +msgid "" +"typedef struct {\n" +" PyObject_VAR_HEAD\n" +" const char *data[1];\n" +"} MyObject;\n" +"\n" +"static PyTypeObject MyObject_Type = {\n" +" PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"mymod.MyObject\",\n" +" .tp_basicsize = sizeof(MyObject) - sizeof(char *),\n" +" .tp_itemsize = sizeof(char *),\n" +"};" +msgstr "" + +#: c-api/typeobj.rst:887 msgid "built-in function" msgstr "" -#: c-api/typeobj.rst:809 +#: c-api/typeobj.rst:822 msgid "repr" msgstr "" -#: c-api/typeobj.rst:874 +#: c-api/typeobj.rst:887 msgid "hash" msgstr "" diff --git a/c-api/unicode.po b/c-api/unicode.po index 4a2d570df..3b5a166f0 100644 --- a/c-api/unicode.po +++ b/c-api/unicode.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-02-24 17:22+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -346,7 +346,11 @@ msgid "" "created using this function are not resizable." msgstr "" -#: c-api/unicode.rst:354 +#: c-api/unicode.rst:348 +msgid "On error, set an exception and return ``NULL``." +msgstr "" + +#: c-api/unicode.rst:356 msgid "" "Create a new Unicode object with the given *kind* (possible values are :c:" "macro:`PyUnicode_1BYTE_KIND` etc., as returned by :c:func:" @@ -354,7 +358,7 @@ msgid "" "1, 2 or 4 bytes per character, as given by the kind." msgstr "" -#: c-api/unicode.rst:359 +#: c-api/unicode.rst:361 msgid "" "If necessary, the input *buffer* is copied and transformed into the " "canonical representation. For example, if the *buffer* is a UCS4 string (:c:" @@ -362,7 +366,7 @@ msgid "" "range, it will be transformed into UCS1 (:c:macro:`PyUnicode_1BYTE_KIND`)." msgstr "" -#: c-api/unicode.rst:370 +#: c-api/unicode.rst:372 msgid "" "Create a Unicode object from the char buffer *str*. The bytes will be " "interpreted as being UTF-8 encoded. The buffer is copied into the new " @@ -370,29 +374,29 @@ msgid "" "data is not allowed." msgstr "" -#: c-api/unicode.rst:376 +#: c-api/unicode.rst:378 msgid "This function raises :exc:`SystemError` when:" msgstr "" -#: c-api/unicode.rst:378 +#: c-api/unicode.rst:380 msgid "*size* < 0," msgstr "" -#: c-api/unicode.rst:379 +#: c-api/unicode.rst:381 msgid "*str* is ``NULL`` and *size* > 0" msgstr "" -#: c-api/unicode.rst:381 +#: c-api/unicode.rst:383 msgid "*str* == ``NULL`` with *size* > 0 is not allowed anymore." msgstr "" -#: c-api/unicode.rst:387 +#: c-api/unicode.rst:389 msgid "" "Create a Unicode object from a UTF-8 encoded null-terminated char buffer " "*str*." msgstr "" -#: c-api/unicode.rst:393 +#: c-api/unicode.rst:395 msgid "" "Take a C :c:func:`printf`\\ -style *format* string and a variable number of " "arguments, calculate the size of the resulting Python Unicode string and " @@ -401,23 +405,23 @@ msgid "" "*format* ASCII-encoded string." msgstr "" -#: c-api/unicode.rst:399 +#: c-api/unicode.rst:401 msgid "" "A conversion specifier contains two or more characters and has the following " "components, which must occur in this order:" msgstr "" -#: c-api/unicode.rst:402 +#: c-api/unicode.rst:404 msgid "The ``'%'`` character, which marks the start of the specifier." msgstr "" -#: c-api/unicode.rst:404 +#: c-api/unicode.rst:406 msgid "" "Conversion flags (optional), which affect the result of some conversion " "types." msgstr "" -#: c-api/unicode.rst:407 +#: c-api/unicode.rst:409 msgid "" "Minimum field width (optional). If specified as an ``'*'`` (asterisk), the " "actual width is given in the next argument, which must be of type :c:expr:" @@ -425,7 +429,7 @@ msgid "" "optional precision." msgstr "" -#: c-api/unicode.rst:412 +#: c-api/unicode.rst:414 msgid "" "Precision (optional), given as a ``'.'`` (dot) followed by the precision. If " "specified as ``'*'`` (an asterisk), the actual precision is given in the " @@ -433,268 +437,268 @@ msgid "" "comes after the precision." msgstr "" -#: c-api/unicode.rst:417 +#: c-api/unicode.rst:419 msgid "Length modifier (optional)." msgstr "" -#: c-api/unicode.rst:419 +#: c-api/unicode.rst:421 msgid "Conversion type." msgstr "" -#: c-api/unicode.rst:421 +#: c-api/unicode.rst:423 msgid "The conversion flag characters are:" msgstr "" -#: c-api/unicode.rst:426 +#: c-api/unicode.rst:428 msgid "Flag" msgstr "" -#: c-api/unicode.rst:426 +#: c-api/unicode.rst:428 msgid "Meaning" msgstr "" -#: c-api/unicode.rst:428 +#: c-api/unicode.rst:430 msgid "``0``" msgstr "" -#: c-api/unicode.rst:428 +#: c-api/unicode.rst:430 msgid "The conversion will be zero padded for numeric values." msgstr "" -#: c-api/unicode.rst:430 +#: c-api/unicode.rst:432 msgid "``-``" msgstr "" -#: c-api/unicode.rst:430 +#: c-api/unicode.rst:432 msgid "" "The converted value is left adjusted (overrides the ``0`` flag if both are " "given)." msgstr "" -#: c-api/unicode.rst:434 +#: c-api/unicode.rst:436 msgid "" "The length modifiers for following integer conversions (``d``, ``i``, ``o``, " "``u``, ``x``, or ``X``) specify the type of the argument (:c:expr:`int` by " "default):" msgstr "" -#: c-api/unicode.rst:441 +#: c-api/unicode.rst:443 msgid "Modifier" msgstr "" -#: c-api/unicode.rst:441 +#: c-api/unicode.rst:443 msgid "Types" msgstr "" -#: c-api/unicode.rst:443 +#: c-api/unicode.rst:445 msgid "``l``" msgstr "" -#: c-api/unicode.rst:443 +#: c-api/unicode.rst:445 msgid ":c:expr:`long` or :c:expr:`unsigned long`" msgstr "" -#: c-api/unicode.rst:445 +#: c-api/unicode.rst:447 msgid "``ll``" msgstr "" -#: c-api/unicode.rst:445 +#: c-api/unicode.rst:447 msgid ":c:expr:`long long` or :c:expr:`unsigned long long`" msgstr "" -#: c-api/unicode.rst:447 +#: c-api/unicode.rst:449 msgid "``j``" msgstr "" -#: c-api/unicode.rst:447 +#: c-api/unicode.rst:449 msgid ":c:type:`intmax_t` or :c:type:`uintmax_t`" msgstr "" -#: c-api/unicode.rst:449 +#: c-api/unicode.rst:451 msgid "``z``" msgstr "" -#: c-api/unicode.rst:449 +#: c-api/unicode.rst:451 msgid ":c:type:`size_t` or :c:type:`ssize_t`" msgstr "" -#: c-api/unicode.rst:451 +#: c-api/unicode.rst:453 msgid "``t``" msgstr "" -#: c-api/unicode.rst:451 +#: c-api/unicode.rst:453 msgid ":c:type:`ptrdiff_t`" msgstr "" -#: c-api/unicode.rst:454 +#: c-api/unicode.rst:456 msgid "" "The length modifier ``l`` for following conversions ``s`` or ``V`` specify " "that the type of the argument is :c:expr:`const wchar_t*`." msgstr "" -#: c-api/unicode.rst:457 +#: c-api/unicode.rst:459 msgid "The conversion specifiers are:" msgstr "" -#: c-api/unicode.rst:463 +#: c-api/unicode.rst:465 msgid "Conversion Specifier" msgstr "" -#: c-api/unicode.rst:464 +#: c-api/unicode.rst:466 msgid "Type" msgstr "" -#: c-api/unicode.rst:465 +#: c-api/unicode.rst:467 msgid "Comment" msgstr "" -#: c-api/unicode.rst:467 +#: c-api/unicode.rst:469 msgid "``%``" msgstr "" -#: c-api/unicode.rst:468 +#: c-api/unicode.rst:470 msgid "*n/a*" msgstr "" -#: c-api/unicode.rst:469 +#: c-api/unicode.rst:471 msgid "The literal ``%`` character." msgstr "" -#: c-api/unicode.rst:471 +#: c-api/unicode.rst:473 msgid "``d``, ``i``" msgstr "" -#: c-api/unicode.rst:476 c-api/unicode.rst:484 c-api/unicode.rst:488 +#: c-api/unicode.rst:478 c-api/unicode.rst:486 c-api/unicode.rst:490 msgid "Specified by the length modifier" msgstr "" -#: c-api/unicode.rst:473 +#: c-api/unicode.rst:475 msgid "The decimal representation of a signed C integer." msgstr "" -#: c-api/unicode.rst:475 +#: c-api/unicode.rst:477 msgid "``u``" msgstr "" -#: c-api/unicode.rst:477 +#: c-api/unicode.rst:479 msgid "The decimal representation of an unsigned C integer." msgstr "" -#: c-api/unicode.rst:479 +#: c-api/unicode.rst:481 msgid "``o``" msgstr "" -#: c-api/unicode.rst:481 +#: c-api/unicode.rst:483 msgid "The octal representation of an unsigned C integer." msgstr "" -#: c-api/unicode.rst:483 +#: c-api/unicode.rst:485 msgid "``x``" msgstr "" -#: c-api/unicode.rst:485 +#: c-api/unicode.rst:487 msgid "The hexadecimal representation of an unsigned C integer (lowercase)." msgstr "" -#: c-api/unicode.rst:487 +#: c-api/unicode.rst:489 msgid "``X``" msgstr "" -#: c-api/unicode.rst:489 +#: c-api/unicode.rst:491 msgid "The hexadecimal representation of an unsigned C integer (uppercase)." msgstr "" -#: c-api/unicode.rst:491 +#: c-api/unicode.rst:493 msgid "``c``" msgstr "" -#: c-api/unicode.rst:492 +#: c-api/unicode.rst:494 msgid ":c:expr:`int`" msgstr "" -#: c-api/unicode.rst:493 +#: c-api/unicode.rst:495 msgid "A single character." msgstr "" -#: c-api/unicode.rst:495 +#: c-api/unicode.rst:497 msgid "``s``" msgstr "" -#: c-api/unicode.rst:496 +#: c-api/unicode.rst:498 msgid ":c:expr:`const char*` or :c:expr:`const wchar_t*`" msgstr "" -#: c-api/unicode.rst:497 +#: c-api/unicode.rst:499 msgid "A null-terminated C character array." msgstr "" -#: c-api/unicode.rst:499 +#: c-api/unicode.rst:501 msgid "``p``" msgstr "" -#: c-api/unicode.rst:500 +#: c-api/unicode.rst:502 msgid ":c:expr:`const void*`" msgstr "" -#: c-api/unicode.rst:501 +#: c-api/unicode.rst:503 msgid "" "The hex representation of a C pointer. Mostly equivalent to " "``printf(\"%p\")`` except that it is guaranteed to start with the literal " "``0x`` regardless of what the platform's ``printf`` yields." msgstr "" -#: c-api/unicode.rst:506 +#: c-api/unicode.rst:508 msgid "``A``" msgstr "" -#: c-api/unicode.rst:511 c-api/unicode.rst:525 +#: c-api/unicode.rst:513 c-api/unicode.rst:527 msgid ":c:expr:`PyObject*`" msgstr "" -#: c-api/unicode.rst:508 +#: c-api/unicode.rst:510 msgid "The result of calling :func:`ascii`." msgstr "" -#: c-api/unicode.rst:510 +#: c-api/unicode.rst:512 msgid "``U``" msgstr "" -#: c-api/unicode.rst:512 +#: c-api/unicode.rst:514 msgid "A Unicode object." msgstr "" -#: c-api/unicode.rst:514 +#: c-api/unicode.rst:516 msgid "``V``" msgstr "" -#: c-api/unicode.rst:515 +#: c-api/unicode.rst:517 msgid ":c:expr:`PyObject*`, :c:expr:`const char*` or :c:expr:`const wchar_t*`" msgstr "" -#: c-api/unicode.rst:516 +#: c-api/unicode.rst:518 msgid "" "A Unicode object (which may be ``NULL``) and a null-terminated C character " "array as a second parameter (which will be used, if the first parameter is " "``NULL``)." msgstr "" -#: c-api/unicode.rst:520 +#: c-api/unicode.rst:522 msgid "``S``" msgstr "" -#: c-api/unicode.rst:522 +#: c-api/unicode.rst:524 msgid "The result of calling :c:func:`PyObject_Str`." msgstr "" -#: c-api/unicode.rst:524 +#: c-api/unicode.rst:526 msgid "``R``" msgstr "" -#: c-api/unicode.rst:526 +#: c-api/unicode.rst:528 msgid "The result of calling :c:func:`PyObject_Repr`." msgstr "" -#: c-api/unicode.rst:529 +#: c-api/unicode.rst:531 msgid "" "The width formatter unit is number of characters rather than bytes. The " "precision formatter unit is number of bytes or :c:type:`wchar_t` items (if " @@ -704,28 +708,28 @@ msgid "" "``PyObject*`` argument is not ``NULL``)." msgstr "" -#: c-api/unicode.rst:537 +#: c-api/unicode.rst:539 msgid "" "Unlike to C :c:func:`printf` the ``0`` flag has effect even when a precision " "is given for integer conversions (``d``, ``i``, ``u``, ``o``, ``x``, or " "``X``)." msgstr "" -#: c-api/unicode.rst:541 +#: c-api/unicode.rst:543 msgid "Support for ``\"%lld\"`` and ``\"%llu\"`` added." msgstr "" -#: c-api/unicode.rst:544 +#: c-api/unicode.rst:546 msgid "Support for ``\"%li\"``, ``\"%lli\"`` and ``\"%zi\"`` added." msgstr "" -#: c-api/unicode.rst:547 +#: c-api/unicode.rst:549 msgid "" "Support width and precision formatter for ``\"%s\"``, ``\"%A\"``, " "``\"%U\"``, ``\"%V\"``, ``\"%S\"``, ``\"%R\"`` added." msgstr "" -#: c-api/unicode.rst:551 +#: c-api/unicode.rst:553 msgid "" "Support for conversion specifiers ``o`` and ``X``. Support for length " "modifiers ``j`` and ``t``. Length modifiers are now applied to all integer " @@ -734,36 +738,36 @@ msgid "" "flag ``-``." msgstr "" -#: c-api/unicode.rst:559 +#: c-api/unicode.rst:561 msgid "" "An unrecognized format character now sets a :exc:`SystemError`. In previous " "versions it caused all the rest of the format string to be copied as-is to " "the result string, and any extra arguments discarded." msgstr "" -#: c-api/unicode.rst:566 +#: c-api/unicode.rst:568 msgid "" "Identical to :c:func:`PyUnicode_FromFormat` except that it takes exactly two " "arguments." msgstr "" -#: c-api/unicode.rst:572 +#: c-api/unicode.rst:574 msgid "" "Copy an instance of a Unicode subtype to a new true Unicode object if " "necessary. If *obj* is already a true Unicode object (not a subtype), return " "a new :term:`strong reference` to the object." msgstr "" -#: c-api/unicode.rst:576 +#: c-api/unicode.rst:578 msgid "" "Objects other than Unicode or its subtypes will cause a :exc:`TypeError`." msgstr "" -#: c-api/unicode.rst:582 +#: c-api/unicode.rst:584 msgid "Decode an encoded object *obj* to a Unicode object." msgstr "" -#: c-api/unicode.rst:584 +#: c-api/unicode.rst:586 msgid "" ":class:`bytes`, :class:`bytearray` and other :term:`bytes-like objects " "` are decoded according to the given *encoding* and using " @@ -771,23 +775,27 @@ msgid "" "interface use the default values (see :ref:`builtincodecs` for details)." msgstr "" -#: c-api/unicode.rst:590 +#: c-api/unicode.rst:592 msgid "" "All other objects, including Unicode objects, cause a :exc:`TypeError` to be " "set." msgstr "" -#: c-api/unicode.rst:593 +#: c-api/unicode.rst:595 msgid "" "The API returns ``NULL`` if there was an error. The caller is responsible " "for decref'ing the returned objects." msgstr "" -#: c-api/unicode.rst:599 +#: c-api/unicode.rst:601 msgid "Return the length of the Unicode object, in code points." msgstr "" -#: c-api/unicode.rst:610 +#: c-api/unicode.rst:603 +msgid "On error, set an exception and return ``-1``." +msgstr "" + +#: c-api/unicode.rst:614 msgid "" "Copy characters from one Unicode object into another. This function " "performs character conversion when necessary and falls back to :c:func:`!" @@ -795,39 +803,43 @@ msgid "" "otherwise returns the number of copied characters." msgstr "" -#: c-api/unicode.rst:621 +#: c-api/unicode.rst:625 msgid "" "Fill a string with a character: write *fill_char* into ``unicode[start:" "start+length]``." msgstr "" -#: c-api/unicode.rst:624 +#: c-api/unicode.rst:628 msgid "" "Fail if *fill_char* is bigger than the string maximum character, or if the " "string has more than 1 reference." msgstr "" -#: c-api/unicode.rst:627 +#: c-api/unicode.rst:631 msgid "" "Return the number of written character, or return ``-1`` and raise an " "exception on error." msgstr "" -#: c-api/unicode.rst:636 +#: c-api/unicode.rst:640 msgid "" "Write a character to a string. The string must have been created through :c:" "func:`PyUnicode_New`. Since Unicode strings are supposed to be immutable, " "the string must not be shared, or have been hashed yet." msgstr "" -#: c-api/unicode.rst:640 +#: c-api/unicode.rst:644 msgid "" "This function checks that *unicode* is a Unicode object, that the index is " "not out of bounds, and that the object can be modified safely (i.e. that it " "its reference count is one)." msgstr "" -#: c-api/unicode.rst:649 +#: c-api/unicode.rst:648 +msgid "Return ``0`` on success, ``-1`` on error with an exception set." +msgstr "" + +#: c-api/unicode.rst:655 msgid "" "Read a character from a string. This function checks that *unicode* is a " "Unicode object and the index is not out of bounds, in contrast to :c:func:" @@ -835,12 +847,17 @@ msgid "" msgstr "" #: c-api/unicode.rst:659 +msgid "Return character on success, ``-1`` on error with an exception set." +msgstr "" + +#: c-api/unicode.rst:667 msgid "" "Return a substring of *unicode*, from character index *start* (included) to " -"character index *end* (excluded). Negative indices are not supported." +"character index *end* (excluded). Negative indices are not supported. On " +"error, set an exception and return ``NULL``." msgstr "" -#: c-api/unicode.rst:668 +#: c-api/unicode.rst:677 msgid "" "Copy the string *unicode* into a UCS4 buffer, including a null character, if " "*copy_null* is set. Returns ``NULL`` and sets an exception on error (in " @@ -848,7 +865,7 @@ msgid "" "*unicode*). *buffer* is returned on success." msgstr "" -#: c-api/unicode.rst:678 +#: c-api/unicode.rst:687 msgid "" "Copy the string *unicode* into a new UCS4 buffer that is allocated using :c:" "func:`PyMem_Malloc`. If this fails, ``NULL`` is returned with a :exc:" @@ -856,17 +873,17 @@ msgid "" "appended." msgstr "" -#: c-api/unicode.rst:687 +#: c-api/unicode.rst:696 msgid "Locale Encoding" msgstr "" -#: c-api/unicode.rst:689 +#: c-api/unicode.rst:698 msgid "" "The current locale encoding can be used to decode text from the operating " "system." msgstr "" -#: c-api/unicode.rst:696 +#: c-api/unicode.rst:705 msgid "" "Decode a string from UTF-8 on Android and VxWorks, or from the current " "locale encoding on other platforms. The supported error handlers are " @@ -875,21 +892,21 @@ msgid "" "null character but cannot contain embedded null characters." msgstr "" -#: c-api/unicode.rst:703 +#: c-api/unicode.rst:712 msgid "" "Use :c:func:`PyUnicode_DecodeFSDefaultAndSize` to decode a string from the :" "term:`filesystem encoding and error handler`." msgstr "" -#: c-api/unicode.rst:741 +#: c-api/unicode.rst:750 msgid "This function ignores the :ref:`Python UTF-8 Mode `." msgstr "" -#: c-api/unicode.rst:807 +#: c-api/unicode.rst:816 msgid "The :c:func:`Py_DecodeLocale` function." msgstr "" -#: c-api/unicode.rst:714 +#: c-api/unicode.rst:723 msgid "" "The function now also uses the current locale encoding for the " "``surrogateescape`` error handler, except on Android. Previously, :c:func:" @@ -897,13 +914,13 @@ msgid "" "locale encoding was used for ``strict``." msgstr "" -#: c-api/unicode.rst:723 +#: c-api/unicode.rst:732 msgid "" "Similar to :c:func:`PyUnicode_DecodeLocaleAndSize`, but compute the string " "length using :c:func:`!strlen`." msgstr "" -#: c-api/unicode.rst:731 +#: c-api/unicode.rst:740 msgid "" "Encode a Unicode object to UTF-8 on Android and VxWorks, or to the current " "locale encoding on other platforms. The supported error handlers are " @@ -912,17 +929,17 @@ msgid "" "`bytes` object. *unicode* cannot contain embedded null characters." msgstr "" -#: c-api/unicode.rst:738 +#: c-api/unicode.rst:747 msgid "" "Use :c:func:`PyUnicode_EncodeFSDefault` to encode a string to the :term:" "`filesystem encoding and error handler`." msgstr "" -#: c-api/unicode.rst:838 +#: c-api/unicode.rst:847 msgid "The :c:func:`Py_EncodeLocale` function." msgstr "" -#: c-api/unicode.rst:749 +#: c-api/unicode.rst:758 msgid "" "The function now also uses the current locale encoding for the " "``surrogateescape`` error handler, except on Android. Previously, :c:func:" @@ -930,24 +947,24 @@ msgid "" "locale encoding was used for ``strict``." msgstr "" -#: c-api/unicode.rst:758 +#: c-api/unicode.rst:767 msgid "File System Encoding" msgstr "" -#: c-api/unicode.rst:760 +#: c-api/unicode.rst:769 msgid "" "Functions encoding to and decoding from the :term:`filesystem encoding and " "error handler` (:pep:`383` and :pep:`529`)." msgstr "" -#: c-api/unicode.rst:763 +#: c-api/unicode.rst:772 msgid "" "To encode file names to :class:`bytes` during argument parsing, the " "``\"O&\"`` converter should be used, passing :c:func:`PyUnicode_FSConverter` " "as the conversion function:" msgstr "" -#: c-api/unicode.rst:769 +#: c-api/unicode.rst:778 msgid "" "ParseTuple converter: encode :class:`str` objects -- obtained directly or " "through the :class:`os.PathLike` interface -- to :class:`bytes` using :c:" @@ -956,18 +973,18 @@ msgid "" "is no longer used." msgstr "" -#: c-api/unicode.rst:794 +#: c-api/unicode.rst:803 msgid "Accepts a :term:`path-like object`." msgstr "" -#: c-api/unicode.rst:780 +#: c-api/unicode.rst:789 msgid "" "To decode file names to :class:`str` during argument parsing, the ``\"O&\"`` " "converter should be used, passing :c:func:`PyUnicode_FSDecoder` as the " "conversion function:" msgstr "" -#: c-api/unicode.rst:786 +#: c-api/unicode.rst:795 msgid "" "ParseTuple converter: decode :class:`bytes` objects -- obtained either " "directly or indirectly through the :class:`os.PathLike` interface -- to :" @@ -976,56 +993,56 @@ msgid "" "which must be released when it is no longer used." msgstr "" -#: c-api/unicode.rst:800 +#: c-api/unicode.rst:809 msgid "Decode a string from the :term:`filesystem encoding and error handler`." msgstr "" -#: c-api/unicode.rst:802 +#: c-api/unicode.rst:811 msgid "" "If you need to decode a string from the current locale encoding, use :c:func:" "`PyUnicode_DecodeLocaleAndSize`." msgstr "" -#: c-api/unicode.rst:822 c-api/unicode.rst:842 +#: c-api/unicode.rst:831 c-api/unicode.rst:851 msgid "" "The :term:`filesystem error handler ` " "is now used." msgstr "" -#: c-api/unicode.rst:816 +#: c-api/unicode.rst:825 msgid "" "Decode a null-terminated string from the :term:`filesystem encoding and " "error handler`." msgstr "" -#: c-api/unicode.rst:819 +#: c-api/unicode.rst:828 msgid "" "If the string length is known, use :c:func:" "`PyUnicode_DecodeFSDefaultAndSize`." msgstr "" -#: c-api/unicode.rst:829 +#: c-api/unicode.rst:838 msgid "" "Encode a Unicode object to the :term:`filesystem encoding and error " "handler`, and return :class:`bytes`. Note that the resulting :class:`bytes` " "object can contain null bytes." msgstr "" -#: c-api/unicode.rst:833 +#: c-api/unicode.rst:842 msgid "" "If you need to encode a string to the current locale encoding, use :c:func:" "`PyUnicode_EncodeLocale`." msgstr "" -#: c-api/unicode.rst:847 +#: c-api/unicode.rst:856 msgid "wchar_t Support" msgstr "" -#: c-api/unicode.rst:849 +#: c-api/unicode.rst:858 msgid ":c:type:`wchar_t` support for platforms which support it:" msgstr "" -#: c-api/unicode.rst:853 +#: c-api/unicode.rst:862 msgid "" "Create a Unicode object from the :c:type:`wchar_t` buffer *wstr* of the " "given *size*. Passing ``-1`` as the *size* indicates that the function must " @@ -1033,7 +1050,7 @@ msgid "" "failure." msgstr "" -#: c-api/unicode.rst:861 +#: c-api/unicode.rst:870 msgid "" "Copy the Unicode object contents into the :c:type:`wchar_t` buffer *wstr*. " "At most *size* :c:type:`wchar_t` characters are copied (excluding a possibly " @@ -1041,13 +1058,13 @@ msgid "" "`wchar_t` characters copied or ``-1`` in case of an error." msgstr "" -#: c-api/unicode.rst:866 +#: c-api/unicode.rst:875 msgid "" "When *wstr* is ``NULL``, instead return the *size* that would be required to " "store all of *unicode* including a terminating null." msgstr "" -#: c-api/unicode.rst:869 +#: c-api/unicode.rst:878 msgid "" "Note that the resulting :c:expr:`wchar_t*` string may or may not be null-" "terminated. It is the responsibility of the caller to make sure that the :c:" @@ -1057,7 +1074,7 @@ msgid "" "most C functions." msgstr "" -#: c-api/unicode.rst:879 +#: c-api/unicode.rst:888 msgid "" "Convert the Unicode object to a wide character string. The output string " "always ends with a null character. If *size* is not ``NULL``, write the " @@ -1068,37 +1085,37 @@ msgid "" "`wchar_t*` string contains null characters a :exc:`ValueError` is raised." msgstr "" -#: c-api/unicode.rst:887 +#: c-api/unicode.rst:896 msgid "" "Returns a buffer allocated by :c:macro:`PyMem_New` (use :c:func:`PyMem_Free` " "to free it) on success. On error, returns ``NULL`` and *\\*size* is " "undefined. Raises a :exc:`MemoryError` if memory allocation is failed." msgstr "" -#: c-api/unicode.rst:894 +#: c-api/unicode.rst:903 msgid "" "Raises a :exc:`ValueError` if *size* is ``NULL`` and the :c:expr:`wchar_t*` " "string contains null characters." msgstr "" -#: c-api/unicode.rst:902 +#: c-api/unicode.rst:911 msgid "Built-in Codecs" msgstr "" -#: c-api/unicode.rst:904 +#: c-api/unicode.rst:913 msgid "" "Python provides a set of built-in codecs which are written in C for speed. " "All of these codecs are directly usable via the following functions." msgstr "" -#: c-api/unicode.rst:907 +#: c-api/unicode.rst:916 msgid "" "Many of the following APIs take two arguments encoding and errors, and they " "have the same semantics as the ones of the built-in :func:`str` string " "object constructor." msgstr "" -#: c-api/unicode.rst:911 +#: c-api/unicode.rst:920 msgid "" "Setting encoding to ``NULL`` causes the default encoding to be used which is " "UTF-8. The file system calls should use :c:func:`PyUnicode_FSConverter` for " @@ -1106,28 +1123,28 @@ msgid "" "handler` internally." msgstr "" -#: c-api/unicode.rst:916 +#: c-api/unicode.rst:925 msgid "" "Error handling is set by errors which may also be set to ``NULL`` meaning to " "use the default handling defined for the codec. Default error handling for " "all built-in codecs is \"strict\" (:exc:`ValueError` is raised)." msgstr "" -#: c-api/unicode.rst:920 +#: c-api/unicode.rst:929 msgid "" "The codecs all use a similar interface. Only deviations from the following " "generic ones are documented for simplicity." msgstr "" -#: c-api/unicode.rst:925 +#: c-api/unicode.rst:934 msgid "Generic Codecs" msgstr "" -#: c-api/unicode.rst:927 +#: c-api/unicode.rst:936 msgid "These are the generic codec APIs:" msgstr "" -#: c-api/unicode.rst:933 +#: c-api/unicode.rst:942 msgid "" "Create a Unicode object by decoding *size* bytes of the encoded string " "*str*. *encoding* and *errors* have the same meaning as the parameters of " @@ -1136,7 +1153,7 @@ msgid "" "was raised by the codec." msgstr "" -#: c-api/unicode.rst:943 +#: c-api/unicode.rst:952 msgid "" "Encode a Unicode object and return the result as Python bytes object. " "*encoding* and *errors* have the same meaning as the parameters of the same " @@ -1145,21 +1162,21 @@ msgid "" "was raised by the codec." msgstr "" -#: c-api/unicode.rst:951 +#: c-api/unicode.rst:960 msgid "UTF-8 Codecs" msgstr "" -#: c-api/unicode.rst:953 +#: c-api/unicode.rst:962 msgid "These are the UTF-8 codec APIs:" msgstr "" -#: c-api/unicode.rst:958 +#: c-api/unicode.rst:967 msgid "" "Create a Unicode object by decoding *size* bytes of the UTF-8 encoded string " "*str*. Return ``NULL`` if an exception was raised by the codec." msgstr "" -#: c-api/unicode.rst:965 +#: c-api/unicode.rst:974 msgid "" "If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF8`. If " "*consumed* is not ``NULL``, trailing incomplete UTF-8 byte sequences will " @@ -1167,14 +1184,14 @@ msgid "" "of bytes that have been decoded will be stored in *consumed*." msgstr "" -#: c-api/unicode.rst:973 +#: c-api/unicode.rst:982 msgid "" "Encode a Unicode object using UTF-8 and return the result as Python bytes " "object. Error handling is \"strict\". Return ``NULL`` if an exception was " "raised by the codec." msgstr "" -#: c-api/unicode.rst:980 +#: c-api/unicode.rst:989 msgid "" "Return a pointer to the UTF-8 encoding of the Unicode object, and store the " "size of the encoded representation (in bytes) in *size*. The *size* " @@ -1183,13 +1200,13 @@ msgid "" "regardless of whether there are any other null code points." msgstr "" -#: c-api/unicode.rst:986 +#: c-api/unicode.rst:995 msgid "" "In the case of an error, ``NULL`` is returned with an exception set and no " "*size* is stored." msgstr "" -#: c-api/unicode.rst:989 +#: c-api/unicode.rst:998 msgid "" "This caches the UTF-8 representation of the string in the Unicode object, " "and subsequent calls will return a pointer to the same buffer. The caller " @@ -1198,40 +1215,47 @@ msgid "" "collected." msgstr "" -#: c-api/unicode.rst:1009 +#: c-api/unicode.rst:1018 msgid "The return type is now ``const char *`` rather of ``char *``." msgstr "" -#: c-api/unicode.rst:999 +#: c-api/unicode.rst:1008 msgid "This function is a part of the :ref:`limited API `." msgstr "" -#: c-api/unicode.rst:1005 +#: c-api/unicode.rst:1014 msgid "As :c:func:`PyUnicode_AsUTF8AndSize`, but does not store the size." msgstr "" -#: c-api/unicode.rst:1014 +#: c-api/unicode.rst:1023 msgid "UTF-32 Codecs" msgstr "" -#: c-api/unicode.rst:1016 +#: c-api/unicode.rst:1025 msgid "These are the UTF-32 codec APIs:" msgstr "" -#: c-api/unicode.rst:1022 +#: c-api/unicode.rst:1031 msgid "" "Decode *size* bytes from a UTF-32 encoded buffer string and return the " "corresponding Unicode object. *errors* (if non-``NULL``) defines the error " "handling. It defaults to \"strict\"." msgstr "" -#: c-api/unicode.rst:1076 +#: c-api/unicode.rst:1085 msgid "" "If *byteorder* is non-``NULL``, the decoder starts decoding using the given " "byte order::" msgstr "" -#: c-api/unicode.rst:1033 +#: c-api/unicode.rst:1088 +msgid "" +"*byteorder == -1: little endian\n" +"*byteorder == 0: native order\n" +"*byteorder == 1: big endian" +msgstr "" + +#: c-api/unicode.rst:1042 msgid "" "If ``*byteorder`` is zero, and the first four bytes of the input data are a " "byte order mark (BOM), the decoder switches to this byte order and the BOM " @@ -1239,21 +1263,21 @@ msgid "" "``-1`` or ``1``, any byte order mark is copied to the output." msgstr "" -#: c-api/unicode.rst:1038 +#: c-api/unicode.rst:1047 msgid "" "After completion, *\\*byteorder* is set to the current byte order at the end " "of input data." msgstr "" -#: c-api/unicode.rst:1092 +#: c-api/unicode.rst:1101 msgid "If *byteorder* is ``NULL``, the codec starts in native order mode." msgstr "" -#: c-api/unicode.rst:1094 +#: c-api/unicode.rst:1103 msgid "Return ``NULL`` if an exception was raised by the codec." msgstr "" -#: c-api/unicode.rst:1049 +#: c-api/unicode.rst:1058 msgid "" "If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF32`. If " "*consumed* is not ``NULL``, :c:func:`PyUnicode_DecodeUTF32Stateful` will not " @@ -1262,29 +1286,29 @@ msgid "" "number of bytes that have been decoded will be stored in *consumed*." msgstr "" -#: c-api/unicode.rst:1058 +#: c-api/unicode.rst:1067 msgid "" "Return a Python byte string using the UTF-32 encoding in native byte order. " "The string always starts with a BOM mark. Error handling is \"strict\". " "Return ``NULL`` if an exception was raised by the codec." msgstr "" -#: c-api/unicode.rst:1064 +#: c-api/unicode.rst:1073 msgid "UTF-16 Codecs" msgstr "" -#: c-api/unicode.rst:1066 +#: c-api/unicode.rst:1075 msgid "These are the UTF-16 codec APIs:" msgstr "" -#: c-api/unicode.rst:1072 +#: c-api/unicode.rst:1081 msgid "" "Decode *size* bytes from a UTF-16 encoded buffer string and return the " "corresponding Unicode object. *errors* (if non-``NULL``) defines the error " "handling. It defaults to \"strict\"." msgstr "" -#: c-api/unicode.rst:1083 +#: c-api/unicode.rst:1092 msgid "" "If ``*byteorder`` is zero, and the first two bytes of the input data are a " "byte order mark (BOM), the decoder switches to this byte order and the BOM " @@ -1293,13 +1317,13 @@ msgid "" "result in either a ``\\ufeff`` or a ``\\ufffe`` character)." msgstr "" -#: c-api/unicode.rst:1089 +#: c-api/unicode.rst:1098 msgid "" "After completion, ``*byteorder`` is set to the current byte order at the end " "of input data." msgstr "" -#: c-api/unicode.rst:1100 +#: c-api/unicode.rst:1109 msgid "" "If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF16`. If " "*consumed* is not ``NULL``, :c:func:`PyUnicode_DecodeUTF16Stateful` will not " @@ -1309,28 +1333,28 @@ msgid "" "*consumed*." msgstr "" -#: c-api/unicode.rst:1109 +#: c-api/unicode.rst:1118 msgid "" "Return a Python byte string using the UTF-16 encoding in native byte order. " "The string always starts with a BOM mark. Error handling is \"strict\". " "Return ``NULL`` if an exception was raised by the codec." msgstr "" -#: c-api/unicode.rst:1115 +#: c-api/unicode.rst:1124 msgid "UTF-7 Codecs" msgstr "" -#: c-api/unicode.rst:1117 +#: c-api/unicode.rst:1126 msgid "These are the UTF-7 codec APIs:" msgstr "" -#: c-api/unicode.rst:1122 +#: c-api/unicode.rst:1131 msgid "" "Create a Unicode object by decoding *size* bytes of the UTF-7 encoded string " "*str*. Return ``NULL`` if an exception was raised by the codec." msgstr "" -#: c-api/unicode.rst:1129 +#: c-api/unicode.rst:1138 msgid "" "If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeUTF7`. If " "*consumed* is not ``NULL``, trailing incomplete UTF-7 base-64 sections will " @@ -1338,101 +1362,101 @@ msgid "" "of bytes that have been decoded will be stored in *consumed*." msgstr "" -#: c-api/unicode.rst:1136 +#: c-api/unicode.rst:1145 msgid "Unicode-Escape Codecs" msgstr "" -#: c-api/unicode.rst:1138 +#: c-api/unicode.rst:1147 msgid "These are the \"Unicode Escape\" codec APIs:" msgstr "" -#: c-api/unicode.rst:1144 +#: c-api/unicode.rst:1153 msgid "" "Create a Unicode object by decoding *size* bytes of the Unicode-Escape " "encoded string *str*. Return ``NULL`` if an exception was raised by the " "codec." msgstr "" -#: c-api/unicode.rst:1150 +#: c-api/unicode.rst:1159 msgid "" "Encode a Unicode object using Unicode-Escape and return the result as a " "bytes object. Error handling is \"strict\". Return ``NULL`` if an " "exception was raised by the codec." msgstr "" -#: c-api/unicode.rst:1156 +#: c-api/unicode.rst:1165 msgid "Raw-Unicode-Escape Codecs" msgstr "" -#: c-api/unicode.rst:1158 +#: c-api/unicode.rst:1167 msgid "These are the \"Raw Unicode Escape\" codec APIs:" msgstr "" -#: c-api/unicode.rst:1164 +#: c-api/unicode.rst:1173 msgid "" "Create a Unicode object by decoding *size* bytes of the Raw-Unicode-Escape " "encoded string *str*. Return ``NULL`` if an exception was raised by the " "codec." msgstr "" -#: c-api/unicode.rst:1170 +#: c-api/unicode.rst:1179 msgid "" "Encode a Unicode object using Raw-Unicode-Escape and return the result as a " "bytes object. Error handling is \"strict\". Return ``NULL`` if an " "exception was raised by the codec." msgstr "" -#: c-api/unicode.rst:1176 +#: c-api/unicode.rst:1185 msgid "Latin-1 Codecs" msgstr "" -#: c-api/unicode.rst:1178 +#: c-api/unicode.rst:1187 msgid "" "These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 " "Unicode ordinals and only these are accepted by the codecs during encoding." msgstr "" -#: c-api/unicode.rst:1184 +#: c-api/unicode.rst:1193 msgid "" "Create a Unicode object by decoding *size* bytes of the Latin-1 encoded " "string *str*. Return ``NULL`` if an exception was raised by the codec." msgstr "" -#: c-api/unicode.rst:1190 +#: c-api/unicode.rst:1199 msgid "" "Encode a Unicode object using Latin-1 and return the result as Python bytes " "object. Error handling is \"strict\". Return ``NULL`` if an exception was " "raised by the codec." msgstr "" -#: c-api/unicode.rst:1196 +#: c-api/unicode.rst:1205 msgid "ASCII Codecs" msgstr "" -#: c-api/unicode.rst:1198 +#: c-api/unicode.rst:1207 msgid "" "These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All " "other codes generate errors." msgstr "" -#: c-api/unicode.rst:1204 +#: c-api/unicode.rst:1213 msgid "" "Create a Unicode object by decoding *size* bytes of the ASCII encoded string " "*str*. Return ``NULL`` if an exception was raised by the codec." msgstr "" -#: c-api/unicode.rst:1210 +#: c-api/unicode.rst:1219 msgid "" "Encode a Unicode object using ASCII and return the result as Python bytes " "object. Error handling is \"strict\". Return ``NULL`` if an exception was " "raised by the codec." msgstr "" -#: c-api/unicode.rst:1216 +#: c-api/unicode.rst:1225 msgid "Character Map Codecs" msgstr "" -#: c-api/unicode.rst:1218 +#: c-api/unicode.rst:1227 msgid "" "This codec is special in that it can be used to implement many different " "codecs (and this is in fact what was done to obtain most of the standard " @@ -1442,18 +1466,18 @@ msgid "" "sequences work well." msgstr "" -#: c-api/unicode.rst:1224 +#: c-api/unicode.rst:1233 msgid "These are the mapping codec APIs:" msgstr "" -#: c-api/unicode.rst:1229 +#: c-api/unicode.rst:1238 msgid "" "Create a Unicode object by decoding *size* bytes of the encoded string *str* " "using the given *mapping* object. Return ``NULL`` if an exception was " "raised by the codec." msgstr "" -#: c-api/unicode.rst:1233 +#: c-api/unicode.rst:1242 msgid "" "If *mapping* is ``NULL``, Latin-1 decoding will be applied. Else *mapping* " "must map bytes ordinals (integers in the range from 0 to 255) to Unicode " @@ -1463,14 +1487,14 @@ msgid "" "treated as undefined mappings and cause an error." msgstr "" -#: c-api/unicode.rst:1244 +#: c-api/unicode.rst:1253 msgid "" "Encode a Unicode object using the given *mapping* object and return the " "result as a bytes object. Error handling is \"strict\". Return ``NULL`` if " "an exception was raised by the codec." msgstr "" -#: c-api/unicode.rst:1248 +#: c-api/unicode.rst:1257 msgid "" "The *mapping* object must map Unicode ordinal integers to bytes objects, " "integers in the range from 0 to 255 or ``None``. Unmapped character " @@ -1478,41 +1502,41 @@ msgid "" "``None`` are treated as \"undefined mapping\" and cause an error." msgstr "" -#: c-api/unicode.rst:1254 +#: c-api/unicode.rst:1263 msgid "The following codec API is special in that maps Unicode to Unicode." msgstr "" -#: c-api/unicode.rst:1258 +#: c-api/unicode.rst:1267 msgid "" "Translate a string by applying a character mapping table to it and return " "the resulting Unicode object. Return ``NULL`` if an exception was raised by " "the codec." msgstr "" -#: c-api/unicode.rst:1262 +#: c-api/unicode.rst:1271 msgid "" "The mapping table must map Unicode ordinal integers to Unicode ordinal " "integers or ``None`` (causing deletion of the character)." msgstr "" -#: c-api/unicode.rst:1265 +#: c-api/unicode.rst:1274 msgid "" "Mapping tables need only provide the :meth:`~object.__getitem__` interface; " "dictionaries and sequences work well. Unmapped character ordinals (ones " "which cause a :exc:`LookupError`) are left untouched and are copied as-is." msgstr "" -#: c-api/unicode.rst:1269 +#: c-api/unicode.rst:1278 msgid "" "*errors* has the usual meaning for codecs. It may be ``NULL`` which " "indicates to use the default error handling." msgstr "" -#: c-api/unicode.rst:1274 +#: c-api/unicode.rst:1283 msgid "MBCS codecs for Windows" msgstr "" -#: c-api/unicode.rst:1276 +#: c-api/unicode.rst:1285 msgid "" "These are the MBCS codec APIs. They are currently only available on Windows " "and use the Win32 MBCS converters to implement the conversions. Note that " @@ -1520,13 +1544,13 @@ msgid "" "is defined by the user settings on the machine running the codec." msgstr "" -#: c-api/unicode.rst:1283 +#: c-api/unicode.rst:1292 msgid "" "Create a Unicode object by decoding *size* bytes of the MBCS encoded string " "*str*. Return ``NULL`` if an exception was raised by the codec." msgstr "" -#: c-api/unicode.rst:1290 +#: c-api/unicode.rst:1299 msgid "" "If *consumed* is ``NULL``, behave like :c:func:`PyUnicode_DecodeMBCS`. If " "*consumed* is not ``NULL``, :c:func:`PyUnicode_DecodeMBCSStateful` will not " @@ -1534,44 +1558,44 @@ msgid "" "will be stored in *consumed*." msgstr "" -#: c-api/unicode.rst:1298 +#: c-api/unicode.rst:1307 msgid "" "Encode a Unicode object using MBCS and return the result as Python bytes " "object. Error handling is \"strict\". Return ``NULL`` if an exception was " "raised by the codec." msgstr "" -#: c-api/unicode.rst:1305 +#: c-api/unicode.rst:1314 msgid "" "Encode the Unicode object using the specified code page and return a Python " "bytes object. Return ``NULL`` if an exception was raised by the codec. Use :" "c:macro:`!CP_ACP` code page to get the MBCS encoder." msgstr "" -#: c-api/unicode.rst:1313 +#: c-api/unicode.rst:1322 msgid "Methods & Slots" msgstr "" -#: c-api/unicode.rst:1319 +#: c-api/unicode.rst:1328 msgid "Methods and Slot Functions" msgstr "" -#: c-api/unicode.rst:1321 +#: c-api/unicode.rst:1330 msgid "" "The following APIs are capable of handling Unicode objects and strings on " "input (we refer to them as strings in the descriptions) and return Unicode " "objects or integers as appropriate." msgstr "" -#: c-api/unicode.rst:1325 +#: c-api/unicode.rst:1334 msgid "They all return ``NULL`` or ``-1`` if an exception occurs." msgstr "" -#: c-api/unicode.rst:1330 +#: c-api/unicode.rst:1339 msgid "Concat two strings giving a new Unicode string." msgstr "" -#: c-api/unicode.rst:1335 +#: c-api/unicode.rst:1344 msgid "" "Split a string giving a list of Unicode strings. If *sep* is ``NULL``, " "splitting will be done at all whitespace substrings. Otherwise, splits " @@ -1580,27 +1604,27 @@ msgid "" "list." msgstr "" -#: c-api/unicode.rst:1343 +#: c-api/unicode.rst:1352 msgid "" "Split a Unicode string at line breaks, returning a list of Unicode strings. " "CRLF is considered to be one line break. If *keepends* is ``0``, the Line " "break characters are not included in the resulting strings." msgstr "" -#: c-api/unicode.rst:1350 +#: c-api/unicode.rst:1359 msgid "" "Join a sequence of strings using the given *separator* and return the " "resulting Unicode string." msgstr "" -#: c-api/unicode.rst:1357 +#: c-api/unicode.rst:1366 msgid "" "Return ``1`` if *substr* matches ``unicode[start:end]`` at the given tail " "end (*direction* == ``-1`` means to do a prefix match, *direction* == ``1`` " "a suffix match), ``0`` otherwise. Return ``-1`` if an error occurred." msgstr "" -#: c-api/unicode.rst:1365 +#: c-api/unicode.rst:1374 msgid "" "Return the first position of *substr* in ``unicode[start:end]`` using the " "given *direction* (*direction* == ``1`` means to do a forward search, " @@ -1609,7 +1633,7 @@ msgid "" "``-2`` indicates that an error occurred and an exception has been set." msgstr "" -#: c-api/unicode.rst:1375 +#: c-api/unicode.rst:1384 msgid "" "Return the first position of the character *ch* in ``unicode[start:end]`` " "using the given *direction* (*direction* == ``1`` means to do a forward " @@ -1619,37 +1643,37 @@ msgid "" "set." msgstr "" -#: c-api/unicode.rst:1383 +#: c-api/unicode.rst:1392 msgid "" "*start* and *end* are now adjusted to behave like ``unicode[start:end]``." msgstr "" -#: c-api/unicode.rst:1390 +#: c-api/unicode.rst:1399 msgid "" "Return the number of non-overlapping occurrences of *substr* in " "``unicode[start:end]``. Return ``-1`` if an error occurred." msgstr "" -#: c-api/unicode.rst:1397 +#: c-api/unicode.rst:1406 msgid "" "Replace at most *maxcount* occurrences of *substr* in *unicode* with " "*replstr* and return the resulting Unicode object. *maxcount* == ``-1`` " "means replace all occurrences." msgstr "" -#: c-api/unicode.rst:1404 +#: c-api/unicode.rst:1413 msgid "" "Compare two strings and return ``-1``, ``0``, ``1`` for less than, equal, " "and greater than, respectively." msgstr "" -#: c-api/unicode.rst:1407 +#: c-api/unicode.rst:1416 msgid "" "This function returns ``-1`` upon failure, so one should call :c:func:" "`PyErr_Occurred` to check for errors." msgstr "" -#: c-api/unicode.rst:1413 +#: c-api/unicode.rst:1422 msgid "" "Compare a Unicode object, *unicode*, with *string* and return ``-1``, ``0``, " "``1`` for less than, equal, and greater than, respectively. It is best to " @@ -1657,51 +1681,51 @@ msgid "" "string as ISO-8859-1 if it contains non-ASCII characters." msgstr "" -#: c-api/unicode.rst:1418 +#: c-api/unicode.rst:1427 msgid "This function does not raise exceptions." msgstr "" -#: c-api/unicode.rst:1423 +#: c-api/unicode.rst:1432 msgid "Rich compare two Unicode strings and return one of the following:" msgstr "" -#: c-api/unicode.rst:1425 +#: c-api/unicode.rst:1434 msgid "``NULL`` in case an exception was raised" msgstr "" -#: c-api/unicode.rst:1426 +#: c-api/unicode.rst:1435 msgid ":c:data:`Py_True` or :c:data:`Py_False` for successful comparisons" msgstr "" -#: c-api/unicode.rst:1427 +#: c-api/unicode.rst:1436 msgid ":c:data:`Py_NotImplemented` in case the type combination is unknown" msgstr "" -#: c-api/unicode.rst:1429 +#: c-api/unicode.rst:1438 msgid "" "Possible values for *op* are :c:macro:`Py_GT`, :c:macro:`Py_GE`, :c:macro:" "`Py_EQ`, :c:macro:`Py_NE`, :c:macro:`Py_LT`, and :c:macro:`Py_LE`." msgstr "" -#: c-api/unicode.rst:1435 +#: c-api/unicode.rst:1444 msgid "" "Return a new string object from *format* and *args*; this is analogous to " "``format % args``." msgstr "" -#: c-api/unicode.rst:1441 +#: c-api/unicode.rst:1450 msgid "" "Check whether *substr* is contained in *unicode* and return true or false " "accordingly." msgstr "" -#: c-api/unicode.rst:1444 +#: c-api/unicode.rst:1453 msgid "" "*substr* has to coerce to a one element Unicode string. ``-1`` is returned " "if there was an error." msgstr "" -#: c-api/unicode.rst:1450 +#: c-api/unicode.rst:1459 msgid "" "Intern the argument :c:expr:`*p_unicode` in place. The argument must be the " "address of a pointer variable pointing to a Python Unicode string object. " @@ -1709,16 +1733,53 @@ msgid "" "`*p_unicode`, it sets :c:expr:`*p_unicode` to it (releasing the reference to " "the old string object and creating a new :term:`strong reference` to the " "interned string object), otherwise it leaves :c:expr:`*p_unicode` alone and " -"interns it (creating a new :term:`strong reference`). (Clarification: even " -"though there is a lot of talk about references, think of this function as " -"reference-neutral; you own the object after the call if and only if you " -"owned it before the call.)" +"interns it." +msgstr "" + +#: c-api/unicode.rst:1466 +msgid "" +"(Clarification: even though there is a lot of talk about references, think " +"of this function as reference-neutral. You must own the object you pass in; " +"after the call you no longer own the passed-in reference, but you newly own " +"the result.)" +msgstr "" + +#: c-api/unicode.rst:1471 +msgid "" +"This function never raises an exception. On error, it leaves its argument " +"unchanged without interning it." +msgstr "" + +#: c-api/unicode.rst:1474 +msgid "" +"Instances of subclasses of :py:class:`str` may not be interned, that is, :c:" +"expr:`PyUnicode_CheckExact(*p_unicode)` must be true. If it is not, then -- " +"as with any other error -- the argument is left unchanged." +msgstr "" + +#: c-api/unicode.rst:1478 +msgid "" +"Note that interned strings are not “immortal”. You must keep a reference to " +"the result to benefit from interning." msgstr "" -#: c-api/unicode.rst:1463 +#: c-api/unicode.rst:1484 msgid "" "A combination of :c:func:`PyUnicode_FromString` and :c:func:" -"`PyUnicode_InternInPlace`, returning either a new Unicode string object that " -"has been interned, or a new (\"owned\") reference to an earlier interned " -"string object with the same value." +"`PyUnicode_InternInPlace`, meant for statically allocated strings." +msgstr "" + +#: c-api/unicode.rst:1487 +msgid "" +"Return a new (\"owned\") reference to either a new Unicode string object " +"that has been interned, or an earlier interned string object with the same " +"value." +msgstr "" + +#: c-api/unicode.rst:1491 +msgid "" +"Python may keep a reference to the result, or prevent it from being garbage-" +"collected promptly. For interning an unbounded number of different strings, " +"such as ones coming from user input, prefer calling :c:func:" +"`PyUnicode_FromString` and :c:func:`PyUnicode_InternInPlace` directly." msgstr "" diff --git a/deprecations/c-api-pending-removal-in-3.14.po b/deprecations/c-api-pending-removal-in-3.14.po index b44414dd4..7e0454485 100644 --- a/deprecations/c-api-pending-removal-in-3.14.po +++ b/deprecations/c-api-pending-removal-in-3.14.po @@ -8,10 +8,11 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" +"Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" @@ -38,139 +39,141 @@ msgid "" msgstr "" #: deprecations/c-api-pending-removal-in-3.14.rst:12 -msgid "``PySys_SetArgvEx()``: set :c:member:`PyConfig.argv` instead." +msgid ":c:func:`!PySys_SetArgvEx()`: Set :c:member:`PyConfig.argv` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:13 -msgid "``PySys_SetArgv()``: set :c:member:`PyConfig.argv` instead." +#: deprecations/c-api-pending-removal-in-3.14.rst:14 +msgid ":c:func:`!PySys_SetArgv()`: Set :c:member:`PyConfig.argv` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:14 -msgid "``Py_SetProgramName()``: set :c:member:`PyConfig.program_name` instead." +#: deprecations/c-api-pending-removal-in-3.14.rst:16 +msgid "" +":c:func:`!Py_SetProgramName()`: Set :c:member:`PyConfig.program_name` " +"instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:15 -msgid "``Py_SetPythonHome()``: set :c:member:`PyConfig.home` instead." +#: deprecations/c-api-pending-removal-in-3.14.rst:18 +msgid ":c:func:`!Py_SetPythonHome()`: Set :c:member:`PyConfig.home` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:17 -#: deprecations/c-api-pending-removal-in-3.14.rst:45 +#: deprecations/c-api-pending-removal-in-3.14.rst:21 +#: deprecations/c-api-pending-removal-in-3.14.rst:71 msgid "" "The :c:func:`Py_InitializeFromConfig` API should be used with :c:type:" "`PyConfig` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:20 +#: deprecations/c-api-pending-removal-in-3.14.rst:24 msgid "Global configuration variables:" msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:22 -msgid ":c:var:`Py_DebugFlag`: use :c:member:`PyConfig.parser_debug` instead." +#: deprecations/c-api-pending-removal-in-3.14.rst:26 +msgid ":c:var:`Py_DebugFlag`: Use :c:member:`PyConfig.parser_debug` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:23 -msgid ":c:var:`Py_VerboseFlag`: use :c:member:`PyConfig.verbose` instead." +#: deprecations/c-api-pending-removal-in-3.14.rst:28 +msgid ":c:var:`Py_VerboseFlag`: Use :c:member:`PyConfig.verbose` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:24 -msgid ":c:var:`Py_QuietFlag`: use :c:member:`PyConfig.quiet` instead." +#: deprecations/c-api-pending-removal-in-3.14.rst:30 +msgid ":c:var:`Py_QuietFlag`: Use :c:member:`PyConfig.quiet` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:25 +#: deprecations/c-api-pending-removal-in-3.14.rst:32 msgid "" -":c:var:`Py_InteractiveFlag`: use :c:member:`PyConfig.interactive` instead." +":c:var:`Py_InteractiveFlag`: Use :c:member:`PyConfig.interactive` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:26 -msgid ":c:var:`Py_InspectFlag`: use :c:member:`PyConfig.inspect` instead." +#: deprecations/c-api-pending-removal-in-3.14.rst:34 +msgid ":c:var:`Py_InspectFlag`: Use :c:member:`PyConfig.inspect` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:27 +#: deprecations/c-api-pending-removal-in-3.14.rst:36 msgid "" -":c:var:`Py_OptimizeFlag`: use :c:member:`PyConfig.optimization_level` " +":c:var:`Py_OptimizeFlag`: Use :c:member:`PyConfig.optimization_level` " "instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:28 -msgid ":c:var:`Py_NoSiteFlag`: use :c:member:`PyConfig.site_import` instead." +#: deprecations/c-api-pending-removal-in-3.14.rst:38 +msgid ":c:var:`Py_NoSiteFlag`: Use :c:member:`PyConfig.site_import` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:29 +#: deprecations/c-api-pending-removal-in-3.14.rst:40 msgid "" -":c:var:`Py_BytesWarningFlag`: use :c:member:`PyConfig.bytes_warning` instead." +":c:var:`Py_BytesWarningFlag`: Use :c:member:`PyConfig.bytes_warning` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:30 +#: deprecations/c-api-pending-removal-in-3.14.rst:42 msgid "" -":c:var:`Py_FrozenFlag`: use :c:member:`PyConfig.pathconfig_warnings` instead." +":c:var:`Py_FrozenFlag`: Use :c:member:`PyConfig.pathconfig_warnings` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:31 +#: deprecations/c-api-pending-removal-in-3.14.rst:44 msgid "" -":c:var:`Py_IgnoreEnvironmentFlag`: use :c:member:`PyConfig.use_environment` " +":c:var:`Py_IgnoreEnvironmentFlag`: Use :c:member:`PyConfig.use_environment` " "instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:32 +#: deprecations/c-api-pending-removal-in-3.14.rst:46 msgid "" -":c:var:`Py_DontWriteBytecodeFlag`: use :c:member:`PyConfig.write_bytecode` " +":c:var:`Py_DontWriteBytecodeFlag`: Use :c:member:`PyConfig.write_bytecode` " "instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:33 +#: deprecations/c-api-pending-removal-in-3.14.rst:48 msgid "" -":c:var:`Py_NoUserSiteDirectory`: use :c:member:`PyConfig." +":c:var:`Py_NoUserSiteDirectory`: Use :c:member:`PyConfig." "user_site_directory` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:34 +#: deprecations/c-api-pending-removal-in-3.14.rst:50 msgid "" -":c:var:`Py_UnbufferedStdioFlag`: use :c:member:`PyConfig.buffered_stdio` " +":c:var:`Py_UnbufferedStdioFlag`: Use :c:member:`PyConfig.buffered_stdio` " "instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:35 +#: deprecations/c-api-pending-removal-in-3.14.rst:52 msgid "" -":c:var:`Py_HashRandomizationFlag`: use :c:member:`PyConfig.use_hash_seed` " +":c:var:`Py_HashRandomizationFlag`: Use :c:member:`PyConfig.use_hash_seed` " "and :c:member:`PyConfig.hash_seed` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:37 -msgid ":c:var:`Py_IsolatedFlag`: use :c:member:`PyConfig.isolated` instead." +#: deprecations/c-api-pending-removal-in-3.14.rst:55 +msgid ":c:var:`Py_IsolatedFlag`: Use :c:member:`PyConfig.isolated` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:38 +#: deprecations/c-api-pending-removal-in-3.14.rst:57 msgid "" -":c:var:`Py_LegacyWindowsFSEncodingFlag`: use :c:member:`PyPreConfig." +":c:var:`Py_LegacyWindowsFSEncodingFlag`: Use :c:member:`PyPreConfig." "legacy_windows_fs_encoding` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:39 +#: deprecations/c-api-pending-removal-in-3.14.rst:59 msgid "" -":c:var:`Py_LegacyWindowsStdioFlag`: use :c:member:`PyConfig." +":c:var:`Py_LegacyWindowsStdioFlag`: Use :c:member:`PyConfig." "legacy_windows_stdio` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:40 +#: deprecations/c-api-pending-removal-in-3.14.rst:61 msgid "" -":c:var:`!Py_FileSystemDefaultEncoding`: use :c:member:`PyConfig." +":c:var:`!Py_FileSystemDefaultEncoding`: Use :c:member:`PyConfig." "filesystem_encoding` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:41 +#: deprecations/c-api-pending-removal-in-3.14.rst:63 msgid "" -":c:var:`!Py_HasFileSystemDefaultEncoding`: use :c:member:`PyConfig." +":c:var:`!Py_HasFileSystemDefaultEncoding`: Use :c:member:`PyConfig." "filesystem_encoding` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:42 +#: deprecations/c-api-pending-removal-in-3.14.rst:65 msgid "" -":c:var:`!Py_FileSystemDefaultEncodeErrors`: use :c:member:`PyConfig." +":c:var:`!Py_FileSystemDefaultEncodeErrors`: Use :c:member:`PyConfig." "filesystem_errors` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:43 +#: deprecations/c-api-pending-removal-in-3.14.rst:67 msgid "" -":c:var:`!Py_UTF8Mode`: use :c:member:`PyPreConfig.utf8_mode` instead. (see :" +":c:var:`!Py_UTF8Mode`: Use :c:member:`PyPreConfig.utf8_mode` instead. (see :" "c:func:`Py_PreInitialize`)" msgstr "" diff --git a/deprecations/c-api-pending-removal-in-3.15.po b/deprecations/c-api-pending-removal-in-3.15.po index cd2e9d8b4..d8fa169b2 100644 --- a/deprecations/c-api-pending-removal-in-3.15.po +++ b/deprecations/c-api-pending-removal-in-3.15.po @@ -8,10 +8,11 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" +"Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" @@ -26,59 +27,54 @@ msgstr "" #: deprecations/c-api-pending-removal-in-3.15.rst:5 msgid "" -":c:func:`PyImport_ImportModuleNoBlock`: use :c:func:`PyImport_ImportModule` " -"instead." -msgstr "" - -#: deprecations/c-api-pending-removal-in-3.15.rst:6 -msgid "" -":c:func:`PyWeakref_GET_OBJECT`: use :c:func:`!PyWeakref_GetRef` instead." +"The :c:func:`PyImport_ImportModuleNoBlock`: Use :c:func:" +"`PyImport_ImportModule` instead." msgstr "" #: deprecations/c-api-pending-removal-in-3.15.rst:7 -msgid ":c:func:`PyWeakref_GetObject`: use :c:func:`!PyWeakref_GetRef` instead." -msgstr "" - -#: deprecations/c-api-pending-removal-in-3.15.rst:8 -msgid ":c:type:`!Py_UNICODE_WIDE` type: use :c:type:`wchar_t` instead." +msgid "" +":c:func:`PyWeakref_GetObject` and :c:func:`PyWeakref_GET_OBJECT`: Use :c:" +"func:`!PyWeakref_GetRef` instead." msgstr "" #: deprecations/c-api-pending-removal-in-3.15.rst:9 -msgid ":c:type:`Py_UNICODE` type: use :c:type:`wchar_t` instead." +msgid "" +":c:type:`Py_UNICODE` type and the :c:macro:`!Py_UNICODE_WIDE` macro: Use :c:" +"type:`wchar_t` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.15.rst:10 +#: deprecations/c-api-pending-removal-in-3.15.rst:11 msgid "Python initialization functions:" msgstr "" -#: deprecations/c-api-pending-removal-in-3.15.rst:12 +#: deprecations/c-api-pending-removal-in-3.15.rst:13 msgid "" -":c:func:`PySys_ResetWarnOptions`: clear :data:`sys.warnoptions` and :data:`!" +":c:func:`PySys_ResetWarnOptions`: Clear :data:`sys.warnoptions` and :data:`!" "warnings.filters` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.15.rst:14 -msgid ":c:func:`Py_GetExecPrefix`: get :data:`sys.exec_prefix` instead." +#: deprecations/c-api-pending-removal-in-3.15.rst:15 +msgid ":c:func:`Py_GetExecPrefix`: Get :data:`sys.exec_prefix` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.15.rst:15 -msgid ":c:func:`Py_GetPath`: get :data:`sys.path` instead." +#: deprecations/c-api-pending-removal-in-3.15.rst:17 +msgid ":c:func:`Py_GetPath`: Get :data:`sys.path` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.15.rst:16 -msgid ":c:func:`Py_GetPrefix`: get :data:`sys.prefix` instead." +#: deprecations/c-api-pending-removal-in-3.15.rst:19 +msgid ":c:func:`Py_GetPrefix`: Get :data:`sys.prefix` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.15.rst:17 -msgid ":c:func:`Py_GetProgramFullPath`: get :data:`sys.executable` instead." +#: deprecations/c-api-pending-removal-in-3.15.rst:21 +msgid ":c:func:`Py_GetProgramFullPath`: Get :data:`sys.executable` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.15.rst:18 -msgid ":c:func:`Py_GetProgramName`: get :data:`sys.executable` instead." +#: deprecations/c-api-pending-removal-in-3.15.rst:23 +msgid ":c:func:`Py_GetProgramName`: Get :data:`sys.executable` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.15.rst:19 +#: deprecations/c-api-pending-removal-in-3.15.rst:25 msgid "" -":c:func:`Py_GetPythonHome`: get :c:member:`PyConfig.home` or the :envvar:" +":c:func:`Py_GetPythonHome`: Get :c:member:`PyConfig.home` or the :envvar:" "`PYTHONHOME` environment variable instead." msgstr "" diff --git a/deprecations/c-api-pending-removal-in-future.po b/deprecations/c-api-pending-removal-in-future.po index 8c8e04a60..c9afaff8a 100644 --- a/deprecations/c-api-pending-removal-in-future.po +++ b/deprecations/c-api-pending-removal-in-future.po @@ -8,10 +8,11 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" +"Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" @@ -27,112 +28,113 @@ msgid "" msgstr "" #: deprecations/c-api-pending-removal-in-future.rst:7 -msgid ":c:macro:`Py_TPFLAGS_HAVE_FINALIZE`: unneeded since Python 3.8." +msgid ":c:macro:`Py_TPFLAGS_HAVE_FINALIZE`: Unneeded since Python 3.8." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:8 -msgid ":c:func:`PyErr_Fetch`: use :c:func:`PyErr_GetRaisedException` instead." +#: deprecations/c-api-pending-removal-in-future.rst:9 +msgid ":c:func:`PyErr_Fetch`: Use :c:func:`PyErr_GetRaisedException` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:9 +#: deprecations/c-api-pending-removal-in-future.rst:11 msgid "" -":c:func:`PyErr_NormalizeException`: use :c:func:`PyErr_GetRaisedException` " +":c:func:`PyErr_NormalizeException`: Use :c:func:`PyErr_GetRaisedException` " "instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:10 +#: deprecations/c-api-pending-removal-in-future.rst:13 msgid "" -":c:func:`PyErr_Restore`: use :c:func:`PyErr_SetRaisedException` instead." +":c:func:`PyErr_Restore`: Use :c:func:`PyErr_SetRaisedException` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:11 +#: deprecations/c-api-pending-removal-in-future.rst:15 msgid "" -":c:func:`PyModule_GetFilename`: use :c:func:`PyModule_GetFilenameObject` " +":c:func:`PyModule_GetFilename`: Use :c:func:`PyModule_GetFilenameObject` " "instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:12 -msgid ":c:func:`PyOS_AfterFork`: use :c:func:`PyOS_AfterFork_Child` instead." +#: deprecations/c-api-pending-removal-in-future.rst:17 +msgid ":c:func:`PyOS_AfterFork`: Use :c:func:`PyOS_AfterFork_Child` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:13 +#: deprecations/c-api-pending-removal-in-future.rst:19 msgid "" -":c:func:`PySlice_GetIndicesEx`: use :c:func:`PySlice_Unpack` and :c:func:" +":c:func:`PySlice_GetIndicesEx`: Use :c:func:`PySlice_Unpack` and :c:func:" "`PySlice_AdjustIndices` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:14 +#: deprecations/c-api-pending-removal-in-future.rst:21 msgid "" -":c:func:`!PyUnicode_AsDecodedObject`: use :c:func:`PyCodec_Decode` instead." +":c:func:`!PyUnicode_AsDecodedObject`: Use :c:func:`PyCodec_Decode` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:15 +#: deprecations/c-api-pending-removal-in-future.rst:23 msgid "" -":c:func:`!PyUnicode_AsDecodedUnicode`: use :c:func:`PyCodec_Decode` instead." +":c:func:`!PyUnicode_AsDecodedUnicode`: Use :c:func:`PyCodec_Decode` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:16 +#: deprecations/c-api-pending-removal-in-future.rst:25 msgid "" -":c:func:`!PyUnicode_AsEncodedObject`: use :c:func:`PyCodec_Encode` instead." +":c:func:`!PyUnicode_AsEncodedObject`: Use :c:func:`PyCodec_Encode` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:17 +#: deprecations/c-api-pending-removal-in-future.rst:27 msgid "" -":c:func:`!PyUnicode_AsEncodedUnicode`: use :c:func:`PyCodec_Encode` instead." +":c:func:`!PyUnicode_AsEncodedUnicode`: Use :c:func:`PyCodec_Encode` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:18 -msgid ":c:func:`PyUnicode_READY`: unneeded since Python 3.12" +#: deprecations/c-api-pending-removal-in-future.rst:29 +msgid ":c:func:`PyUnicode_READY`: Unneeded since Python 3.12" msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:19 -msgid ":c:func:`!PyErr_Display`: use :c:func:`PyErr_DisplayException` instead." +#: deprecations/c-api-pending-removal-in-future.rst:31 +msgid ":c:func:`!PyErr_Display`: Use :c:func:`PyErr_DisplayException` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:20 +#: deprecations/c-api-pending-removal-in-future.rst:33 msgid "" -":c:func:`!_PyErr_ChainExceptions`: use ``_PyErr_ChainExceptions1`` instead." +":c:func:`!_PyErr_ChainExceptions`: Use :c:func:`!_PyErr_ChainExceptions1` " +"instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:21 +#: deprecations/c-api-pending-removal-in-future.rst:35 msgid "" ":c:member:`!PyBytesObject.ob_shash` member: call :c:func:`PyObject_Hash` " "instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:23 +#: deprecations/c-api-pending-removal-in-future.rst:37 msgid ":c:member:`!PyDictObject.ma_version_tag` member." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:24 +#: deprecations/c-api-pending-removal-in-future.rst:38 msgid "Thread Local Storage (TLS) API:" msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:26 +#: deprecations/c-api-pending-removal-in-future.rst:40 msgid "" -":c:func:`PyThread_create_key`: use :c:func:`PyThread_tss_alloc` instead." +":c:func:`PyThread_create_key`: Use :c:func:`PyThread_tss_alloc` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:27 -msgid ":c:func:`PyThread_delete_key`: use :c:func:`PyThread_tss_free` instead." +#: deprecations/c-api-pending-removal-in-future.rst:42 +msgid ":c:func:`PyThread_delete_key`: Use :c:func:`PyThread_tss_free` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:28 +#: deprecations/c-api-pending-removal-in-future.rst:44 msgid "" -":c:func:`PyThread_set_key_value`: use :c:func:`PyThread_tss_set` instead." +":c:func:`PyThread_set_key_value`: Use :c:func:`PyThread_tss_set` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:29 +#: deprecations/c-api-pending-removal-in-future.rst:46 msgid "" -":c:func:`PyThread_get_key_value`: use :c:func:`PyThread_tss_get` instead." +":c:func:`PyThread_get_key_value`: Use :c:func:`PyThread_tss_get` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:30 +#: deprecations/c-api-pending-removal-in-future.rst:48 msgid "" -":c:func:`PyThread_delete_key_value`: use :c:func:`PyThread_tss_delete` " +":c:func:`PyThread_delete_key_value`: Use :c:func:`PyThread_tss_delete` " "instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:31 -msgid ":c:func:`PyThread_ReInitTLS`: unneeded since Python 3.7." +#: deprecations/c-api-pending-removal-in-future.rst:50 +msgid ":c:func:`PyThread_ReInitTLS`: Unneeded since Python 3.7." msgstr "" diff --git a/deprecations/index.po b/deprecations/index.po index fc7c04727..8a7e89b57 100644 --- a/deprecations/index.po +++ b/deprecations/index.po @@ -8,10 +8,11 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" +"Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" @@ -186,7 +187,7 @@ msgstr "" #: deprecations/pending-removal-in-3.13.rst:51 msgid "" -"Use :func:`importlib.resources.files()` instead. Refer to `importlib-" +"Use :func:`importlib.resources.files` instead. Refer to `importlib-" "resources: Migrating from Legacy `_ (:gh:`106531`)" msgstr "" @@ -197,50 +198,62 @@ msgid "Pending Removal in Python 3.14" msgstr "" #: deprecations/pending-removal-in-3.14.rst:4 +msgid "The import system:" +msgstr "" + +#: deprecations/pending-removal-in-3.14.rst:6 +msgid "" +"Setting :attr:`~module.__loader__` on a module while failing to set :attr:" +"`__spec__.loader ` is deprecated. In " +"Python 3.14, :attr:`!__loader__` will cease to be set or taken into " +"consideration by the import system or the standard library." +msgstr "" + +#: deprecations/pending-removal-in-3.14.rst:11 msgid "" ":mod:`argparse`: The *type*, *choices*, and *metavar* parameters of :class:`!" "argparse.BooleanOptionalAction` are deprecated and will be removed in 3.14. " "(Contributed by Nikita Sobolev in :gh:`92248`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:9 +#: deprecations/pending-removal-in-3.14.rst:16 msgid "" ":mod:`ast`: The following features have been deprecated in documentation " "since Python 3.8, now cause a :exc:`DeprecationWarning` to be emitted at " "runtime when they are accessed or used, and will be removed in Python 3.14:" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:13 +#: deprecations/pending-removal-in-3.14.rst:20 msgid ":class:`!ast.Num`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:14 +#: deprecations/pending-removal-in-3.14.rst:21 msgid ":class:`!ast.Str`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:15 +#: deprecations/pending-removal-in-3.14.rst:22 msgid ":class:`!ast.Bytes`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:16 +#: deprecations/pending-removal-in-3.14.rst:23 msgid ":class:`!ast.NameConstant`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:17 +#: deprecations/pending-removal-in-3.14.rst:24 msgid ":class:`!ast.Ellipsis`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:19 +#: deprecations/pending-removal-in-3.14.rst:26 msgid "" "Use :class:`ast.Constant` instead. (Contributed by Serhiy Storchaka in :gh:" "`90953`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:22 +#: deprecations/pending-removal-in-3.14.rst:29 msgid ":mod:`asyncio`:" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:24 +#: deprecations/pending-removal-in-3.14.rst:31 msgid "" "The child watcher classes :class:`~asyncio.MultiLoopChildWatcher`, :class:" "`~asyncio.FastChildWatcher`, :class:`~asyncio.AbstractChildWatcher` and :" @@ -248,7 +261,7 @@ msgid "" "Python 3.14. (Contributed by Kumar Aditya in :gh:`94597`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:30 +#: deprecations/pending-removal-in-3.14.rst:37 msgid "" ":func:`asyncio.set_child_watcher`, :func:`asyncio.get_child_watcher`, :meth:" "`asyncio.AbstractEventLoopPolicy.set_child_watcher` and :meth:`asyncio." @@ -256,7 +269,7 @@ msgid "" "removed in Python 3.14. (Contributed by Kumar Aditya in :gh:`94597`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:36 +#: deprecations/pending-removal-in-3.14.rst:43 msgid "" "The :meth:`~asyncio.get_event_loop` method of the default event loop policy " "now emits a :exc:`DeprecationWarning` if there is no current event loop set " @@ -264,7 +277,7 @@ msgid "" "Rossum in :gh:`100160`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:41 +#: deprecations/pending-removal-in-3.14.rst:48 msgid "" ":mod:`collections.abc`: Deprecated :class:`~collections.abc.ByteString`. " "Prefer :class:`!Sequence` or :class:`~collections.abc.Buffer`. For use in " @@ -272,51 +285,51 @@ msgid "" "abc.Buffer`. (Contributed by Shantanu Jain in :gh:`91896`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:47 +#: deprecations/pending-removal-in-3.14.rst:54 msgid "" ":mod:`email`: Deprecated the *isdst* parameter in :func:`email.utils." "localtime`. (Contributed by Alan Williams in :gh:`72346`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:50 +#: deprecations/pending-removal-in-3.14.rst:57 msgid "" ":mod:`importlib`: ``__package__`` and ``__cached__`` will cease to be set or " "taken into consideration by the import system (:gh:`97879`)." msgstr "" -#: deprecations/pending-removal-in-3.14.rst:53 +#: deprecations/pending-removal-in-3.14.rst:60 msgid ":mod:`importlib.abc` deprecated classes:" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:55 +#: deprecations/pending-removal-in-3.14.rst:62 msgid ":class:`!importlib.abc.ResourceReader`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:56 +#: deprecations/pending-removal-in-3.14.rst:63 msgid ":class:`!importlib.abc.Traversable`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:57 +#: deprecations/pending-removal-in-3.14.rst:64 msgid ":class:`!importlib.abc.TraversableResources`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:59 +#: deprecations/pending-removal-in-3.14.rst:66 msgid "Use :mod:`importlib.resources.abc` classes instead:" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:61 +#: deprecations/pending-removal-in-3.14.rst:68 msgid ":class:`importlib.resources.abc.Traversable`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:62 +#: deprecations/pending-removal-in-3.14.rst:69 msgid ":class:`importlib.resources.abc.TraversableResources`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:64 +#: deprecations/pending-removal-in-3.14.rst:71 msgid "(Contributed by Jason R. Coombs and Hugo van Kemenade in :gh:`93963`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:66 +#: deprecations/pending-removal-in-3.14.rst:73 msgid "" ":mod:`itertools` had undocumented, inefficient, historically buggy, and " "inconsistent support for copy, deepcopy, and pickle operations. This will be " @@ -324,7 +337,7 @@ msgid "" "burden. (Contributed by Raymond Hettinger in :gh:`101588`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:72 +#: deprecations/pending-removal-in-3.14.rst:79 msgid "" ":mod:`multiprocessing`: The default start method will change to a safer one " "on Linux, BSDs, and other non-macOS POSIX platforms where ``'fork'`` is " @@ -335,53 +348,53 @@ msgid "" "``'fork'``. See :ref:`multiprocessing-start-methods`." msgstr "" -#: deprecations/pending-removal-in-3.14.rst:80 +#: deprecations/pending-removal-in-3.14.rst:87 msgid "" ":mod:`pathlib`: :meth:`~pathlib.PurePath.is_relative_to` and :meth:`~pathlib." "PurePath.relative_to`: passing additional arguments is deprecated." msgstr "" -#: deprecations/pending-removal-in-3.14.rst:84 +#: deprecations/pending-removal-in-3.14.rst:91 msgid "" ":mod:`pkgutil`: :func:`~pkgutil.find_loader` and :func:`~pkgutil.get_loader` " "now raise :exc:`DeprecationWarning`; use :func:`importlib.util.find_spec` " "instead. (Contributed by Nikita Sobolev in :gh:`97850`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:89 +#: deprecations/pending-removal-in-3.14.rst:96 msgid ":mod:`pty`:" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:91 +#: deprecations/pending-removal-in-3.14.rst:98 msgid "``master_open()``: use :func:`pty.openpty`." msgstr "" -#: deprecations/pending-removal-in-3.14.rst:92 +#: deprecations/pending-removal-in-3.14.rst:99 msgid "``slave_open()``: use :func:`pty.openpty`." msgstr "" -#: deprecations/pending-removal-in-3.14.rst:94 +#: deprecations/pending-removal-in-3.14.rst:101 msgid ":mod:`sqlite3`:" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:96 +#: deprecations/pending-removal-in-3.14.rst:103 msgid ":data:`~sqlite3.version` and :data:`~sqlite3.version_info`." msgstr "" -#: deprecations/pending-removal-in-3.14.rst:98 +#: deprecations/pending-removal-in-3.14.rst:105 msgid "" ":meth:`~sqlite3.Cursor.execute` and :meth:`~sqlite3.Cursor.executemany` if :" "ref:`named placeholders ` are used and *parameters* is " "a sequence instead of a :class:`dict`." msgstr "" -#: deprecations/pending-removal-in-3.14.rst:102 +#: deprecations/pending-removal-in-3.14.rst:109 msgid "" "date and datetime adapter, date and timestamp converter: see the :mod:" "`sqlite3` documentation for suggested replacement recipes." msgstr "" -#: deprecations/pending-removal-in-3.14.rst:105 +#: deprecations/pending-removal-in-3.14.rst:112 msgid "" ":class:`types.CodeType`: Accessing :attr:`~codeobject.co_lnotab` was " "deprecated in :pep:`626` since 3.10 and was planned to be removed in 3.12, " @@ -389,13 +402,13 @@ msgid "" "in 3.14. (Contributed by Nikita Sobolev in :gh:`101866`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:112 +#: deprecations/pending-removal-in-3.14.rst:119 msgid "" ":mod:`typing`: :class:`~typing.ByteString`, deprecated since Python 3.9, now " "causes a :exc:`DeprecationWarning` to be emitted when it is used." msgstr "" -#: deprecations/pending-removal-in-3.14.rst:115 +#: deprecations/pending-removal-in-3.14.rst:122 msgid "" ":mod:`urllib`: :class:`!urllib.parse.Quoter` is deprecated: it was not " "intended to be a public API. (Contributed by Gregory P. Smith in :gh:" @@ -419,9 +432,9 @@ msgstr "" msgid "" ":class:`locale`: :func:`locale.getdefaultlocale` was deprecated in Python " "3.11 and originally planned for removal in Python 3.13 (:gh:`90817`), but " -"removal has been postponed to Python 3.15. Use :func:`locale.setlocale()`, :" -"func:`locale.getencoding()` and :func:`locale.getlocale()` instead. " -"(Contributed by Hugo van Kemenade in :gh:`111187`.)" +"removal has been postponed to Python 3.15. Use :func:`locale.setlocale`, :" +"func:`locale.getencoding` and :func:`locale.getlocale` instead. (Contributed " +"by Hugo van Kemenade in :gh:`111187`.)" msgstr "" #: deprecations/pending-removal-in-3.15.rst:16 @@ -499,6 +512,10 @@ msgid "" msgstr "" #: deprecations/pending-removal-in-3.16.rst:8 +msgid ":mod:`builtins`: ``~bool``, bitwise inversion on bool." +msgstr "" + +#: deprecations/pending-removal-in-3.16.rst:11 msgid "" ":mod:`symtable`: Deprecate :meth:`symtable.Class.get_methods` due to the " "lack of interest. (Contributed by Bénédikt Tran in :gh:`119698`.)" @@ -530,21 +547,17 @@ msgid ":mod:`builtins`:" msgstr "" #: deprecations/pending-removal-in-future.rst:14 -msgid "``~bool``, bitwise inversion on bool." -msgstr "" - -#: deprecations/pending-removal-in-future.rst:15 msgid "``bool(NotImplemented)``." msgstr "" -#: deprecations/pending-removal-in-future.rst:16 +#: deprecations/pending-removal-in-future.rst:15 msgid "" "Generators: ``throw(type, exc, tb)`` and ``athrow(type, exc, tb)`` signature " "is deprecated: use ``throw(exc)`` and ``athrow(exc)`` instead, the single " "argument signature." msgstr "" -#: deprecations/pending-removal-in-future.rst:19 +#: deprecations/pending-removal-in-future.rst:18 msgid "" "Currently Python accepts numeric literals immediately followed by keywords, " "for example ``0in x``, ``1or x``, ``0if 1else 2``. It allows confusing and " @@ -556,32 +569,32 @@ msgid "" "syntax error. (:gh:`87999`)" msgstr "" -#: deprecations/pending-removal-in-future.rst:27 +#: deprecations/pending-removal-in-future.rst:26 msgid "" "Support for ``__index__()`` and ``__int__()`` method returning non-int type: " "these methods will be required to return an instance of a strict subclass " "of :class:`int`." msgstr "" -#: deprecations/pending-removal-in-future.rst:30 +#: deprecations/pending-removal-in-future.rst:29 msgid "" "Support for ``__float__()`` method returning a strict subclass of :class:" "`float`: these methods will be required to return an instance of :class:" "`float`." msgstr "" -#: deprecations/pending-removal-in-future.rst:33 +#: deprecations/pending-removal-in-future.rst:32 msgid "" "Support for ``__complex__()`` method returning a strict subclass of :class:" "`complex`: these methods will be required to return an instance of :class:" "`complex`." msgstr "" -#: deprecations/pending-removal-in-future.rst:36 +#: deprecations/pending-removal-in-future.rst:35 msgid "Delegation of ``int()`` to ``__trunc__()`` method." msgstr "" -#: deprecations/pending-removal-in-future.rst:37 +#: deprecations/pending-removal-in-future.rst:36 msgid "" "Passing a complex number as the *real* or *imag* argument in the :func:" "`complex` constructor is now deprecated; it should only be passed as a " @@ -589,83 +602,83 @@ msgid "" "`109218`.)" msgstr "" -#: deprecations/pending-removal-in-future.rst:42 +#: deprecations/pending-removal-in-future.rst:41 msgid "" ":mod:`calendar`: ``calendar.January`` and ``calendar.February`` constants " "are deprecated and replaced by :data:`calendar.JANUARY` and :data:`calendar." "FEBRUARY`. (Contributed by Prince Roshan in :gh:`103636`.)" msgstr "" -#: deprecations/pending-removal-in-future.rst:47 +#: deprecations/pending-removal-in-future.rst:46 msgid "" ":attr:`codeobject.co_lnotab`: use the :meth:`codeobject.co_lines` method " "instead." msgstr "" -#: deprecations/pending-removal-in-future.rst:50 +#: deprecations/pending-removal-in-future.rst:49 msgid ":mod:`datetime`:" msgstr "" -#: deprecations/pending-removal-in-future.rst:52 +#: deprecations/pending-removal-in-future.rst:51 msgid "" ":meth:`~datetime.datetime.utcnow`: use ``datetime.datetime.now(tz=datetime." "UTC)``." msgstr "" -#: deprecations/pending-removal-in-future.rst:54 +#: deprecations/pending-removal-in-future.rst:53 msgid "" ":meth:`~datetime.datetime.utcfromtimestamp`: use ``datetime.datetime." "fromtimestamp(timestamp, tz=datetime.UTC)``." msgstr "" -#: deprecations/pending-removal-in-future.rst:57 +#: deprecations/pending-removal-in-future.rst:56 msgid ":mod:`gettext`: Plural value must be an integer." msgstr "" -#: deprecations/pending-removal-in-future.rst:59 +#: deprecations/pending-removal-in-future.rst:58 msgid ":mod:`importlib`:" msgstr "" -#: deprecations/pending-removal-in-future.rst:61 +#: deprecations/pending-removal-in-future.rst:60 msgid "``load_module()`` method: use ``exec_module()`` instead." msgstr "" -#: deprecations/pending-removal-in-future.rst:62 +#: deprecations/pending-removal-in-future.rst:61 msgid "" ":func:`~importlib.util.cache_from_source` *debug_override* parameter is " "deprecated: use the *optimization* parameter instead." msgstr "" -#: deprecations/pending-removal-in-future.rst:65 +#: deprecations/pending-removal-in-future.rst:64 msgid ":mod:`importlib.metadata`:" msgstr "" -#: deprecations/pending-removal-in-future.rst:67 +#: deprecations/pending-removal-in-future.rst:66 msgid "``EntryPoints`` tuple interface." msgstr "" -#: deprecations/pending-removal-in-future.rst:68 +#: deprecations/pending-removal-in-future.rst:67 msgid "Implicit ``None`` on return values." msgstr "" -#: deprecations/pending-removal-in-future.rst:70 +#: deprecations/pending-removal-in-future.rst:69 msgid "" ":mod:`mailbox`: Use of StringIO input and text mode is deprecated, use " "BytesIO and binary mode instead." msgstr "" -#: deprecations/pending-removal-in-future.rst:73 +#: deprecations/pending-removal-in-future.rst:72 msgid "" ":mod:`os`: Calling :func:`os.register_at_fork` in multi-threaded process." msgstr "" -#: deprecations/pending-removal-in-future.rst:75 +#: deprecations/pending-removal-in-future.rst:74 msgid "" ":class:`!pydoc.ErrorDuringImport`: A tuple value for *exc_info* parameter is " "deprecated, use an exception instance." msgstr "" -#: deprecations/pending-removal-in-future.rst:78 +#: deprecations/pending-removal-in-future.rst:77 msgid "" ":mod:`re`: More strict rules are now applied for numerical group references " "and group names in regular expressions. Only sequence of ASCII digits is " @@ -674,185 +687,185 @@ msgid "" "underscore. (Contributed by Serhiy Storchaka in :gh:`91760`.)" msgstr "" -#: deprecations/pending-removal-in-future.rst:85 +#: deprecations/pending-removal-in-future.rst:84 msgid "" ":mod:`!sre_compile`, :mod:`!sre_constants` and :mod:`!sre_parse` modules." msgstr "" -#: deprecations/pending-removal-in-future.rst:87 +#: deprecations/pending-removal-in-future.rst:86 msgid "" ":mod:`shutil`: :func:`~shutil.rmtree`'s *onerror* parameter is deprecated in " "Python 3.12; use the *onexc* parameter instead." msgstr "" -#: deprecations/pending-removal-in-future.rst:90 +#: deprecations/pending-removal-in-future.rst:89 msgid ":mod:`ssl` options and protocols:" msgstr "" -#: deprecations/pending-removal-in-future.rst:92 +#: deprecations/pending-removal-in-future.rst:91 msgid ":class:`ssl.SSLContext` without protocol argument is deprecated." msgstr "" -#: deprecations/pending-removal-in-future.rst:93 +#: deprecations/pending-removal-in-future.rst:92 msgid "" ":class:`ssl.SSLContext`: :meth:`~ssl.SSLContext.set_npn_protocols` and :meth:" "`!selected_npn_protocol` are deprecated: use ALPN instead." msgstr "" -#: deprecations/pending-removal-in-future.rst:96 +#: deprecations/pending-removal-in-future.rst:95 msgid "``ssl.OP_NO_SSL*`` options" msgstr "" -#: deprecations/pending-removal-in-future.rst:97 +#: deprecations/pending-removal-in-future.rst:96 msgid "``ssl.OP_NO_TLS*`` options" msgstr "" -#: deprecations/pending-removal-in-future.rst:98 +#: deprecations/pending-removal-in-future.rst:97 msgid "``ssl.PROTOCOL_SSLv3``" msgstr "" -#: deprecations/pending-removal-in-future.rst:99 +#: deprecations/pending-removal-in-future.rst:98 msgid "``ssl.PROTOCOL_TLS``" msgstr "" -#: deprecations/pending-removal-in-future.rst:100 +#: deprecations/pending-removal-in-future.rst:99 msgid "``ssl.PROTOCOL_TLSv1``" msgstr "" -#: deprecations/pending-removal-in-future.rst:101 +#: deprecations/pending-removal-in-future.rst:100 msgid "``ssl.PROTOCOL_TLSv1_1``" msgstr "" -#: deprecations/pending-removal-in-future.rst:102 +#: deprecations/pending-removal-in-future.rst:101 msgid "``ssl.PROTOCOL_TLSv1_2``" msgstr "" -#: deprecations/pending-removal-in-future.rst:103 +#: deprecations/pending-removal-in-future.rst:102 msgid "``ssl.TLSVersion.SSLv3``" msgstr "" -#: deprecations/pending-removal-in-future.rst:104 +#: deprecations/pending-removal-in-future.rst:103 msgid "``ssl.TLSVersion.TLSv1``" msgstr "" -#: deprecations/pending-removal-in-future.rst:105 +#: deprecations/pending-removal-in-future.rst:104 msgid "``ssl.TLSVersion.TLSv1_1``" msgstr "" -#: deprecations/pending-removal-in-future.rst:107 +#: deprecations/pending-removal-in-future.rst:106 msgid "" ":func:`sysconfig.is_python_build` *check_home* parameter is deprecated and " "ignored." msgstr "" -#: deprecations/pending-removal-in-future.rst:110 +#: deprecations/pending-removal-in-future.rst:109 msgid ":mod:`threading` methods:" msgstr "" -#: deprecations/pending-removal-in-future.rst:112 +#: deprecations/pending-removal-in-future.rst:111 msgid "" ":meth:`!threading.Condition.notifyAll`: use :meth:`~threading.Condition." "notify_all`." msgstr "" -#: deprecations/pending-removal-in-future.rst:113 +#: deprecations/pending-removal-in-future.rst:112 msgid ":meth:`!threading.Event.isSet`: use :meth:`~threading.Event.is_set`." msgstr "" -#: deprecations/pending-removal-in-future.rst:114 +#: deprecations/pending-removal-in-future.rst:113 msgid "" ":meth:`!threading.Thread.isDaemon`, :meth:`threading.Thread.setDaemon`: use :" "attr:`threading.Thread.daemon` attribute." msgstr "" -#: deprecations/pending-removal-in-future.rst:116 +#: deprecations/pending-removal-in-future.rst:115 msgid "" ":meth:`!threading.Thread.getName`, :meth:`threading.Thread.setName`: use :" "attr:`threading.Thread.name` attribute." msgstr "" -#: deprecations/pending-removal-in-future.rst:118 +#: deprecations/pending-removal-in-future.rst:117 msgid ":meth:`!threading.currentThread`: use :meth:`threading.current_thread`." msgstr "" -#: deprecations/pending-removal-in-future.rst:119 +#: deprecations/pending-removal-in-future.rst:118 msgid ":meth:`!threading.activeCount`: use :meth:`threading.active_count`." msgstr "" -#: deprecations/pending-removal-in-future.rst:121 +#: deprecations/pending-removal-in-future.rst:120 msgid ":class:`typing.Text` (:gh:`92332`)." msgstr "" -#: deprecations/pending-removal-in-future.rst:123 +#: deprecations/pending-removal-in-future.rst:122 msgid "" ":class:`unittest.IsolatedAsyncioTestCase`: it is deprecated to return a " "value that is not ``None`` from a test case." msgstr "" -#: deprecations/pending-removal-in-future.rst:126 +#: deprecations/pending-removal-in-future.rst:125 msgid "" ":mod:`urllib.parse` deprecated functions: :func:`~urllib.parse.urlparse` " "instead" msgstr "" -#: deprecations/pending-removal-in-future.rst:128 +#: deprecations/pending-removal-in-future.rst:127 msgid "``splitattr()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:129 +#: deprecations/pending-removal-in-future.rst:128 msgid "``splithost()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:130 +#: deprecations/pending-removal-in-future.rst:129 msgid "``splitnport()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:131 +#: deprecations/pending-removal-in-future.rst:130 msgid "``splitpasswd()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:132 +#: deprecations/pending-removal-in-future.rst:131 msgid "``splitport()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:133 +#: deprecations/pending-removal-in-future.rst:132 msgid "``splitquery()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:134 +#: deprecations/pending-removal-in-future.rst:133 msgid "``splittag()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:135 +#: deprecations/pending-removal-in-future.rst:134 msgid "``splittype()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:136 +#: deprecations/pending-removal-in-future.rst:135 msgid "``splituser()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:137 +#: deprecations/pending-removal-in-future.rst:136 msgid "``splitvalue()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:138 +#: deprecations/pending-removal-in-future.rst:137 msgid "``to_bytes()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:140 +#: deprecations/pending-removal-in-future.rst:139 msgid "" ":mod:`urllib.request`: :class:`~urllib.request.URLopener` and :class:" "`~urllib.request.FancyURLopener` style of invoking requests is deprecated. " "Use newer :func:`~urllib.request.urlopen` functions and methods." msgstr "" -#: deprecations/pending-removal-in-future.rst:144 +#: deprecations/pending-removal-in-future.rst:143 msgid "" ":mod:`wsgiref`: ``SimpleHandler.stdout.write()`` should not do partial " "writes." msgstr "" -#: deprecations/pending-removal-in-future.rst:147 +#: deprecations/pending-removal-in-future.rst:146 msgid "" ":mod:`xml.etree.ElementTree`: Testing the truth value of an :class:`~xml." "etree.ElementTree.Element` is deprecated. In a future release it will always " @@ -860,7 +873,7 @@ msgid "" "instead." msgstr "" -#: deprecations/pending-removal-in-future.rst:152 +#: deprecations/pending-removal-in-future.rst:151 msgid "" ":meth:`zipimport.zipimporter.load_module` is deprecated: use :meth:" "`~zipimport.zipimporter.exec_module` instead." @@ -888,140 +901,142 @@ msgid "" msgstr "" #: deprecations/c-api-pending-removal-in-3.14.rst:12 -msgid "``PySys_SetArgvEx()``: set :c:member:`PyConfig.argv` instead." +msgid ":c:func:`!PySys_SetArgvEx()`: Set :c:member:`PyConfig.argv` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:13 -msgid "``PySys_SetArgv()``: set :c:member:`PyConfig.argv` instead." +#: deprecations/c-api-pending-removal-in-3.14.rst:14 +msgid ":c:func:`!PySys_SetArgv()`: Set :c:member:`PyConfig.argv` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:14 -msgid "``Py_SetProgramName()``: set :c:member:`PyConfig.program_name` instead." +#: deprecations/c-api-pending-removal-in-3.14.rst:16 +msgid "" +":c:func:`!Py_SetProgramName()`: Set :c:member:`PyConfig.program_name` " +"instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:15 -msgid "``Py_SetPythonHome()``: set :c:member:`PyConfig.home` instead." +#: deprecations/c-api-pending-removal-in-3.14.rst:18 +msgid ":c:func:`!Py_SetPythonHome()`: Set :c:member:`PyConfig.home` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:17 -#: deprecations/c-api-pending-removal-in-3.14.rst:45 +#: deprecations/c-api-pending-removal-in-3.14.rst:21 +#: deprecations/c-api-pending-removal-in-3.14.rst:71 msgid "" "The :c:func:`Py_InitializeFromConfig` API should be used with :c:type:" "`PyConfig` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:20 +#: deprecations/c-api-pending-removal-in-3.14.rst:24 msgid "Global configuration variables:" msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:22 -msgid ":c:var:`Py_DebugFlag`: use :c:member:`PyConfig.parser_debug` instead." +#: deprecations/c-api-pending-removal-in-3.14.rst:26 +msgid ":c:var:`Py_DebugFlag`: Use :c:member:`PyConfig.parser_debug` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:23 -msgid ":c:var:`Py_VerboseFlag`: use :c:member:`PyConfig.verbose` instead." +#: deprecations/c-api-pending-removal-in-3.14.rst:28 +msgid ":c:var:`Py_VerboseFlag`: Use :c:member:`PyConfig.verbose` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:24 -msgid ":c:var:`Py_QuietFlag`: use :c:member:`PyConfig.quiet` instead." +#: deprecations/c-api-pending-removal-in-3.14.rst:30 +msgid ":c:var:`Py_QuietFlag`: Use :c:member:`PyConfig.quiet` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:25 +#: deprecations/c-api-pending-removal-in-3.14.rst:32 msgid "" -":c:var:`Py_InteractiveFlag`: use :c:member:`PyConfig.interactive` instead." +":c:var:`Py_InteractiveFlag`: Use :c:member:`PyConfig.interactive` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:26 -msgid ":c:var:`Py_InspectFlag`: use :c:member:`PyConfig.inspect` instead." +#: deprecations/c-api-pending-removal-in-3.14.rst:34 +msgid ":c:var:`Py_InspectFlag`: Use :c:member:`PyConfig.inspect` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:27 +#: deprecations/c-api-pending-removal-in-3.14.rst:36 msgid "" -":c:var:`Py_OptimizeFlag`: use :c:member:`PyConfig.optimization_level` " +":c:var:`Py_OptimizeFlag`: Use :c:member:`PyConfig.optimization_level` " "instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:28 -msgid ":c:var:`Py_NoSiteFlag`: use :c:member:`PyConfig.site_import` instead." +#: deprecations/c-api-pending-removal-in-3.14.rst:38 +msgid ":c:var:`Py_NoSiteFlag`: Use :c:member:`PyConfig.site_import` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:29 +#: deprecations/c-api-pending-removal-in-3.14.rst:40 msgid "" -":c:var:`Py_BytesWarningFlag`: use :c:member:`PyConfig.bytes_warning` instead." +":c:var:`Py_BytesWarningFlag`: Use :c:member:`PyConfig.bytes_warning` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:30 +#: deprecations/c-api-pending-removal-in-3.14.rst:42 msgid "" -":c:var:`Py_FrozenFlag`: use :c:member:`PyConfig.pathconfig_warnings` instead." +":c:var:`Py_FrozenFlag`: Use :c:member:`PyConfig.pathconfig_warnings` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:31 +#: deprecations/c-api-pending-removal-in-3.14.rst:44 msgid "" -":c:var:`Py_IgnoreEnvironmentFlag`: use :c:member:`PyConfig.use_environment` " +":c:var:`Py_IgnoreEnvironmentFlag`: Use :c:member:`PyConfig.use_environment` " "instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:32 +#: deprecations/c-api-pending-removal-in-3.14.rst:46 msgid "" -":c:var:`Py_DontWriteBytecodeFlag`: use :c:member:`PyConfig.write_bytecode` " +":c:var:`Py_DontWriteBytecodeFlag`: Use :c:member:`PyConfig.write_bytecode` " "instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:33 +#: deprecations/c-api-pending-removal-in-3.14.rst:48 msgid "" -":c:var:`Py_NoUserSiteDirectory`: use :c:member:`PyConfig." +":c:var:`Py_NoUserSiteDirectory`: Use :c:member:`PyConfig." "user_site_directory` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:34 +#: deprecations/c-api-pending-removal-in-3.14.rst:50 msgid "" -":c:var:`Py_UnbufferedStdioFlag`: use :c:member:`PyConfig.buffered_stdio` " +":c:var:`Py_UnbufferedStdioFlag`: Use :c:member:`PyConfig.buffered_stdio` " "instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:35 +#: deprecations/c-api-pending-removal-in-3.14.rst:52 msgid "" -":c:var:`Py_HashRandomizationFlag`: use :c:member:`PyConfig.use_hash_seed` " +":c:var:`Py_HashRandomizationFlag`: Use :c:member:`PyConfig.use_hash_seed` " "and :c:member:`PyConfig.hash_seed` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:37 -msgid ":c:var:`Py_IsolatedFlag`: use :c:member:`PyConfig.isolated` instead." +#: deprecations/c-api-pending-removal-in-3.14.rst:55 +msgid ":c:var:`Py_IsolatedFlag`: Use :c:member:`PyConfig.isolated` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:38 +#: deprecations/c-api-pending-removal-in-3.14.rst:57 msgid "" -":c:var:`Py_LegacyWindowsFSEncodingFlag`: use :c:member:`PyPreConfig." +":c:var:`Py_LegacyWindowsFSEncodingFlag`: Use :c:member:`PyPreConfig." "legacy_windows_fs_encoding` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:39 +#: deprecations/c-api-pending-removal-in-3.14.rst:59 msgid "" -":c:var:`Py_LegacyWindowsStdioFlag`: use :c:member:`PyConfig." +":c:var:`Py_LegacyWindowsStdioFlag`: Use :c:member:`PyConfig." "legacy_windows_stdio` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:40 +#: deprecations/c-api-pending-removal-in-3.14.rst:61 msgid "" -":c:var:`!Py_FileSystemDefaultEncoding`: use :c:member:`PyConfig." +":c:var:`!Py_FileSystemDefaultEncoding`: Use :c:member:`PyConfig." "filesystem_encoding` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:41 +#: deprecations/c-api-pending-removal-in-3.14.rst:63 msgid "" -":c:var:`!Py_HasFileSystemDefaultEncoding`: use :c:member:`PyConfig." +":c:var:`!Py_HasFileSystemDefaultEncoding`: Use :c:member:`PyConfig." "filesystem_encoding` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:42 +#: deprecations/c-api-pending-removal-in-3.14.rst:65 msgid "" -":c:var:`!Py_FileSystemDefaultEncodeErrors`: use :c:member:`PyConfig." +":c:var:`!Py_FileSystemDefaultEncodeErrors`: Use :c:member:`PyConfig." "filesystem_errors` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.14.rst:43 +#: deprecations/c-api-pending-removal-in-3.14.rst:67 msgid "" -":c:var:`!Py_UTF8Mode`: use :c:member:`PyPreConfig.utf8_mode` instead. (see :" +":c:var:`!Py_UTF8Mode`: Use :c:member:`PyPreConfig.utf8_mode` instead. (see :" "c:func:`Py_PreInitialize`)" msgstr "" @@ -1031,60 +1046,55 @@ msgstr "" #: deprecations/c-api-pending-removal-in-3.15.rst:5 msgid "" -":c:func:`PyImport_ImportModuleNoBlock`: use :c:func:`PyImport_ImportModule` " -"instead." -msgstr "" - -#: deprecations/c-api-pending-removal-in-3.15.rst:6 -msgid "" -":c:func:`PyWeakref_GET_OBJECT`: use :c:func:`!PyWeakref_GetRef` instead." +"The :c:func:`PyImport_ImportModuleNoBlock`: Use :c:func:" +"`PyImport_ImportModule` instead." msgstr "" #: deprecations/c-api-pending-removal-in-3.15.rst:7 -msgid ":c:func:`PyWeakref_GetObject`: use :c:func:`!PyWeakref_GetRef` instead." -msgstr "" - -#: deprecations/c-api-pending-removal-in-3.15.rst:8 -msgid ":c:type:`!Py_UNICODE_WIDE` type: use :c:type:`wchar_t` instead." +msgid "" +":c:func:`PyWeakref_GetObject` and :c:func:`PyWeakref_GET_OBJECT`: Use :c:" +"func:`!PyWeakref_GetRef` instead." msgstr "" #: deprecations/c-api-pending-removal-in-3.15.rst:9 -msgid ":c:type:`Py_UNICODE` type: use :c:type:`wchar_t` instead." +msgid "" +":c:type:`Py_UNICODE` type and the :c:macro:`!Py_UNICODE_WIDE` macro: Use :c:" +"type:`wchar_t` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.15.rst:10 +#: deprecations/c-api-pending-removal-in-3.15.rst:11 msgid "Python initialization functions:" msgstr "" -#: deprecations/c-api-pending-removal-in-3.15.rst:12 +#: deprecations/c-api-pending-removal-in-3.15.rst:13 msgid "" -":c:func:`PySys_ResetWarnOptions`: clear :data:`sys.warnoptions` and :data:`!" +":c:func:`PySys_ResetWarnOptions`: Clear :data:`sys.warnoptions` and :data:`!" "warnings.filters` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.15.rst:14 -msgid ":c:func:`Py_GetExecPrefix`: get :data:`sys.exec_prefix` instead." +#: deprecations/c-api-pending-removal-in-3.15.rst:15 +msgid ":c:func:`Py_GetExecPrefix`: Get :data:`sys.exec_prefix` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.15.rst:15 -msgid ":c:func:`Py_GetPath`: get :data:`sys.path` instead." +#: deprecations/c-api-pending-removal-in-3.15.rst:17 +msgid ":c:func:`Py_GetPath`: Get :data:`sys.path` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.15.rst:16 -msgid ":c:func:`Py_GetPrefix`: get :data:`sys.prefix` instead." +#: deprecations/c-api-pending-removal-in-3.15.rst:19 +msgid ":c:func:`Py_GetPrefix`: Get :data:`sys.prefix` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.15.rst:17 -msgid ":c:func:`Py_GetProgramFullPath`: get :data:`sys.executable` instead." +#: deprecations/c-api-pending-removal-in-3.15.rst:21 +msgid ":c:func:`Py_GetProgramFullPath`: Get :data:`sys.executable` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.15.rst:18 -msgid ":c:func:`Py_GetProgramName`: get :data:`sys.executable` instead." +#: deprecations/c-api-pending-removal-in-3.15.rst:23 +msgid ":c:func:`Py_GetProgramName`: Get :data:`sys.executable` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-3.15.rst:19 +#: deprecations/c-api-pending-removal-in-3.15.rst:25 msgid "" -":c:func:`Py_GetPythonHome`: get :c:member:`PyConfig.home` or the :envvar:" +":c:func:`Py_GetPythonHome`: Get :c:member:`PyConfig.home` or the :envvar:" "`PYTHONHOME` environment variable instead." msgstr "" @@ -1095,112 +1105,113 @@ msgid "" msgstr "" #: deprecations/c-api-pending-removal-in-future.rst:7 -msgid ":c:macro:`Py_TPFLAGS_HAVE_FINALIZE`: unneeded since Python 3.8." +msgid ":c:macro:`Py_TPFLAGS_HAVE_FINALIZE`: Unneeded since Python 3.8." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:8 -msgid ":c:func:`PyErr_Fetch`: use :c:func:`PyErr_GetRaisedException` instead." +#: deprecations/c-api-pending-removal-in-future.rst:9 +msgid ":c:func:`PyErr_Fetch`: Use :c:func:`PyErr_GetRaisedException` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:9 +#: deprecations/c-api-pending-removal-in-future.rst:11 msgid "" -":c:func:`PyErr_NormalizeException`: use :c:func:`PyErr_GetRaisedException` " +":c:func:`PyErr_NormalizeException`: Use :c:func:`PyErr_GetRaisedException` " "instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:10 +#: deprecations/c-api-pending-removal-in-future.rst:13 msgid "" -":c:func:`PyErr_Restore`: use :c:func:`PyErr_SetRaisedException` instead." +":c:func:`PyErr_Restore`: Use :c:func:`PyErr_SetRaisedException` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:11 +#: deprecations/c-api-pending-removal-in-future.rst:15 msgid "" -":c:func:`PyModule_GetFilename`: use :c:func:`PyModule_GetFilenameObject` " +":c:func:`PyModule_GetFilename`: Use :c:func:`PyModule_GetFilenameObject` " "instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:12 -msgid ":c:func:`PyOS_AfterFork`: use :c:func:`PyOS_AfterFork_Child` instead." +#: deprecations/c-api-pending-removal-in-future.rst:17 +msgid ":c:func:`PyOS_AfterFork`: Use :c:func:`PyOS_AfterFork_Child` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:13 +#: deprecations/c-api-pending-removal-in-future.rst:19 msgid "" -":c:func:`PySlice_GetIndicesEx`: use :c:func:`PySlice_Unpack` and :c:func:" +":c:func:`PySlice_GetIndicesEx`: Use :c:func:`PySlice_Unpack` and :c:func:" "`PySlice_AdjustIndices` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:14 +#: deprecations/c-api-pending-removal-in-future.rst:21 msgid "" -":c:func:`!PyUnicode_AsDecodedObject`: use :c:func:`PyCodec_Decode` instead." +":c:func:`!PyUnicode_AsDecodedObject`: Use :c:func:`PyCodec_Decode` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:15 +#: deprecations/c-api-pending-removal-in-future.rst:23 msgid "" -":c:func:`!PyUnicode_AsDecodedUnicode`: use :c:func:`PyCodec_Decode` instead." +":c:func:`!PyUnicode_AsDecodedUnicode`: Use :c:func:`PyCodec_Decode` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:16 +#: deprecations/c-api-pending-removal-in-future.rst:25 msgid "" -":c:func:`!PyUnicode_AsEncodedObject`: use :c:func:`PyCodec_Encode` instead." +":c:func:`!PyUnicode_AsEncodedObject`: Use :c:func:`PyCodec_Encode` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:17 +#: deprecations/c-api-pending-removal-in-future.rst:27 msgid "" -":c:func:`!PyUnicode_AsEncodedUnicode`: use :c:func:`PyCodec_Encode` instead." +":c:func:`!PyUnicode_AsEncodedUnicode`: Use :c:func:`PyCodec_Encode` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:18 -msgid ":c:func:`PyUnicode_READY`: unneeded since Python 3.12" +#: deprecations/c-api-pending-removal-in-future.rst:29 +msgid ":c:func:`PyUnicode_READY`: Unneeded since Python 3.12" msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:19 -msgid ":c:func:`!PyErr_Display`: use :c:func:`PyErr_DisplayException` instead." +#: deprecations/c-api-pending-removal-in-future.rst:31 +msgid ":c:func:`!PyErr_Display`: Use :c:func:`PyErr_DisplayException` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:20 +#: deprecations/c-api-pending-removal-in-future.rst:33 msgid "" -":c:func:`!_PyErr_ChainExceptions`: use ``_PyErr_ChainExceptions1`` instead." +":c:func:`!_PyErr_ChainExceptions`: Use :c:func:`!_PyErr_ChainExceptions1` " +"instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:21 +#: deprecations/c-api-pending-removal-in-future.rst:35 msgid "" ":c:member:`!PyBytesObject.ob_shash` member: call :c:func:`PyObject_Hash` " "instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:23 +#: deprecations/c-api-pending-removal-in-future.rst:37 msgid ":c:member:`!PyDictObject.ma_version_tag` member." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:24 +#: deprecations/c-api-pending-removal-in-future.rst:38 msgid "Thread Local Storage (TLS) API:" msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:26 +#: deprecations/c-api-pending-removal-in-future.rst:40 msgid "" -":c:func:`PyThread_create_key`: use :c:func:`PyThread_tss_alloc` instead." +":c:func:`PyThread_create_key`: Use :c:func:`PyThread_tss_alloc` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:27 -msgid ":c:func:`PyThread_delete_key`: use :c:func:`PyThread_tss_free` instead." +#: deprecations/c-api-pending-removal-in-future.rst:42 +msgid ":c:func:`PyThread_delete_key`: Use :c:func:`PyThread_tss_free` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:28 +#: deprecations/c-api-pending-removal-in-future.rst:44 msgid "" -":c:func:`PyThread_set_key_value`: use :c:func:`PyThread_tss_set` instead." +":c:func:`PyThread_set_key_value`: Use :c:func:`PyThread_tss_set` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:29 +#: deprecations/c-api-pending-removal-in-future.rst:46 msgid "" -":c:func:`PyThread_get_key_value`: use :c:func:`PyThread_tss_get` instead." +":c:func:`PyThread_get_key_value`: Use :c:func:`PyThread_tss_get` instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:30 +#: deprecations/c-api-pending-removal-in-future.rst:48 msgid "" -":c:func:`PyThread_delete_key_value`: use :c:func:`PyThread_tss_delete` " +":c:func:`PyThread_delete_key_value`: Use :c:func:`PyThread_tss_delete` " "instead." msgstr "" -#: deprecations/c-api-pending-removal-in-future.rst:31 -msgid ":c:func:`PyThread_ReInitTLS`: unneeded since Python 3.7." +#: deprecations/c-api-pending-removal-in-future.rst:50 +msgid ":c:func:`PyThread_ReInitTLS`: Unneeded since Python 3.7." msgstr "" diff --git a/deprecations/pending-removal-in-3.13.po b/deprecations/pending-removal-in-3.13.po index 645108887..7de3750e7 100644 --- a/deprecations/pending-removal-in-3.13.po +++ b/deprecations/pending-removal-in-3.13.po @@ -8,10 +8,11 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" +"Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" @@ -182,7 +183,7 @@ msgstr "" #: deprecations/pending-removal-in-3.13.rst:51 msgid "" -"Use :func:`importlib.resources.files()` instead. Refer to `importlib-" +"Use :func:`importlib.resources.files` instead. Refer to `importlib-" "resources: Migrating from Legacy `_ (:gh:`106531`)" msgstr "" diff --git a/deprecations/pending-removal-in-3.14.po b/deprecations/pending-removal-in-3.14.po index 4f2e96e4b..8fb8bec31 100644 --- a/deprecations/pending-removal-in-3.14.po +++ b/deprecations/pending-removal-in-3.14.po @@ -8,10 +8,11 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" +"Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" @@ -21,50 +22,62 @@ msgid "Pending Removal in Python 3.14" msgstr "" #: deprecations/pending-removal-in-3.14.rst:4 +msgid "The import system:" +msgstr "" + +#: deprecations/pending-removal-in-3.14.rst:6 +msgid "" +"Setting :attr:`~module.__loader__` on a module while failing to set :attr:" +"`__spec__.loader ` is deprecated. In " +"Python 3.14, :attr:`!__loader__` will cease to be set or taken into " +"consideration by the import system or the standard library." +msgstr "" + +#: deprecations/pending-removal-in-3.14.rst:11 msgid "" ":mod:`argparse`: The *type*, *choices*, and *metavar* parameters of :class:`!" "argparse.BooleanOptionalAction` are deprecated and will be removed in 3.14. " "(Contributed by Nikita Sobolev in :gh:`92248`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:9 +#: deprecations/pending-removal-in-3.14.rst:16 msgid "" ":mod:`ast`: The following features have been deprecated in documentation " "since Python 3.8, now cause a :exc:`DeprecationWarning` to be emitted at " "runtime when they are accessed or used, and will be removed in Python 3.14:" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:13 +#: deprecations/pending-removal-in-3.14.rst:20 msgid ":class:`!ast.Num`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:14 +#: deprecations/pending-removal-in-3.14.rst:21 msgid ":class:`!ast.Str`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:15 +#: deprecations/pending-removal-in-3.14.rst:22 msgid ":class:`!ast.Bytes`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:16 +#: deprecations/pending-removal-in-3.14.rst:23 msgid ":class:`!ast.NameConstant`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:17 +#: deprecations/pending-removal-in-3.14.rst:24 msgid ":class:`!ast.Ellipsis`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:19 +#: deprecations/pending-removal-in-3.14.rst:26 msgid "" "Use :class:`ast.Constant` instead. (Contributed by Serhiy Storchaka in :gh:" "`90953`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:22 +#: deprecations/pending-removal-in-3.14.rst:29 msgid ":mod:`asyncio`:" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:24 +#: deprecations/pending-removal-in-3.14.rst:31 msgid "" "The child watcher classes :class:`~asyncio.MultiLoopChildWatcher`, :class:" "`~asyncio.FastChildWatcher`, :class:`~asyncio.AbstractChildWatcher` and :" @@ -72,7 +85,7 @@ msgid "" "Python 3.14. (Contributed by Kumar Aditya in :gh:`94597`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:30 +#: deprecations/pending-removal-in-3.14.rst:37 msgid "" ":func:`asyncio.set_child_watcher`, :func:`asyncio.get_child_watcher`, :meth:" "`asyncio.AbstractEventLoopPolicy.set_child_watcher` and :meth:`asyncio." @@ -80,7 +93,7 @@ msgid "" "removed in Python 3.14. (Contributed by Kumar Aditya in :gh:`94597`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:36 +#: deprecations/pending-removal-in-3.14.rst:43 msgid "" "The :meth:`~asyncio.get_event_loop` method of the default event loop policy " "now emits a :exc:`DeprecationWarning` if there is no current event loop set " @@ -88,7 +101,7 @@ msgid "" "Rossum in :gh:`100160`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:41 +#: deprecations/pending-removal-in-3.14.rst:48 msgid "" ":mod:`collections.abc`: Deprecated :class:`~collections.abc.ByteString`. " "Prefer :class:`!Sequence` or :class:`~collections.abc.Buffer`. For use in " @@ -96,51 +109,51 @@ msgid "" "abc.Buffer`. (Contributed by Shantanu Jain in :gh:`91896`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:47 +#: deprecations/pending-removal-in-3.14.rst:54 msgid "" ":mod:`email`: Deprecated the *isdst* parameter in :func:`email.utils." "localtime`. (Contributed by Alan Williams in :gh:`72346`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:50 +#: deprecations/pending-removal-in-3.14.rst:57 msgid "" ":mod:`importlib`: ``__package__`` and ``__cached__`` will cease to be set or " "taken into consideration by the import system (:gh:`97879`)." msgstr "" -#: deprecations/pending-removal-in-3.14.rst:53 +#: deprecations/pending-removal-in-3.14.rst:60 msgid ":mod:`importlib.abc` deprecated classes:" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:55 +#: deprecations/pending-removal-in-3.14.rst:62 msgid ":class:`!importlib.abc.ResourceReader`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:56 +#: deprecations/pending-removal-in-3.14.rst:63 msgid ":class:`!importlib.abc.Traversable`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:57 +#: deprecations/pending-removal-in-3.14.rst:64 msgid ":class:`!importlib.abc.TraversableResources`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:59 +#: deprecations/pending-removal-in-3.14.rst:66 msgid "Use :mod:`importlib.resources.abc` classes instead:" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:61 +#: deprecations/pending-removal-in-3.14.rst:68 msgid ":class:`importlib.resources.abc.Traversable`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:62 +#: deprecations/pending-removal-in-3.14.rst:69 msgid ":class:`importlib.resources.abc.TraversableResources`" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:64 +#: deprecations/pending-removal-in-3.14.rst:71 msgid "(Contributed by Jason R. Coombs and Hugo van Kemenade in :gh:`93963`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:66 +#: deprecations/pending-removal-in-3.14.rst:73 msgid "" ":mod:`itertools` had undocumented, inefficient, historically buggy, and " "inconsistent support for copy, deepcopy, and pickle operations. This will be " @@ -148,7 +161,7 @@ msgid "" "burden. (Contributed by Raymond Hettinger in :gh:`101588`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:72 +#: deprecations/pending-removal-in-3.14.rst:79 msgid "" ":mod:`multiprocessing`: The default start method will change to a safer one " "on Linux, BSDs, and other non-macOS POSIX platforms where ``'fork'`` is " @@ -159,53 +172,53 @@ msgid "" "``'fork'``. See :ref:`multiprocessing-start-methods`." msgstr "" -#: deprecations/pending-removal-in-3.14.rst:80 +#: deprecations/pending-removal-in-3.14.rst:87 msgid "" ":mod:`pathlib`: :meth:`~pathlib.PurePath.is_relative_to` and :meth:`~pathlib." "PurePath.relative_to`: passing additional arguments is deprecated." msgstr "" -#: deprecations/pending-removal-in-3.14.rst:84 +#: deprecations/pending-removal-in-3.14.rst:91 msgid "" ":mod:`pkgutil`: :func:`~pkgutil.find_loader` and :func:`~pkgutil.get_loader` " "now raise :exc:`DeprecationWarning`; use :func:`importlib.util.find_spec` " "instead. (Contributed by Nikita Sobolev in :gh:`97850`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:89 +#: deprecations/pending-removal-in-3.14.rst:96 msgid ":mod:`pty`:" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:91 +#: deprecations/pending-removal-in-3.14.rst:98 msgid "``master_open()``: use :func:`pty.openpty`." msgstr "" -#: deprecations/pending-removal-in-3.14.rst:92 +#: deprecations/pending-removal-in-3.14.rst:99 msgid "``slave_open()``: use :func:`pty.openpty`." msgstr "" -#: deprecations/pending-removal-in-3.14.rst:94 +#: deprecations/pending-removal-in-3.14.rst:101 msgid ":mod:`sqlite3`:" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:96 +#: deprecations/pending-removal-in-3.14.rst:103 msgid ":data:`~sqlite3.version` and :data:`~sqlite3.version_info`." msgstr "" -#: deprecations/pending-removal-in-3.14.rst:98 +#: deprecations/pending-removal-in-3.14.rst:105 msgid "" ":meth:`~sqlite3.Cursor.execute` and :meth:`~sqlite3.Cursor.executemany` if :" "ref:`named placeholders ` are used and *parameters* is " "a sequence instead of a :class:`dict`." msgstr "" -#: deprecations/pending-removal-in-3.14.rst:102 +#: deprecations/pending-removal-in-3.14.rst:109 msgid "" "date and datetime adapter, date and timestamp converter: see the :mod:" "`sqlite3` documentation for suggested replacement recipes." msgstr "" -#: deprecations/pending-removal-in-3.14.rst:105 +#: deprecations/pending-removal-in-3.14.rst:112 msgid "" ":class:`types.CodeType`: Accessing :attr:`~codeobject.co_lnotab` was " "deprecated in :pep:`626` since 3.10 and was planned to be removed in 3.12, " @@ -213,13 +226,13 @@ msgid "" "in 3.14. (Contributed by Nikita Sobolev in :gh:`101866`.)" msgstr "" -#: deprecations/pending-removal-in-3.14.rst:112 +#: deprecations/pending-removal-in-3.14.rst:119 msgid "" ":mod:`typing`: :class:`~typing.ByteString`, deprecated since Python 3.9, now " "causes a :exc:`DeprecationWarning` to be emitted when it is used." msgstr "" -#: deprecations/pending-removal-in-3.14.rst:115 +#: deprecations/pending-removal-in-3.14.rst:122 msgid "" ":mod:`urllib`: :class:`!urllib.parse.Quoter` is deprecated: it was not " "intended to be a public API. (Contributed by Gregory P. Smith in :gh:" diff --git a/deprecations/pending-removal-in-3.15.po b/deprecations/pending-removal-in-3.15.po index 698286c65..2074d7f0f 100644 --- a/deprecations/pending-removal-in-3.15.po +++ b/deprecations/pending-removal-in-3.15.po @@ -8,10 +8,11 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" +"Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" @@ -32,9 +33,9 @@ msgstr "" msgid "" ":class:`locale`: :func:`locale.getdefaultlocale` was deprecated in Python " "3.11 and originally planned for removal in Python 3.13 (:gh:`90817`), but " -"removal has been postponed to Python 3.15. Use :func:`locale.setlocale()`, :" -"func:`locale.getencoding()` and :func:`locale.getlocale()` instead. " -"(Contributed by Hugo van Kemenade in :gh:`111187`.)" +"removal has been postponed to Python 3.15. Use :func:`locale.setlocale`, :" +"func:`locale.getencoding` and :func:`locale.getlocale` instead. (Contributed " +"by Hugo van Kemenade in :gh:`111187`.)" msgstr "" #: deprecations/pending-removal-in-3.15.rst:16 diff --git a/deprecations/pending-removal-in-3.16.po b/deprecations/pending-removal-in-3.16.po index c95dac962..9526b7b03 100644 --- a/deprecations/pending-removal-in-3.16.po +++ b/deprecations/pending-removal-in-3.16.po @@ -8,10 +8,11 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" +"Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" @@ -27,6 +28,10 @@ msgid "" msgstr "" #: deprecations/pending-removal-in-3.16.rst:8 +msgid ":mod:`builtins`: ``~bool``, bitwise inversion on bool." +msgstr "" + +#: deprecations/pending-removal-in-3.16.rst:11 msgid "" ":mod:`symtable`: Deprecate :meth:`symtable.Class.get_methods` due to the " "lack of interest. (Contributed by Bénédikt Tran in :gh:`119698`.)" diff --git a/deprecations/pending-removal-in-future.po b/deprecations/pending-removal-in-future.po index 55ec30d14..d65a890d5 100644 --- a/deprecations/pending-removal-in-future.po +++ b/deprecations/pending-removal-in-future.po @@ -8,10 +8,11 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" +"Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" @@ -41,21 +42,17 @@ msgid ":mod:`builtins`:" msgstr "" #: deprecations/pending-removal-in-future.rst:14 -msgid "``~bool``, bitwise inversion on bool." -msgstr "" - -#: deprecations/pending-removal-in-future.rst:15 msgid "``bool(NotImplemented)``." msgstr "" -#: deprecations/pending-removal-in-future.rst:16 +#: deprecations/pending-removal-in-future.rst:15 msgid "" "Generators: ``throw(type, exc, tb)`` and ``athrow(type, exc, tb)`` signature " "is deprecated: use ``throw(exc)`` and ``athrow(exc)`` instead, the single " "argument signature." msgstr "" -#: deprecations/pending-removal-in-future.rst:19 +#: deprecations/pending-removal-in-future.rst:18 msgid "" "Currently Python accepts numeric literals immediately followed by keywords, " "for example ``0in x``, ``1or x``, ``0if 1else 2``. It allows confusing and " @@ -67,32 +64,32 @@ msgid "" "syntax error. (:gh:`87999`)" msgstr "" -#: deprecations/pending-removal-in-future.rst:27 +#: deprecations/pending-removal-in-future.rst:26 msgid "" "Support for ``__index__()`` and ``__int__()`` method returning non-int type: " "these methods will be required to return an instance of a strict subclass " "of :class:`int`." msgstr "" -#: deprecations/pending-removal-in-future.rst:30 +#: deprecations/pending-removal-in-future.rst:29 msgid "" "Support for ``__float__()`` method returning a strict subclass of :class:" "`float`: these methods will be required to return an instance of :class:" "`float`." msgstr "" -#: deprecations/pending-removal-in-future.rst:33 +#: deprecations/pending-removal-in-future.rst:32 msgid "" "Support for ``__complex__()`` method returning a strict subclass of :class:" "`complex`: these methods will be required to return an instance of :class:" "`complex`." msgstr "" -#: deprecations/pending-removal-in-future.rst:36 +#: deprecations/pending-removal-in-future.rst:35 msgid "Delegation of ``int()`` to ``__trunc__()`` method." msgstr "" -#: deprecations/pending-removal-in-future.rst:37 +#: deprecations/pending-removal-in-future.rst:36 msgid "" "Passing a complex number as the *real* or *imag* argument in the :func:" "`complex` constructor is now deprecated; it should only be passed as a " @@ -100,83 +97,83 @@ msgid "" "`109218`.)" msgstr "" -#: deprecations/pending-removal-in-future.rst:42 +#: deprecations/pending-removal-in-future.rst:41 msgid "" ":mod:`calendar`: ``calendar.January`` and ``calendar.February`` constants " "are deprecated and replaced by :data:`calendar.JANUARY` and :data:`calendar." "FEBRUARY`. (Contributed by Prince Roshan in :gh:`103636`.)" msgstr "" -#: deprecations/pending-removal-in-future.rst:47 +#: deprecations/pending-removal-in-future.rst:46 msgid "" ":attr:`codeobject.co_lnotab`: use the :meth:`codeobject.co_lines` method " "instead." msgstr "" -#: deprecations/pending-removal-in-future.rst:50 +#: deprecations/pending-removal-in-future.rst:49 msgid ":mod:`datetime`:" msgstr "" -#: deprecations/pending-removal-in-future.rst:52 +#: deprecations/pending-removal-in-future.rst:51 msgid "" ":meth:`~datetime.datetime.utcnow`: use ``datetime.datetime.now(tz=datetime." "UTC)``." msgstr "" -#: deprecations/pending-removal-in-future.rst:54 +#: deprecations/pending-removal-in-future.rst:53 msgid "" ":meth:`~datetime.datetime.utcfromtimestamp`: use ``datetime.datetime." "fromtimestamp(timestamp, tz=datetime.UTC)``." msgstr "" -#: deprecations/pending-removal-in-future.rst:57 +#: deprecations/pending-removal-in-future.rst:56 msgid ":mod:`gettext`: Plural value must be an integer." msgstr "" -#: deprecations/pending-removal-in-future.rst:59 +#: deprecations/pending-removal-in-future.rst:58 msgid ":mod:`importlib`:" msgstr "" -#: deprecations/pending-removal-in-future.rst:61 +#: deprecations/pending-removal-in-future.rst:60 msgid "``load_module()`` method: use ``exec_module()`` instead." msgstr "" -#: deprecations/pending-removal-in-future.rst:62 +#: deprecations/pending-removal-in-future.rst:61 msgid "" ":func:`~importlib.util.cache_from_source` *debug_override* parameter is " "deprecated: use the *optimization* parameter instead." msgstr "" -#: deprecations/pending-removal-in-future.rst:65 +#: deprecations/pending-removal-in-future.rst:64 msgid ":mod:`importlib.metadata`:" msgstr "" -#: deprecations/pending-removal-in-future.rst:67 +#: deprecations/pending-removal-in-future.rst:66 msgid "``EntryPoints`` tuple interface." msgstr "" -#: deprecations/pending-removal-in-future.rst:68 +#: deprecations/pending-removal-in-future.rst:67 msgid "Implicit ``None`` on return values." msgstr "" -#: deprecations/pending-removal-in-future.rst:70 +#: deprecations/pending-removal-in-future.rst:69 msgid "" ":mod:`mailbox`: Use of StringIO input and text mode is deprecated, use " "BytesIO and binary mode instead." msgstr "" -#: deprecations/pending-removal-in-future.rst:73 +#: deprecations/pending-removal-in-future.rst:72 msgid "" ":mod:`os`: Calling :func:`os.register_at_fork` in multi-threaded process." msgstr "" -#: deprecations/pending-removal-in-future.rst:75 +#: deprecations/pending-removal-in-future.rst:74 msgid "" ":class:`!pydoc.ErrorDuringImport`: A tuple value for *exc_info* parameter is " "deprecated, use an exception instance." msgstr "" -#: deprecations/pending-removal-in-future.rst:78 +#: deprecations/pending-removal-in-future.rst:77 msgid "" ":mod:`re`: More strict rules are now applied for numerical group references " "and group names in regular expressions. Only sequence of ASCII digits is " @@ -185,185 +182,185 @@ msgid "" "underscore. (Contributed by Serhiy Storchaka in :gh:`91760`.)" msgstr "" -#: deprecations/pending-removal-in-future.rst:85 +#: deprecations/pending-removal-in-future.rst:84 msgid "" ":mod:`!sre_compile`, :mod:`!sre_constants` and :mod:`!sre_parse` modules." msgstr "" -#: deprecations/pending-removal-in-future.rst:87 +#: deprecations/pending-removal-in-future.rst:86 msgid "" ":mod:`shutil`: :func:`~shutil.rmtree`'s *onerror* parameter is deprecated in " "Python 3.12; use the *onexc* parameter instead." msgstr "" -#: deprecations/pending-removal-in-future.rst:90 +#: deprecations/pending-removal-in-future.rst:89 msgid ":mod:`ssl` options and protocols:" msgstr "" -#: deprecations/pending-removal-in-future.rst:92 +#: deprecations/pending-removal-in-future.rst:91 msgid ":class:`ssl.SSLContext` without protocol argument is deprecated." msgstr "" -#: deprecations/pending-removal-in-future.rst:93 +#: deprecations/pending-removal-in-future.rst:92 msgid "" ":class:`ssl.SSLContext`: :meth:`~ssl.SSLContext.set_npn_protocols` and :meth:" "`!selected_npn_protocol` are deprecated: use ALPN instead." msgstr "" -#: deprecations/pending-removal-in-future.rst:96 +#: deprecations/pending-removal-in-future.rst:95 msgid "``ssl.OP_NO_SSL*`` options" msgstr "" -#: deprecations/pending-removal-in-future.rst:97 +#: deprecations/pending-removal-in-future.rst:96 msgid "``ssl.OP_NO_TLS*`` options" msgstr "" -#: deprecations/pending-removal-in-future.rst:98 +#: deprecations/pending-removal-in-future.rst:97 msgid "``ssl.PROTOCOL_SSLv3``" msgstr "" -#: deprecations/pending-removal-in-future.rst:99 +#: deprecations/pending-removal-in-future.rst:98 msgid "``ssl.PROTOCOL_TLS``" msgstr "" -#: deprecations/pending-removal-in-future.rst:100 +#: deprecations/pending-removal-in-future.rst:99 msgid "``ssl.PROTOCOL_TLSv1``" msgstr "" -#: deprecations/pending-removal-in-future.rst:101 +#: deprecations/pending-removal-in-future.rst:100 msgid "``ssl.PROTOCOL_TLSv1_1``" msgstr "" -#: deprecations/pending-removal-in-future.rst:102 +#: deprecations/pending-removal-in-future.rst:101 msgid "``ssl.PROTOCOL_TLSv1_2``" msgstr "" -#: deprecations/pending-removal-in-future.rst:103 +#: deprecations/pending-removal-in-future.rst:102 msgid "``ssl.TLSVersion.SSLv3``" msgstr "" -#: deprecations/pending-removal-in-future.rst:104 +#: deprecations/pending-removal-in-future.rst:103 msgid "``ssl.TLSVersion.TLSv1``" msgstr "" -#: deprecations/pending-removal-in-future.rst:105 +#: deprecations/pending-removal-in-future.rst:104 msgid "``ssl.TLSVersion.TLSv1_1``" msgstr "" -#: deprecations/pending-removal-in-future.rst:107 +#: deprecations/pending-removal-in-future.rst:106 msgid "" ":func:`sysconfig.is_python_build` *check_home* parameter is deprecated and " "ignored." msgstr "" -#: deprecations/pending-removal-in-future.rst:110 +#: deprecations/pending-removal-in-future.rst:109 msgid ":mod:`threading` methods:" msgstr "" -#: deprecations/pending-removal-in-future.rst:112 +#: deprecations/pending-removal-in-future.rst:111 msgid "" ":meth:`!threading.Condition.notifyAll`: use :meth:`~threading.Condition." "notify_all`." msgstr "" -#: deprecations/pending-removal-in-future.rst:113 +#: deprecations/pending-removal-in-future.rst:112 msgid ":meth:`!threading.Event.isSet`: use :meth:`~threading.Event.is_set`." msgstr "" -#: deprecations/pending-removal-in-future.rst:114 +#: deprecations/pending-removal-in-future.rst:113 msgid "" ":meth:`!threading.Thread.isDaemon`, :meth:`threading.Thread.setDaemon`: use :" "attr:`threading.Thread.daemon` attribute." msgstr "" -#: deprecations/pending-removal-in-future.rst:116 +#: deprecations/pending-removal-in-future.rst:115 msgid "" ":meth:`!threading.Thread.getName`, :meth:`threading.Thread.setName`: use :" "attr:`threading.Thread.name` attribute." msgstr "" -#: deprecations/pending-removal-in-future.rst:118 +#: deprecations/pending-removal-in-future.rst:117 msgid ":meth:`!threading.currentThread`: use :meth:`threading.current_thread`." msgstr "" -#: deprecations/pending-removal-in-future.rst:119 +#: deprecations/pending-removal-in-future.rst:118 msgid ":meth:`!threading.activeCount`: use :meth:`threading.active_count`." msgstr "" -#: deprecations/pending-removal-in-future.rst:121 +#: deprecations/pending-removal-in-future.rst:120 msgid ":class:`typing.Text` (:gh:`92332`)." msgstr "" -#: deprecations/pending-removal-in-future.rst:123 +#: deprecations/pending-removal-in-future.rst:122 msgid "" ":class:`unittest.IsolatedAsyncioTestCase`: it is deprecated to return a " "value that is not ``None`` from a test case." msgstr "" -#: deprecations/pending-removal-in-future.rst:126 +#: deprecations/pending-removal-in-future.rst:125 msgid "" ":mod:`urllib.parse` deprecated functions: :func:`~urllib.parse.urlparse` " "instead" msgstr "" -#: deprecations/pending-removal-in-future.rst:128 +#: deprecations/pending-removal-in-future.rst:127 msgid "``splitattr()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:129 +#: deprecations/pending-removal-in-future.rst:128 msgid "``splithost()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:130 +#: deprecations/pending-removal-in-future.rst:129 msgid "``splitnport()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:131 +#: deprecations/pending-removal-in-future.rst:130 msgid "``splitpasswd()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:132 +#: deprecations/pending-removal-in-future.rst:131 msgid "``splitport()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:133 +#: deprecations/pending-removal-in-future.rst:132 msgid "``splitquery()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:134 +#: deprecations/pending-removal-in-future.rst:133 msgid "``splittag()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:135 +#: deprecations/pending-removal-in-future.rst:134 msgid "``splittype()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:136 +#: deprecations/pending-removal-in-future.rst:135 msgid "``splituser()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:137 +#: deprecations/pending-removal-in-future.rst:136 msgid "``splitvalue()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:138 +#: deprecations/pending-removal-in-future.rst:137 msgid "``to_bytes()``" msgstr "" -#: deprecations/pending-removal-in-future.rst:140 +#: deprecations/pending-removal-in-future.rst:139 msgid "" ":mod:`urllib.request`: :class:`~urllib.request.URLopener` and :class:" "`~urllib.request.FancyURLopener` style of invoking requests is deprecated. " "Use newer :func:`~urllib.request.urlopen` functions and methods." msgstr "" -#: deprecations/pending-removal-in-future.rst:144 +#: deprecations/pending-removal-in-future.rst:143 msgid "" ":mod:`wsgiref`: ``SimpleHandler.stdout.write()`` should not do partial " "writes." msgstr "" -#: deprecations/pending-removal-in-future.rst:147 +#: deprecations/pending-removal-in-future.rst:146 msgid "" ":mod:`xml.etree.ElementTree`: Testing the truth value of an :class:`~xml." "etree.ElementTree.Element` is deprecated. In a future release it will always " @@ -371,7 +368,7 @@ msgid "" "instead." msgstr "" -#: deprecations/pending-removal-in-future.rst:152 +#: deprecations/pending-removal-in-future.rst:151 msgid "" ":meth:`zipimport.zipimporter.load_module` is deprecated: use :meth:" "`~zipimport.zipimporter.exec_module` instead." diff --git a/extending/building.po b/extending/building.po index 80292585d..52a8fbc90 100644 --- a/extending/building.po +++ b/extending/building.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-09-18 22:33+0300\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -54,6 +54,16 @@ msgid "" "*punycode* encoding with hyphens replaced by underscores. In Python::" msgstr "" +#: extending/building.rst:32 +msgid "" +"def initfunc_name(name):\n" +" try:\n" +" suffix = b'_' + name.encode('ascii')\n" +" except UnicodeEncodeError:\n" +" suffix = b'U_' + name.encode('punycode').replace(b'-', b'_')\n" +" return b'PyInit' + suffix" +msgstr "" + #: extending/building.rst:39 msgid "" "It is possible to export multiple modules from a single shared library by " diff --git a/extending/embedding.po b/extending/embedding.po index 1484f9a95..6c91190d5 100644 --- a/extending/embedding.po +++ b/extending/embedding.po @@ -6,7 +6,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-01 21:53+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: 2022-12-29 00:34-0500\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -118,6 +118,31 @@ msgstr "" "kalmadan bir Python betiği yürütmeyi amaçlamaktadır. Bu örnek olarak bir " "dosya üzerinde bazı işlemler gerçekleştirmek için kullanılabilir. ::" +#: extending/embedding.rst:56 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include \n" +"\n" +"int\n" +"main(int argc, char *argv[])\n" +"{\n" +" wchar_t *program = Py_DecodeLocale(argv[0], NULL);\n" +" if (program == NULL) {\n" +" fprintf(stderr, \"Fatal error: cannot decode argv[0]\\n\");\n" +" exit(1);\n" +" }\n" +" Py_SetProgramName(program); /* optional but recommended */\n" +" Py_Initialize();\n" +" PyRun_SimpleString(\"from time import time,ctime\\n\"\n" +" \"print('Today is', ctime(time()))\\n\");\n" +" if (Py_FinalizeEx() < 0) {\n" +" exit(120);\n" +" }\n" +" PyMem_RawFree(program);\n" +" return 0;\n" +"}" +msgstr "" + #: extending/embedding.rst:78 msgid "" "The :c:func:`Py_SetProgramName` function should be called before :c:func:" @@ -252,6 +277,82 @@ msgstr "" msgid "The code to run a function defined in a Python script is:" msgstr "Python betiğinde tanımlanan bir işlevi çalıştırma kodu:" +#: extending/embedding.rst:143 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include \n" +"\n" +"int\n" +"main(int argc, char *argv[])\n" +"{\n" +" PyObject *pName, *pModule, *pFunc;\n" +" PyObject *pArgs, *pValue;\n" +" int i;\n" +"\n" +" if (argc < 3) {\n" +" fprintf(stderr,\"Usage: call pythonfile funcname [args]\\n\");\n" +" return 1;\n" +" }\n" +"\n" +" Py_Initialize();\n" +" pName = PyUnicode_DecodeFSDefault(argv[1]);\n" +" /* Error checking of pName left out */\n" +"\n" +" pModule = PyImport_Import(pName);\n" +" Py_DECREF(pName);\n" +"\n" +" if (pModule != NULL) {\n" +" pFunc = PyObject_GetAttrString(pModule, argv[2]);\n" +" /* pFunc is a new reference */\n" +"\n" +" if (pFunc && PyCallable_Check(pFunc)) {\n" +" pArgs = PyTuple_New(argc - 3);\n" +" for (i = 0; i < argc - 3; ++i) {\n" +" pValue = PyLong_FromLong(atoi(argv[i + 3]));\n" +" if (!pValue) {\n" +" Py_DECREF(pArgs);\n" +" Py_DECREF(pModule);\n" +" fprintf(stderr, \"Cannot convert argument\\n\");\n" +" return 1;\n" +" }\n" +" /* pValue reference stolen here: */\n" +" PyTuple_SetItem(pArgs, i, pValue);\n" +" }\n" +" pValue = PyObject_CallObject(pFunc, pArgs);\n" +" Py_DECREF(pArgs);\n" +" if (pValue != NULL) {\n" +" printf(\"Result of call: %ld\\n\", PyLong_AsLong(pValue));\n" +" Py_DECREF(pValue);\n" +" }\n" +" else {\n" +" Py_DECREF(pFunc);\n" +" Py_DECREF(pModule);\n" +" PyErr_Print();\n" +" fprintf(stderr,\"Call failed\\n\");\n" +" return 1;\n" +" }\n" +" }\n" +" else {\n" +" if (PyErr_Occurred())\n" +" PyErr_Print();\n" +" fprintf(stderr, \"Cannot find function \\\"%s\\\"\\n\", " +"argv[2]);\n" +" }\n" +" Py_XDECREF(pFunc);\n" +" Py_DECREF(pModule);\n" +" }\n" +" else {\n" +" PyErr_Print();\n" +" fprintf(stderr, \"Failed to load \\\"%s\\\"\\n\", argv[1]);\n" +" return 1;\n" +" }\n" +" if (Py_FinalizeEx() < 0) {\n" +" return 120;\n" +" }\n" +" return 0;\n" +"}\n" +msgstr "" + #: extending/embedding.rst:146 msgid "" "This code loads a Python script using ``argv[1]``, and calls the function " @@ -267,10 +368,27 @@ msgstr "" "adlandıralım) ve onu aşağıdaki gibi bir Python betiğini çalıştırmak için " "kullanırsanız:" +#: extending/embedding.rst:152 +msgid "" +"def multiply(a,b):\n" +" print(\"Will compute\", a, \"times\", b)\n" +" c = 0\n" +" for i in range(0, a):\n" +" c = c + b\n" +" return c" +msgstr "" + #: extending/embedding.rst:161 msgid "then the result should be:" msgstr "o zaman sonuç olmalıdır:" +#: extending/embedding.rst:163 +msgid "" +"$ call multiply multiply 3 2\n" +"Will compute 3 times 2\n" +"Result of call: 6" +msgstr "" + #: extending/embedding.rst:169 msgid "" "Although the program is quite large for its functionality, most of the code " @@ -281,6 +399,14 @@ msgstr "" "Python ve C arasında veri dönüştürme ve hata raporlama içindir. Python'u " "gömmekle ilgili ilginç kısım şununla başlar ::" +#: extending/embedding.rst:173 +msgid "" +"Py_Initialize();\n" +"pName = PyUnicode_DecodeFSDefault(argv[1]);\n" +"/* Error checking of pName left out */\n" +"pModule = PyImport_Import(pName);" +msgstr "" + #: extending/embedding.rst:178 msgid "" "After initializing the interpreter, the script is loaded using :c:func:" @@ -293,6 +419,17 @@ msgstr "" "`PyUnicode_FromString` veri dönüştürme rutini kullanılarak oluşturulan bir " "Python dizesine ihtiyaç duyar. ::" +#: extending/embedding.rst:183 +msgid "" +"pFunc = PyObject_GetAttrString(pModule, argv[2]);\n" +"/* pFunc is a new reference */\n" +"\n" +"if (pFunc && PyCallable_Check(pFunc)) {\n" +" ...\n" +"}\n" +"Py_XDECREF(pFunc);" +msgstr "" + #: extending/embedding.rst:191 msgid "" "Once the script is loaded, the name we're looking for is retrieved using :c:" @@ -307,6 +444,10 @@ msgstr "" "Program daha sonra normal olarak bir dizi argüman oluşturarak devam eder. " "Python işlevine yapılan çağrı şu şekilde yapılır:" +#: extending/embedding.rst:197 +msgid "pValue = PyObject_CallObject(pFunc, pArgs);" +msgstr "" + #: extending/embedding.rst:199 msgid "" "Upon return of the function, ``pValue`` is either ``NULL`` or it contains a " @@ -341,6 +482,37 @@ msgstr "" "Python uzantısı yazacağınız gibi, Python'un bu rutinlere erişmesini sağlayan " "bir tutkal kodu yazın. Örneğin::" +#: extending/embedding.rst:218 +msgid "" +"static int numargs=0;\n" +"\n" +"/* Return the number of arguments of the application command line */\n" +"static PyObject*\n" +"emb_numargs(PyObject *self, PyObject *args)\n" +"{\n" +" if(!PyArg_ParseTuple(args, \":numargs\"))\n" +" return NULL;\n" +" return PyLong_FromLong(numargs);\n" +"}\n" +"\n" +"static PyMethodDef EmbMethods[] = {\n" +" {\"numargs\", emb_numargs, METH_VARARGS,\n" +" \"Return the number of arguments received by the process.\"},\n" +" {NULL, NULL, 0, NULL}\n" +"};\n" +"\n" +"static PyModuleDef EmbModule = {\n" +" PyModuleDef_HEAD_INIT, \"emb\", NULL, -1, EmbMethods,\n" +" NULL, NULL, NULL, NULL\n" +"};\n" +"\n" +"static PyObject*\n" +"PyInit_emb(void)\n" +"{\n" +" return PyModule_Create(&EmbModule);\n" +"}" +msgstr "" + #: extending/embedding.rst:246 msgid "" "Insert the above code just above the :c:func:`main` function. Also, insert " @@ -349,6 +521,12 @@ msgstr "" "Yukarıdaki kodu :c:func:`main` fonksiyonunun hemen üstüne ekleyin. Ayrıca, :" "c:func:`Py_Initialize`: çağrısından önce aşağıdaki iki ifadeyi ekleyin::" +#: extending/embedding.rst:249 +msgid "" +"numargs = argc;\n" +"PyImport_AppendInittab(\"emb\", &PyInit_emb);" +msgstr "" + #: extending/embedding.rst:252 #, fuzzy msgid "" @@ -360,6 +538,12 @@ msgstr "" "fonksiyonunu gömülü Python yorumlayıcısı için erişilebilir kılar. Bu " "uzantılarla Python betiği şekilde gibi şeyler yapabilir" +#: extending/embedding.rst:256 +msgid "" +"import emb\n" +"print(\"Number of arguments\", emb.numargs())" +msgstr "" + #: extending/embedding.rst:261 msgid "" "In a real application, the methods will expose an API of the application to " @@ -423,6 +607,13 @@ msgstr "" "``pythonX.Y-config --cflags`` derleme sırasında size önerilen bayrakları " "verecektir:" +#: extending/embedding.rst:299 +msgid "" +"$ /opt/bin/python3.11-config --cflags\n" +"-I/opt/include/python3.11 -I/opt/include/python3.11 -Wsign-compare -DNDEBUG " +"-g -fwrapv -O3 -Wall" +msgstr "" + #: extending/embedding.rst:304 msgid "" "``pythonX.Y-config --ldflags --embed`` will give you the recommended flags " @@ -431,6 +622,13 @@ msgstr "" "``pythonX.Y-config --ldflags --embed``, bağlantı kurarken size önerilen " "bayrakları verecektir:" +#: extending/embedding.rst:307 +msgid "" +"$ /opt/bin/python3.11-config --ldflags --embed\n" +"-L/opt/lib/python3.11/config-3.11-x86_64-linux-gnu -L/opt/lib -lpython3.11 -" +"lpthread -ldl -lutil -lm" +msgstr "" + #: extending/embedding.rst:313 msgid "" "To avoid confusion between several Python installations (and especially " @@ -461,3 +659,12 @@ msgstr "" "seçeneklerini bağlamayı inceleyin. Bu durumda, :mod:`sysconfig` modülü, " "birleştirmek isteyeceğiniz konfigürasyon değerlerini programlı olarak " "çıkarmak için kullanışlı bir araçtır. Örneğin:" + +#: extending/embedding.rst:327 +msgid "" +">>> import sysconfig\n" +">>> sysconfig.get_config_var('LIBS')\n" +"'-lpthread -ldl -lutil'\n" +">>> sysconfig.get_config_var('LINKFORSHARED')\n" +"'-Xlinker -export-dynamic'" +msgstr "" diff --git a/extending/extending.po b/extending/extending.po index 0f86807e0..00f71bb50 100644 --- a/extending/extending.po +++ b/extending/extending.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -68,6 +68,12 @@ msgid "" "this function to be callable from Python as follows:" msgstr "" +#: extending/extending.rst:48 +msgid "" +">>> import spam\n" +">>> status = spam.system(\"ls -l\")" +msgstr "" + #: extending/extending.rst:53 msgid "" "Begin by creating a file :file:`spammodule.c`. (Historically, if a module " @@ -80,6 +86,12 @@ msgstr "" msgid "The first two lines of our file can be::" msgstr "" +#: extending/extending.rst:60 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include " +msgstr "" + #: extending/extending.rst:63 msgid "" "which pulls in the Python API (you can add a comment describing the purpose " @@ -117,6 +129,21 @@ msgid "" "(we'll see shortly how it ends up being called)::" msgstr "" +#: extending/extending.rst:87 +msgid "" +"static PyObject *\n" +"spam_system(PyObject *self, PyObject *args)\n" +"{\n" +" const char *command;\n" +" int sts;\n" +"\n" +" if (!PyArg_ParseTuple(args, \"s\", &command))\n" +" return NULL;\n" +" sts = system(command);\n" +" return PyLong_FromLong(sts);\n" +"}" +msgstr "" + #: extending/extending.rst:99 msgid "" "There is a straightforward translation from the argument list in Python (for " @@ -277,12 +304,40 @@ msgid "" "you usually declare a static object variable at the beginning of your file::" msgstr "" +#: extending/extending.rst:207 +msgid "static PyObject *SpamError;" +msgstr "" + #: extending/extending.rst:209 msgid "" "and initialize it in your module's initialization function (:c:func:`!" "PyInit_spam`) with an exception object::" msgstr "" +#: extending/extending.rst:212 +msgid "" +"PyMODINIT_FUNC\n" +"PyInit_spam(void)\n" +"{\n" +" PyObject *m;\n" +"\n" +" m = PyModule_Create(&spammodule);\n" +" if (m == NULL)\n" +" return NULL;\n" +"\n" +" SpamError = PyErr_NewException(\"spam.error\", NULL, NULL);\n" +" Py_XINCREF(SpamError);\n" +" if (PyModule_AddObject(m, \"error\", SpamError) < 0) {\n" +" Py_XDECREF(SpamError);\n" +" Py_CLEAR(SpamError);\n" +" Py_DECREF(m);\n" +" return NULL;\n" +" }\n" +"\n" +" return m;\n" +"}" +msgstr "" + #: extending/extending.rst:233 msgid "" "Note that the Python name for the exception object is :exc:`!spam.error`. " @@ -314,6 +369,25 @@ msgid "" "using a call to :c:func:`PyErr_SetString` as shown below::" msgstr "" +#: extending/extending.rst:251 +msgid "" +"static PyObject *\n" +"spam_system(PyObject *self, PyObject *args)\n" +"{\n" +" const char *command;\n" +" int sts;\n" +"\n" +" if (!PyArg_ParseTuple(args, \"s\", &command))\n" +" return NULL;\n" +" sts = system(command);\n" +" if (sts < 0) {\n" +" PyErr_SetString(SpamError, \"System command failed\");\n" +" return NULL;\n" +" }\n" +" return PyLong_FromLong(sts);\n" +"}" +msgstr "" + #: extending/extending.rst:271 msgid "Back to the Example" msgstr "" @@ -324,6 +398,12 @@ msgid "" "this statement::" msgstr "" +#: extending/extending.rst:276 +msgid "" +"if (!PyArg_ParseTuple(args, \"s\", &command))\n" +" return NULL;" +msgstr "" + #: extending/extending.rst:279 msgid "" "It returns ``NULL`` (the error indicator for functions returning object " @@ -341,6 +421,10 @@ msgid "" "it the string we just got from :c:func:`PyArg_ParseTuple`::" msgstr "" +#: extending/extending.rst:290 +msgid "sts = system(command);" +msgstr "" + #: extending/extending.rst:292 msgid "" "Our :func:`!spam.system` function must return the value of :c:data:`!sts` as " @@ -348,6 +432,10 @@ msgid "" "`PyLong_FromLong`. ::" msgstr "" +#: extending/extending.rst:295 +msgid "return PyLong_FromLong(sts);" +msgstr "" + #: extending/extending.rst:297 msgid "" "In this case, it will return an integer object. (Yes, even integers are " @@ -362,6 +450,12 @@ msgid "" "macro:`Py_RETURN_NONE` macro)::" msgstr "" +#: extending/extending.rst:305 +msgid "" +"Py_INCREF(Py_None);\n" +"return Py_None;" +msgstr "" + #: extending/extending.rst:308 msgid "" ":c:data:`Py_None` is the C name for the special Python object ``None``. It " @@ -379,6 +473,17 @@ msgid "" "programs. First, we need to list its name and address in a \"method table\"::" msgstr "" +#: extending/extending.rst:321 +msgid "" +"static PyMethodDef SpamMethods[] = {\n" +" ...\n" +" {\"system\", spam_system, METH_VARARGS,\n" +" \"Execute a shell command.\"},\n" +" ...\n" +" {NULL, NULL, 0, NULL} /* Sentinel */\n" +"};" +msgstr "" + #: extending/extending.rst:329 msgid "" "Note the third entry (``METH_VARARGS``). This is a flag telling the " @@ -409,6 +514,18 @@ msgid "" "The method table must be referenced in the module definition structure::" msgstr "" +#: extending/extending.rst:346 +msgid "" +"static struct PyModuleDef spammodule = {\n" +" PyModuleDef_HEAD_INIT,\n" +" \"spam\", /* name of module */\n" +" spam_doc, /* module documentation, may be NULL */\n" +" -1, /* size of per-interpreter state of the module,\n" +" or -1 if the module keeps state in global variables. */\n" +" SpamMethods\n" +"};" +msgstr "" + #: extending/extending.rst:355 msgid "" "This structure, in turn, must be passed to the interpreter in the module's " @@ -417,6 +534,15 @@ msgid "" "only non-\\ ``static`` item defined in the module file::" msgstr "" +#: extending/extending.rst:360 +msgid "" +"PyMODINIT_FUNC\n" +"PyInit_spam(void)\n" +"{\n" +" return PyModule_Create(&spammodule);\n" +"}" +msgstr "" + #: extending/extending.rst:366 msgid "" "Note that :c:macro:`PyMODINIT_FUNC` declares the function as ``PyObject *`` " @@ -446,6 +572,47 @@ msgid "" "`PyImport_AppendInittab`, optionally followed by an import of the module::" msgstr "" +#: extending/extending.rst:386 +msgid "" +"int\n" +"main(int argc, char *argv[])\n" +"{\n" +" wchar_t *program = Py_DecodeLocale(argv[0], NULL);\n" +" if (program == NULL) {\n" +" fprintf(stderr, \"Fatal error: cannot decode argv[0]\\n\");\n" +" exit(1);\n" +" }\n" +"\n" +" /* Add a built-in module, before Py_Initialize */\n" +" if (PyImport_AppendInittab(\"spam\", PyInit_spam) == -1) {\n" +" fprintf(stderr, \"Error: could not extend in-built modules " +"table\\n\");\n" +" exit(1);\n" +" }\n" +"\n" +" /* Pass argv[0] to the Python interpreter */\n" +" Py_SetProgramName(program);\n" +"\n" +" /* Initialize the Python interpreter. Required.\n" +" If this step fails, it will be a fatal error. */\n" +" Py_Initialize();\n" +"\n" +" /* Optionally import the module; alternatively,\n" +" import can be deferred until the embedded script\n" +" imports it. */\n" +" PyObject *pmodule = PyImport_ImportModule(\"spam\");\n" +" if (!pmodule) {\n" +" PyErr_Print();\n" +" fprintf(stderr, \"Error: could not import module 'spam'\\n\");\n" +" }\n" +"\n" +" ...\n" +"\n" +" PyMem_RawFree(program);\n" +" return 0;\n" +"}" +msgstr "" + #: extending/extending.rst:425 msgid "" "Removing entries from ``sys.modules`` or importing compiled modules into " @@ -494,6 +661,10 @@ msgid "" "line to the file :file:`Modules/Setup.local` describing your file:" msgstr "" +#: extending/extending.rst:462 +msgid "spam spammodule.o" +msgstr "" + #: extending/extending.rst:466 msgid "" "and rebuild the interpreter by running :program:`make` in the toplevel " @@ -509,6 +680,10 @@ msgid "" "listed on the line in the configuration file as well, for instance:" msgstr "" +#: extending/extending.rst:475 +msgid "spam spammodule.o -lX11" +msgstr "" + #: extending/extending.rst:483 msgid "Calling Python Functions from C" msgstr "" @@ -543,6 +718,33 @@ msgid "" "function might be part of a module definition::" msgstr "" +#: extending/extending.rst:506 +msgid "" +"static PyObject *my_callback = NULL;\n" +"\n" +"static PyObject *\n" +"my_set_callback(PyObject *dummy, PyObject *args)\n" +"{\n" +" PyObject *result = NULL;\n" +" PyObject *temp;\n" +"\n" +" if (PyArg_ParseTuple(args, \"O:set_callback\", &temp)) {\n" +" if (!PyCallable_Check(temp)) {\n" +" PyErr_SetString(PyExc_TypeError, \"parameter must be " +"callable\");\n" +" return NULL;\n" +" }\n" +" Py_XINCREF(temp); /* Add a reference to new callback */\n" +" Py_XDECREF(my_callback); /* Dispose of previous callback */\n" +" my_callback = temp; /* Remember new callback */\n" +" /* Boilerplate to return \"None\" */\n" +" Py_INCREF(Py_None);\n" +" result = Py_None;\n" +" }\n" +" return result;\n" +"}" +msgstr "" + #: extending/extending.rst:529 msgid "" "This function must be registered with the interpreter using the :c:macro:" @@ -571,6 +773,20 @@ msgid "" "or more format codes between parentheses. For example::" msgstr "" +#: extending/extending.rst:550 +msgid "" +"int arg;\n" +"PyObject *arglist;\n" +"PyObject *result;\n" +"...\n" +"arg = 123;\n" +"...\n" +"/* Time to call the callback */\n" +"arglist = Py_BuildValue(\"(i)\", arg);\n" +"result = PyObject_CallObject(my_callback, arglist);\n" +"Py_DECREF(arglist);" +msgstr "" + #: extending/extending.rst:561 msgid "" ":c:func:`PyObject_CallObject` returns a Python object pointer: this is the " @@ -600,6 +816,14 @@ msgid "" "should be cleared by calling :c:func:`PyErr_Clear`. For example::" msgstr "" +#: extending/extending.rst:582 +msgid "" +"if (result == NULL)\n" +" return NULL; /* Pass error back */\n" +"...use result...\n" +"Py_DECREF(result);" +msgstr "" + #: extending/extending.rst:587 msgid "" "Depending on the desired interface to the Python callback function, you may " @@ -612,6 +836,19 @@ msgid "" "you want to pass an integral event code, you might use the following code::" msgstr "" +#: extending/extending.rst:596 +msgid "" +"PyObject *arglist;\n" +"...\n" +"arglist = Py_BuildValue(\"(l)\", eventcode);\n" +"result = PyObject_CallObject(my_callback, arglist);\n" +"Py_DECREF(arglist);\n" +"if (result == NULL)\n" +" return NULL; /* Pass error back */\n" +"/* Here maybe use the result */\n" +"Py_DECREF(result);" +msgstr "" + #: extending/extending.rst:606 msgid "" "Note the placement of ``Py_DECREF(arglist)`` immediately after the call, " @@ -627,6 +864,19 @@ msgid "" "above example, we use :c:func:`Py_BuildValue` to construct the dictionary. ::" msgstr "" +#: extending/extending.rst:614 +msgid "" +"PyObject *dict;\n" +"...\n" +"dict = Py_BuildValue(\"{s:i}\", \"name\", val);\n" +"result = PyObject_Call(my_callback, NULL, dict);\n" +"Py_DECREF(dict);\n" +"if (result == NULL)\n" +" return NULL; /* Pass error back */\n" +"/* Here maybe use the result */\n" +"Py_DECREF(result);" +msgstr "" + #: extending/extending.rst:628 msgid "Extracting Parameters in Extension Functions" msgstr "" @@ -635,6 +885,10 @@ msgstr "" msgid "The :c:func:`PyArg_ParseTuple` function is declared as follows::" msgstr "" +#: extending/extending.rst:634 +msgid "int PyArg_ParseTuple(PyObject *arg, const char *format, ...);" +msgstr "" + #: extending/extending.rst:636 msgid "" "The *arg* argument must be a tuple object containing an argument list passed " @@ -662,6 +916,81 @@ msgstr "" msgid "Some example calls::" msgstr "" +#: extending/extending.rst:652 +msgid "" +"#define PY_SSIZE_T_CLEAN /* Make \"s#\" use Py_ssize_t rather than int. */\n" +"#include " +msgstr "" + +#: extending/extending.rst:657 +msgid "" +"int ok;\n" +"int i, j;\n" +"long k, l;\n" +"const char *s;\n" +"Py_ssize_t size;\n" +"\n" +"ok = PyArg_ParseTuple(args, \"\"); /* No arguments */\n" +" /* Python call: f() */" +msgstr "" + +#: extending/extending.rst:668 +msgid "" +"ok = PyArg_ParseTuple(args, \"s\", &s); /* A string */\n" +" /* Possible Python call: f('whoops!') */" +msgstr "" + +#: extending/extending.rst:673 +msgid "" +"ok = PyArg_ParseTuple(args, \"lls\", &k, &l, &s); /* Two longs and a string " +"*/\n" +" /* Possible Python call: f(1, 2, 'three') */" +msgstr "" + +#: extending/extending.rst:678 +msgid "" +"ok = PyArg_ParseTuple(args, \"(ii)s#\", &i, &j, &s, &size);\n" +" /* A pair of ints and a string, whose size is also returned */\n" +" /* Possible Python call: f((1, 2), 'three') */" +msgstr "" + +#: extending/extending.rst:684 +msgid "" +"{\n" +" const char *file;\n" +" const char *mode = \"r\";\n" +" int bufsize = 0;\n" +" ok = PyArg_ParseTuple(args, \"s|si\", &file, &mode, &bufsize);\n" +" /* A string, and optionally another string and an integer */\n" +" /* Possible Python calls:\n" +" f('spam')\n" +" f('spam', 'w')\n" +" f('spam', 'wb', 100000) */\n" +"}" +msgstr "" + +#: extending/extending.rst:698 +msgid "" +"{\n" +" int left, top, right, bottom, h, v;\n" +" ok = PyArg_ParseTuple(args, \"((ii)(ii))(ii)\",\n" +" &left, &top, &right, &bottom, &h, &v);\n" +" /* A rectangle and a point */\n" +" /* Possible Python call:\n" +" f(((0, 0), (400, 300)), (10, 10)) */\n" +"}" +msgstr "" + +#: extending/extending.rst:709 +msgid "" +"{\n" +" Py_complex c;\n" +" ok = PyArg_ParseTuple(args, \"D:myfunction\", &c);\n" +" /* a complex, also providing a function name for errors */\n" +" /* Possible Python call: myfunction(1+2j) */\n" +"}" +msgstr "" + #: extending/extending.rst:720 msgid "Keyword Parameters for Extension Functions" msgstr "" @@ -671,6 +1000,12 @@ msgid "" "The :c:func:`PyArg_ParseTupleAndKeywords` function is declared as follows::" msgstr "" +#: extending/extending.rst:726 +msgid "" +"int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,\n" +" const char *format, char *kwlist[], ...);" +msgstr "" + #: extending/extending.rst:729 msgid "" "The *arg* and *format* parameters are identical to those of the :c:func:" @@ -696,6 +1031,60 @@ msgid "" "Philbrick (philbrick@hks.com)::" msgstr "" +#: extending/extending.rst:748 +msgid "" +"#define PY_SSIZE_T_CLEAN /* Make \"s#\" use Py_ssize_t rather than int. */\n" +"#include \n" +"\n" +"static PyObject *\n" +"keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds)\n" +"{\n" +" int voltage;\n" +" const char *state = \"a stiff\";\n" +" const char *action = \"voom\";\n" +" const char *type = \"Norwegian Blue\";\n" +"\n" +" static char *kwlist[] = {\"voltage\", \"state\", \"action\", \"type\", " +"NULL};\n" +"\n" +" if (!PyArg_ParseTupleAndKeywords(args, keywds, \"i|sss\", kwlist,\n" +" &voltage, &state, &action, &type))\n" +" return NULL;\n" +"\n" +" printf(\"-- This parrot wouldn't %s if you put %i Volts through it." +"\\n\",\n" +" action, voltage);\n" +" printf(\"-- Lovely plumage, the %s -- It's %s!\\n\", type, state);\n" +"\n" +" Py_RETURN_NONE;\n" +"}\n" +"\n" +"static PyMethodDef keywdarg_methods[] = {\n" +" /* The cast of the function is necessary since PyCFunction values\n" +" * only take two PyObject* parameters, and keywdarg_parrot() takes\n" +" * three.\n" +" */\n" +" {\"parrot\", (PyCFunction)(void(*)(void))keywdarg_parrot, METH_VARARGS | " +"METH_KEYWORDS,\n" +" \"Print a lovely skit to standard output.\"},\n" +" {NULL, NULL, 0, NULL} /* sentinel */\n" +"};\n" +"\n" +"static struct PyModuleDef keywdargmodule = {\n" +" PyModuleDef_HEAD_INIT,\n" +" \"keywdarg\",\n" +" NULL,\n" +" -1,\n" +" keywdarg_methods\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_keywdarg(void)\n" +"{\n" +" return PyModule_Create(&keywdargmodule);\n" +"}" +msgstr "" + #: extending/extending.rst:800 msgid "Building Arbitrary Values" msgstr "" @@ -706,6 +1095,10 @@ msgid "" "declared as follows::" msgstr "" +#: extending/extending.rst:805 +msgid "PyObject *Py_BuildValue(const char *format, ...);" +msgstr "" + #: extending/extending.rst:807 msgid "" "It recognizes a set of format units similar to the ones recognized by :c:" @@ -731,6 +1124,27 @@ msgid "" "Examples (to the left the call, to the right the resulting Python value):" msgstr "" +#: extending/extending.rst:822 +msgid "" +"Py_BuildValue(\"\") None\n" +"Py_BuildValue(\"i\", 123) 123\n" +"Py_BuildValue(\"iii\", 123, 456, 789) (123, 456, 789)\n" +"Py_BuildValue(\"s\", \"hello\") 'hello'\n" +"Py_BuildValue(\"y\", \"hello\") b'hello'\n" +"Py_BuildValue(\"ss\", \"hello\", \"world\") ('hello', 'world')\n" +"Py_BuildValue(\"s#\", \"hello\", 4) 'hell'\n" +"Py_BuildValue(\"y#\", \"hello\", 4) b'hell'\n" +"Py_BuildValue(\"()\") ()\n" +"Py_BuildValue(\"(i)\", 123) (123,)\n" +"Py_BuildValue(\"(ii)\", 123, 456) (123, 456)\n" +"Py_BuildValue(\"(i,i)\", 123, 456) (123, 456)\n" +"Py_BuildValue(\"[i,i]\", 123, 456) [123, 456]\n" +"Py_BuildValue(\"{s:i,s:i}\",\n" +" \"abc\", 123, \"def\", 456) {'abc': 123, 'def': 456}\n" +"Py_BuildValue(\"((ii)(ii)) (ii)\",\n" +" 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6))" +msgstr "" + #: extending/extending.rst:846 msgid "Reference Counts" msgstr "" @@ -968,6 +1382,18 @@ msgid "" "instance::" msgstr "" +#: extending/extending.rst:1016 +msgid "" +"void\n" +"bug(PyObject *list)\n" +"{\n" +" PyObject *item = PyList_GetItem(list, 0);\n" +"\n" +" PyList_SetItem(list, 1, PyLong_FromLong(0L));\n" +" PyObject_Print(item, stdout, 0); /* BUG! */\n" +"}" +msgstr "" + #: extending/extending.rst:1025 msgid "" "This function first borrows a reference to ``list[0]``, then replaces " @@ -1002,6 +1428,20 @@ msgid "" "increment the reference count. The correct version of the function reads::" msgstr "" +#: extending/extending.rst:1047 +msgid "" +"void\n" +"no_bug(PyObject *list)\n" +"{\n" +" PyObject *item = PyList_GetItem(list, 0);\n" +"\n" +" Py_INCREF(item);\n" +" PyList_SetItem(list, 1, PyLong_FromLong(0L));\n" +" PyObject_Print(item, stdout, 0);\n" +" Py_DECREF(item);\n" +"}" +msgstr "" + #: extending/extending.rst:1058 msgid "" "This is a true story. An older version of Python contained variants of this " @@ -1022,6 +1462,19 @@ msgid "" "previous one::" msgstr "" +#: extending/extending.rst:1071 +msgid "" +"void\n" +"bug(PyObject *list)\n" +"{\n" +" PyObject *item = PyList_GetItem(list, 0);\n" +" Py_BEGIN_ALLOW_THREADS\n" +" ...some blocking I/O call...\n" +" Py_END_ALLOW_THREADS\n" +" PyObject_Print(item, stdout, 0); /* BUG! */\n" +"}" +msgstr "" + #: extending/extending.rst:1085 msgid "NULL Pointers" msgstr "" @@ -1170,6 +1623,10 @@ msgid "" "following this convention::" msgstr "" +#: extending/extending.rst:1196 +msgid "modulename.attributename" +msgstr "" + #: extending/extending.rst:1198 msgid "" "The convenience function :c:func:`PyCapsule_Import` makes it easy to load a " @@ -1206,18 +1663,52 @@ msgid "" "``static`` like everything else::" msgstr "" +#: extending/extending.rst:1221 +msgid "" +"static int\n" +"PySpam_System(const char *command)\n" +"{\n" +" return system(command);\n" +"}" +msgstr "" + #: extending/extending.rst:1227 msgid "The function :c:func:`!spam_system` is modified in a trivial way::" msgstr "" +#: extending/extending.rst:1229 +msgid "" +"static PyObject *\n" +"spam_system(PyObject *self, PyObject *args)\n" +"{\n" +" const char *command;\n" +" int sts;\n" +"\n" +" if (!PyArg_ParseTuple(args, \"s\", &command))\n" +" return NULL;\n" +" sts = PySpam_System(command);\n" +" return PyLong_FromLong(sts);\n" +"}" +msgstr "" + #: extending/extending.rst:1241 msgid "In the beginning of the module, right after the line ::" msgstr "" +#: extending/extending.rst:1243 +msgid "#include " +msgstr "" + #: extending/extending.rst:1245 msgid "two more lines must be added::" msgstr "" +#: extending/extending.rst:1247 +msgid "" +"#define SPAM_MODULE\n" +"#include \"spammodule.h\"" +msgstr "" + #: extending/extending.rst:1250 msgid "" "The ``#define`` is used to tell the header file that it is being included in " @@ -1226,6 +1717,36 @@ msgid "" "array::" msgstr "" +#: extending/extending.rst:1254 +msgid "" +"PyMODINIT_FUNC\n" +"PyInit_spam(void)\n" +"{\n" +" PyObject *m;\n" +" static void *PySpam_API[PySpam_API_pointers];\n" +" PyObject *c_api_object;\n" +"\n" +" m = PyModule_Create(&spammodule);\n" +" if (m == NULL)\n" +" return NULL;\n" +"\n" +" /* Initialize the C API pointer array */\n" +" PySpam_API[PySpam_System_NUM] = (void *)PySpam_System;\n" +"\n" +" /* Create a Capsule containing the API pointer array's address */\n" +" c_api_object = PyCapsule_New((void *)PySpam_API, \"spam._C_API\", " +"NULL);\n" +"\n" +" if (PyModule_AddObject(m, \"_C_API\", c_api_object) < 0) {\n" +" Py_XDECREF(c_api_object);\n" +" Py_DECREF(m);\n" +" return NULL;\n" +" }\n" +"\n" +" return m;\n" +"}" +msgstr "" + #: extending/extending.rst:1280 msgid "" "Note that ``PySpam_API`` is declared ``static``; otherwise the pointer array " @@ -1238,6 +1759,58 @@ msgid "" "like this::" msgstr "" +#: extending/extending.rst:1286 +msgid "" +"#ifndef Py_SPAMMODULE_H\n" +"#define Py_SPAMMODULE_H\n" +"#ifdef __cplusplus\n" +"extern \"C\" {\n" +"#endif\n" +"\n" +"/* Header file for spammodule */\n" +"\n" +"/* C API functions */\n" +"#define PySpam_System_NUM 0\n" +"#define PySpam_System_RETURN int\n" +"#define PySpam_System_PROTO (const char *command)\n" +"\n" +"/* Total number of C API pointers */\n" +"#define PySpam_API_pointers 1\n" +"\n" +"\n" +"#ifdef SPAM_MODULE\n" +"/* This section is used when compiling spammodule.c */\n" +"\n" +"static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;\n" +"\n" +"#else\n" +"/* This section is used in modules that use spammodule's API */\n" +"\n" +"static void **PySpam_API;\n" +"\n" +"#define PySpam_System \\\n" +" (*(PySpam_System_RETURN (*)PySpam_System_PROTO) " +"PySpam_API[PySpam_System_NUM])\n" +"\n" +"/* Return -1 on error, 0 on success.\n" +" * PyCapsule_Import will set an exception if there's an error.\n" +" */\n" +"static int\n" +"import_spam(void)\n" +"{\n" +" PySpam_API = (void **)PyCapsule_Import(\"spam._C_API\", 0);\n" +" return (PySpam_API != NULL) ? 0 : -1;\n" +"}\n" +"\n" +"#endif\n" +"\n" +"#ifdef __cplusplus\n" +"}\n" +"#endif\n" +"\n" +"#endif /* !defined(Py_SPAMMODULE_H) */" +msgstr "" + #: extending/extending.rst:1334 msgid "" "All that a client module must do in order to have access to the function :c:" @@ -1245,6 +1818,23 @@ msgid "" "import_spam` in its initialization function::" msgstr "" +#: extending/extending.rst:1338 +msgid "" +"PyMODINIT_FUNC\n" +"PyInit_client(void)\n" +"{\n" +" PyObject *m;\n" +"\n" +" m = PyModule_Create(&clientmodule);\n" +" if (m == NULL)\n" +" return NULL;\n" +" if (import_spam() < 0)\n" +" return NULL;\n" +" /* additional initialization can happen here */\n" +" return m;\n" +"}" +msgstr "" + #: extending/extending.rst:1352 msgid "" "The main disadvantage of this approach is that the file :file:`spammodule.h` " diff --git a/extending/newtypes.po b/extending/newtypes.po index d01d12d24..8d88ed95b 100644 --- a/extending/newtypes.po +++ b/extending/newtypes.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -32,6 +32,96 @@ msgid "" "in :ref:`debug builds ` omitted:" msgstr "" +#: extending/newtypes.rst:17 +msgid "" +"typedef struct _typeobject {\n" +" PyObject_VAR_HEAD\n" +" const char *tp_name; /* For printing, in format \".\" */\n" +" Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */\n" +"\n" +" /* Methods to implement standard operations */\n" +"\n" +" destructor tp_dealloc;\n" +" Py_ssize_t tp_vectorcall_offset;\n" +" getattrfunc tp_getattr;\n" +" setattrfunc tp_setattr;\n" +" PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)\n" +" or tp_reserved (Python 3) */\n" +" reprfunc tp_repr;\n" +"\n" +" /* Method suites for standard classes */\n" +"\n" +" PyNumberMethods *tp_as_number;\n" +" PySequenceMethods *tp_as_sequence;\n" +" PyMappingMethods *tp_as_mapping;\n" +"\n" +" /* More standard operations (here for binary compatibility) */\n" +"\n" +" hashfunc tp_hash;\n" +" ternaryfunc tp_call;\n" +" reprfunc tp_str;\n" +" getattrofunc tp_getattro;\n" +" setattrofunc tp_setattro;\n" +"\n" +" /* Functions to access object as input/output buffer */\n" +" PyBufferProcs *tp_as_buffer;\n" +"\n" +" /* Flags to define presence of optional/expanded features */\n" +" unsigned long tp_flags;\n" +"\n" +" const char *tp_doc; /* Documentation string */\n" +"\n" +" /* Assigned meaning in release 2.0 */\n" +" /* call function for all accessible objects */\n" +" traverseproc tp_traverse;\n" +"\n" +" /* delete references to contained objects */\n" +" inquiry tp_clear;\n" +"\n" +" /* Assigned meaning in release 2.1 */\n" +" /* rich comparisons */\n" +" richcmpfunc tp_richcompare;\n" +"\n" +" /* weak reference enabler */\n" +" Py_ssize_t tp_weaklistoffset;\n" +"\n" +" /* Iterators */\n" +" getiterfunc tp_iter;\n" +" iternextfunc tp_iternext;\n" +"\n" +" /* Attribute descriptor and subclassing stuff */\n" +" struct PyMethodDef *tp_methods;\n" +" struct PyMemberDef *tp_members;\n" +" struct PyGetSetDef *tp_getset;\n" +" // Strong reference on a heap type, borrowed reference on a static type\n" +" struct _typeobject *tp_base;\n" +" PyObject *tp_dict;\n" +" descrgetfunc tp_descr_get;\n" +" descrsetfunc tp_descr_set;\n" +" Py_ssize_t tp_dictoffset;\n" +" initproc tp_init;\n" +" allocfunc tp_alloc;\n" +" newfunc tp_new;\n" +" freefunc tp_free; /* Low-level free-memory routine */\n" +" inquiry tp_is_gc; /* For PyObject_IS_GC */\n" +" PyObject *tp_bases;\n" +" PyObject *tp_mro; /* method resolution order */\n" +" PyObject *tp_cache;\n" +" PyObject *tp_subclasses;\n" +" PyObject *tp_weaklist;\n" +" destructor tp_del;\n" +"\n" +" /* Type attribute cache version tag. Added in version 2.6 */\n" +" unsigned int tp_version_tag;\n" +"\n" +" destructor tp_finalize;\n" +" vectorcallfunc tp_vectorcall;\n" +"\n" +" /* bitset of which type-watchers care about this type */\n" +" unsigned char tp_watched;\n" +"} PyTypeObject;\n" +msgstr "" + #: extending/newtypes.rst:20 msgid "" "Now that's a *lot* of methods. Don't worry too much though -- if you have a " @@ -49,6 +139,10 @@ msgid "" "new type. ::" msgstr "" +#: extending/newtypes.rst:31 +msgid "const char *tp_name; /* For printing */" +msgstr "" + #: extending/newtypes.rst:33 msgid "" "The name of the type -- as mentioned in the previous chapter, this will " @@ -56,6 +150,10 @@ msgid "" "choose something that will be helpful in such a situation! ::" msgstr "" +#: extending/newtypes.rst:37 +msgid "Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */" +msgstr "" + #: extending/newtypes.rst:39 msgid "" "These fields tell the runtime how much memory to allocate when new objects " @@ -65,6 +163,10 @@ msgid "" "later. ::" msgstr "" +#: extending/newtypes.rst:44 +msgid "const char *tp_doc;" +msgstr "" + #: extending/newtypes.rst:46 msgid "" "Here you can put a string (or its address) that you want returned when the " @@ -81,6 +183,10 @@ msgstr "" msgid "Finalization and De-allocation" msgstr "" +#: extending/newtypes.rst:64 +msgid "destructor tp_dealloc;" +msgstr "" + #: extending/newtypes.rst:66 msgid "" "This function is called when the reference count of the instance of your " @@ -90,12 +196,34 @@ msgid "" "of this function::" msgstr "" +#: extending/newtypes.rst:72 +msgid "" +"static void\n" +"newdatatype_dealloc(newdatatypeobject *obj)\n" +"{\n" +" free(obj->obj_UnderlyingDatatypePtr);\n" +" Py_TYPE(obj)->tp_free((PyObject *)obj);\n" +"}" +msgstr "" + #: extending/newtypes.rst:79 msgid "" "If your type supports garbage collection, the destructor should call :c:func:" "`PyObject_GC_UnTrack` before clearing any member fields::" msgstr "" +#: extending/newtypes.rst:82 +msgid "" +"static void\n" +"newdatatype_dealloc(newdatatypeobject *obj)\n" +"{\n" +" PyObject_GC_UnTrack(obj);\n" +" Py_CLEAR(obj->other_obj);\n" +" ...\n" +" Py_TYPE(obj)->tp_free((PyObject *)obj);\n" +"}" +msgstr "" + #: extending/newtypes.rst:95 msgid "" "One important requirement of the deallocator function is that it leaves any " @@ -111,6 +239,35 @@ msgid "" "c:func:`PyErr_Fetch` and :c:func:`PyErr_Restore` functions::" msgstr "" +#: extending/newtypes.rst:107 +msgid "" +"static void\n" +"my_dealloc(PyObject *obj)\n" +"{\n" +" MyObject *self = (MyObject *) obj;\n" +" PyObject *cbresult;\n" +"\n" +" if (self->my_callback != NULL) {\n" +" PyObject *err_type, *err_value, *err_traceback;\n" +"\n" +" /* This saves the current exception state */\n" +" PyErr_Fetch(&err_type, &err_value, &err_traceback);\n" +"\n" +" cbresult = PyObject_CallNoArgs(self->my_callback);\n" +" if (cbresult == NULL)\n" +" PyErr_WriteUnraisable(self->my_callback);\n" +" else\n" +" Py_DECREF(cbresult);\n" +"\n" +" /* This restores the saved exception state */\n" +" PyErr_Restore(err_type, err_value, err_traceback);\n" +"\n" +" Py_DECREF(self->my_callback);\n" +" }\n" +" Py_TYPE(obj)->tp_free((PyObject*)self);\n" +"}" +msgstr "" + #: extending/newtypes.rst:134 msgid "" "There are limitations to what you can safely do in a deallocator function. " @@ -146,6 +303,12 @@ msgid "" "`print` function just calls :func:`str`.) These handlers are both optional." msgstr "" +#: extending/newtypes.rst:163 +msgid "" +"reprfunc tp_repr;\n" +"reprfunc tp_str;" +msgstr "" + #: extending/newtypes.rst:166 msgid "" "The :c:member:`~PyTypeObject.tp_repr` handler should return a string object " @@ -153,6 +316,16 @@ msgid "" "a simple example::" msgstr "" +#: extending/newtypes.rst:170 +msgid "" +"static PyObject *\n" +"newdatatype_repr(newdatatypeobject *obj)\n" +"{\n" +" return PyUnicode_FromFormat(\"Repr-ified_newdatatype{{size:%d}}\",\n" +" obj->obj_UnderlyingDatatypePtr->size);\n" +"}" +msgstr "" + #: extending/newtypes.rst:177 msgid "" "If no :c:member:`~PyTypeObject.tp_repr` handler is specified, the " @@ -175,6 +348,16 @@ msgstr "" msgid "Here is a simple example::" msgstr "" +#: extending/newtypes.rst:190 +msgid "" +"static PyObject *\n" +"newdatatype_str(newdatatypeobject *obj)\n" +"{\n" +" return PyUnicode_FromFormat(\"Stringified_newdatatype{{size:%d}}\",\n" +" obj->obj_UnderlyingDatatypePtr->size);\n" +"}" +msgstr "" + #: extending/newtypes.rst:200 msgid "Attribute Management" msgstr "" @@ -198,6 +381,15 @@ msgid "" "whichever pair makes more sense for the implementation's convenience. ::" msgstr "" +#: extending/newtypes.rst:214 +msgid "" +"getattrfunc tp_getattr; /* char * version */\n" +"setattrfunc tp_setattr;\n" +"/* ... */\n" +"getattrofunc tp_getattro; /* PyObject * version */\n" +"setattrofunc tp_setattro;" +msgstr "" + #: extending/newtypes.rst:220 msgid "" "If accessing attributes of an object is always a simple operation (this will " @@ -253,6 +445,13 @@ msgstr "" msgid "The tables are declared as three fields of the type object::" msgstr "" +#: extending/newtypes.rst:255 +msgid "" +"struct PyMethodDef *tp_methods;\n" +"struct PyMemberDef *tp_members;\n" +"struct PyGetSetDef *tp_getset;" +msgstr "" + #: extending/newtypes.rst:259 msgid "" "If :c:member:`~PyTypeObject.tp_methods` is not ``NULL``, it must refer to an " @@ -260,6 +459,16 @@ msgid "" "instance of this structure::" msgstr "" +#: extending/newtypes.rst:263 +msgid "" +"typedef struct PyMethodDef {\n" +" const char *ml_name; /* method name */\n" +" PyCFunction ml_meth; /* implementation function */\n" +" int ml_flags; /* flags */\n" +" const char *ml_doc; /* docstring */\n" +"} PyMethodDef;" +msgstr "" + #: extending/newtypes.rst:270 msgid "" "One entry should be defined for each method provided by the type; no entries " @@ -276,6 +485,17 @@ msgid "" "defined as::" msgstr "" +#: extending/newtypes.rst:279 +msgid "" +"typedef struct PyMemberDef {\n" +" const char *name;\n" +" int type;\n" +" int offset;\n" +" int flags;\n" +" const char *doc;\n" +"} PyMemberDef;" +msgstr "" + #: extending/newtypes.rst:287 msgid "" "For each entry in the table, a :term:`descriptor` will be constructed and " @@ -295,7 +515,7 @@ msgid "" "defined this way can have an associated doc string simply by providing the " "text in the table. An application can use the introspection API to retrieve " "the descriptor from the class object, and get the doc string using its :attr:" -"`!__doc__` attribute." +"`~type.__doc__` attribute." msgstr "" #: extending/newtypes.rst:301 @@ -330,6 +550,23 @@ msgstr "" msgid "Here is an example::" msgstr "" +#: extending/newtypes.rst:331 +msgid "" +"static PyObject *\n" +"newdatatype_getattr(newdatatypeobject *obj, char *name)\n" +"{\n" +" if (strcmp(name, \"data\") == 0)\n" +" {\n" +" return PyLong_FromLong(obj->data);\n" +" }\n" +"\n" +" PyErr_Format(PyExc_AttributeError,\n" +" \"'%.100s' object has no attribute '%.400s'\",\n" +" Py_TYPE(obj)->tp_name, name);\n" +" return NULL;\n" +"}" +msgstr "" + #: extending/newtypes.rst:345 msgid "" "The :c:member:`~PyTypeObject.tp_setattr` handler is called when the :meth:" @@ -340,10 +577,24 @@ msgid "" "tp_setattr` handler should be set to ``NULL``. ::" msgstr "" +#: extending/newtypes.rst:351 +msgid "" +"static int\n" +"newdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v)\n" +"{\n" +" PyErr_Format(PyExc_RuntimeError, \"Read-only attribute: %s\", name);\n" +" return -1;\n" +"}" +msgstr "" + #: extending/newtypes.rst:359 msgid "Object Comparison" msgstr "" +#: extending/newtypes.rst:363 +msgid "richcmpfunc tp_richcompare;" +msgstr "" + #: extending/newtypes.rst:365 msgid "" "The :c:member:`~PyTypeObject.tp_richcompare` handler is called when " @@ -369,6 +620,35 @@ msgid "" "the size of an internal pointer is equal::" msgstr "" +#: extending/newtypes.rst:381 +msgid "" +"static PyObject *\n" +"newdatatype_richcmp(newdatatypeobject *obj1, newdatatypeobject *obj2, int " +"op)\n" +"{\n" +" PyObject *result;\n" +" int c, size1, size2;\n" +"\n" +" /* code to make sure that both arguments are of type\n" +" newdatatype omitted */\n" +"\n" +" size1 = obj1->obj_UnderlyingDatatypePtr->size;\n" +" size2 = obj2->obj_UnderlyingDatatypePtr->size;\n" +"\n" +" switch (op) {\n" +" case Py_LT: c = size1 < size2; break;\n" +" case Py_LE: c = size1 <= size2; break;\n" +" case Py_EQ: c = size1 == size2; break;\n" +" case Py_NE: c = size1 != size2; break;\n" +" case Py_GT: c = size1 > size2; break;\n" +" case Py_GE: c = size1 >= size2; break;\n" +" }\n" +" result = c ? Py_True : Py_False;\n" +" Py_INCREF(result);\n" +" return result;\n" +" }" +msgstr "" + #: extending/newtypes.rst:408 msgid "Abstract Protocol Support" msgstr "" @@ -394,6 +674,13 @@ msgid "" "slot, but a slot may still be unfilled.) ::" msgstr "" +#: extending/newtypes.rst:425 +msgid "" +"PyNumberMethods *tp_as_number;\n" +"PySequenceMethods *tp_as_sequence;\n" +"PyMappingMethods *tp_as_mapping;" +msgstr "" + #: extending/newtypes.rst:429 msgid "" "If you wish your object to be able to act like a number, a sequence, or a " @@ -405,12 +692,29 @@ msgid "" "distribution. ::" msgstr "" +#: extending/newtypes.rst:436 +msgid "hashfunc tp_hash;" +msgstr "" + #: extending/newtypes.rst:438 msgid "" "This function, if you choose to provide it, should return a hash number for " "an instance of your data type. Here is a simple example::" msgstr "" +#: extending/newtypes.rst:441 +msgid "" +"static Py_hash_t\n" +"newdatatype_hash(newdatatypeobject *obj)\n" +"{\n" +" Py_hash_t result;\n" +" result = obj->some_size + 32767 * obj->some_number;\n" +" if (result == -1)\n" +" result = -2;\n" +" return result;\n" +"}" +msgstr "" + #: extending/newtypes.rst:451 msgid "" ":c:type:`!Py_hash_t` is a signed integer type with a platform-varying width. " @@ -419,6 +723,10 @@ msgid "" "computation is successful, as seen above." msgstr "" +#: extending/newtypes.rst:458 +msgid "ternaryfunc tp_call;" +msgstr "" + #: extending/newtypes.rst:460 msgid "" "This function is called when an instance of your data type is \"called\", " @@ -456,6 +764,34 @@ msgstr "" msgid "Here is a toy ``tp_call`` implementation::" msgstr "" +#: extending/newtypes.rst:480 +msgid "" +"static PyObject *\n" +"newdatatype_call(newdatatypeobject *obj, PyObject *args, PyObject *kwds)\n" +"{\n" +" PyObject *result;\n" +" const char *arg1;\n" +" const char *arg2;\n" +" const char *arg3;\n" +"\n" +" if (!PyArg_ParseTuple(args, \"sss:call\", &arg1, &arg2, &arg3)) {\n" +" return NULL;\n" +" }\n" +" result = PyUnicode_FromFormat(\n" +" \"Returning -- value: [%d] arg1: [%s] arg2: [%s] arg3: [%s]\\n\",\n" +" obj->obj_UnderlyingDatatypePtr->size,\n" +" arg1, arg2, arg3);\n" +" return result;\n" +"}" +msgstr "" + +#: extending/newtypes.rst:500 +msgid "" +"/* Iterators */\n" +"getiterfunc tp_iter;\n" +"iternextfunc tp_iternext;" +msgstr "" + #: extending/newtypes.rst:504 msgid "" "These functions provide support for the iterator protocol. Both handlers " @@ -532,12 +868,33 @@ msgid "" "Concretely, here is how the statically declared type object would look::" msgstr "" +#: extending/newtypes.rst:555 +msgid "" +"static PyTypeObject TrivialType = {\n" +" PyVarObject_HEAD_INIT(NULL, 0)\n" +" /* ... other members omitted for brevity ... */\n" +" .tp_flags = Py_TPFLAGS_MANAGED_WEAKREF | ...,\n" +"};" +msgstr "" + #: extending/newtypes.rst:562 msgid "" "The only further addition is that ``tp_dealloc`` needs to clear any weak " "references (by calling :c:func:`PyObject_ClearWeakRefs`)::" msgstr "" +#: extending/newtypes.rst:565 +msgid "" +"static void\n" +"Trivial_dealloc(TrivialObject *self)\n" +"{\n" +" /* Clear weakrefs first before calling any destructors */\n" +" PyObject_ClearWeakRefs((PyObject *) self);\n" +" /* ... remainder of destruction code omitted for brevity ... */\n" +" Py_TYPE(self)->tp_free((PyObject *) self);\n" +"}" +msgstr "" + #: extending/newtypes.rst:576 msgid "More Suggestions" msgstr "" @@ -558,6 +915,14 @@ msgid "" "sample of its use might be something like the following::" msgstr "" +#: extending/newtypes.rst:588 +msgid "" +"if (!PyObject_TypeCheck(some_object, &MyType)) {\n" +" PyErr_SetString(PyExc_TypeError, \"arg #1 not a mything\");\n" +" return NULL;\n" +"}" +msgstr "" + #: extending/newtypes.rst:594 msgid "Download CPython source releases." msgstr "" diff --git a/extending/newtypes_tutorial.po b/extending/newtypes_tutorial.po index 91baf7510..6463365c2 100644 --- a/extending/newtypes_tutorial.po +++ b/extending/newtypes_tutorial.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-09-18 22:33+0300\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -66,6 +66,55 @@ msgid "" "`PyType_FromSpec` function, which isn't covered in this tutorial." msgstr "" +#: extending/newtypes_tutorial.rst:48 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include \n" +"\n" +"typedef struct {\n" +" PyObject_HEAD\n" +" /* Type-specific fields go here. */\n" +"} CustomObject;\n" +"\n" +"static PyTypeObject CustomType = {\n" +" .ob_base = PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"custom.Custom\",\n" +" .tp_doc = PyDoc_STR(\"Custom objects\"),\n" +" .tp_basicsize = sizeof(CustomObject),\n" +" .tp_itemsize = 0,\n" +" .tp_flags = Py_TPFLAGS_DEFAULT,\n" +" .tp_new = PyType_GenericNew,\n" +"};\n" +"\n" +"static PyModuleDef custommodule = {\n" +" .m_base = PyModuleDef_HEAD_INIT,\n" +" .m_name = \"custom\",\n" +" .m_doc = \"Example module that creates an extension type.\",\n" +" .m_size = -1,\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_custom(void)\n" +"{\n" +" PyObject *m;\n" +" if (PyType_Ready(&CustomType) < 0)\n" +" return NULL;\n" +"\n" +" m = PyModule_Create(&custommodule);\n" +" if (m == NULL)\n" +" return NULL;\n" +"\n" +" Py_INCREF(&CustomType);\n" +" if (PyModule_AddObject(m, \"Custom\", (PyObject *) &CustomType) < 0) {\n" +" Py_DECREF(&CustomType);\n" +" Py_DECREF(m);\n" +" return NULL;\n" +" }\n" +"\n" +" return m;\n" +"}\n" +msgstr "" + #: extending/newtypes_tutorial.rst:50 msgid "" "Now that's quite a bit to take in at once, but hopefully bits will seem " @@ -95,6 +144,13 @@ msgstr "" msgid "The first bit is::" msgstr "" +#: extending/newtypes_tutorial.rst:63 +msgid "" +"typedef struct {\n" +" PyObject_HEAD\n" +"} CustomObject;" +msgstr "" + #: extending/newtypes_tutorial.rst:67 msgid "" "This is what a Custom object will contain. ``PyObject_HEAD`` is mandatory " @@ -119,10 +175,31 @@ msgid "" "standard Python floats::" msgstr "" +#: extending/newtypes_tutorial.rst:83 +msgid "" +"typedef struct {\n" +" PyObject_HEAD\n" +" double ob_fval;\n" +"} PyFloatObject;" +msgstr "" + #: extending/newtypes_tutorial.rst:88 msgid "The second bit is the definition of the type object. ::" msgstr "" +#: extending/newtypes_tutorial.rst:90 +msgid "" +"static PyTypeObject CustomType = {\n" +" .ob_base = PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"custom.Custom\",\n" +" .tp_doc = PyDoc_STR(\"Custom objects\"),\n" +" .tp_basicsize = sizeof(CustomObject),\n" +" .tp_itemsize = 0,\n" +" .tp_flags = Py_TPFLAGS_DEFAULT,\n" +" .tp_new = PyType_GenericNew,\n" +"};" +msgstr "" + #: extending/newtypes_tutorial.rst:101 msgid "" "We recommend using C99-style designated initializers as above, to avoid " @@ -142,18 +219,34 @@ msgstr "" msgid "We're going to pick it apart, one field at a time::" msgstr "" +#: extending/newtypes_tutorial.rst:112 +msgid ".ob_base = PyVarObject_HEAD_INIT(NULL, 0)" +msgstr "" + #: extending/newtypes_tutorial.rst:114 msgid "" "This line is mandatory boilerplate to initialize the ``ob_base`` field " "mentioned above. ::" msgstr "" +#: extending/newtypes_tutorial.rst:117 +msgid ".tp_name = \"custom.Custom\"," +msgstr "" + #: extending/newtypes_tutorial.rst:119 msgid "" "The name of our type. This will appear in the default textual " "representation of our objects and in some error messages, for example:" msgstr "" +#: extending/newtypes_tutorial.rst:122 +msgid "" +">>> \"\" + custom.Custom()\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: can only concatenate str (not \"custom.Custom\") to str" +msgstr "" + #: extending/newtypes_tutorial.rst:129 msgid "" "Note that the name is a dotted name that includes both the module name and " @@ -163,6 +256,12 @@ msgid "" "your type compatible with the :mod:`pydoc` and :mod:`pickle` modules. ::" msgstr "" +#: extending/newtypes_tutorial.rst:135 +msgid "" +".tp_basicsize = sizeof(CustomObject),\n" +".tp_itemsize = 0," +msgstr "" + #: extending/newtypes_tutorial.rst:138 msgid "" "This is so that Python knows how much memory to allocate when creating new :" @@ -175,8 +274,8 @@ msgid "" "If you want your type to be subclassable from Python, and your type has the " "same :c:member:`~PyTypeObject.tp_basicsize` as its base type, you may have " "problems with multiple inheritance. A Python subclass of your type will " -"have to list your type first in its :attr:`~class.__bases__`, or else it " -"will not be able to call your type's :meth:`~object.__new__` method without " +"have to list your type first in its :attr:`~type.__bases__`, or else it will " +"not be able to call your type's :meth:`~object.__new__` method without " "getting an error. You can avoid this problem by ensuring that your type has " "a larger value for :c:member:`~PyTypeObject.tp_basicsize` than its base type " "does. Most of the time, this will be true anyway, because either your base " @@ -188,6 +287,10 @@ msgstr "" msgid "We set the class flags to :c:macro:`Py_TPFLAGS_DEFAULT`. ::" msgstr "" +#: extending/newtypes_tutorial.rst:156 +msgid ".tp_flags = Py_TPFLAGS_DEFAULT," +msgstr "" + #: extending/newtypes_tutorial.rst:158 msgid "" "All types should include this constant in their flags. It enables all of " @@ -200,6 +303,10 @@ msgid "" "We provide a doc string for the type in :c:member:`~PyTypeObject.tp_doc`. ::" msgstr "" +#: extending/newtypes_tutorial.rst:164 +msgid ".tp_doc = PyDoc_STR(\"Custom objects\")," +msgstr "" + #: extending/newtypes_tutorial.rst:166 msgid "" "To enable object creation, we have to provide a :c:member:`~PyTypeObject." @@ -209,12 +316,22 @@ msgid "" "`PyType_GenericNew`. ::" msgstr "" +#: extending/newtypes_tutorial.rst:171 +msgid ".tp_new = PyType_GenericNew," +msgstr "" + #: extending/newtypes_tutorial.rst:173 msgid "" "Everything else in the file should be familiar, except for some code in :c:" "func:`!PyInit_custom`::" msgstr "" +#: extending/newtypes_tutorial.rst:176 +msgid "" +"if (PyType_Ready(&CustomType) < 0)\n" +" return;" +msgstr "" + #: extending/newtypes_tutorial.rst:179 msgid "" "This initializes the :class:`!Custom` type, filling in a number of members " @@ -222,26 +339,63 @@ msgid "" "that we initially set to ``NULL``. ::" msgstr "" +#: extending/newtypes_tutorial.rst:183 +msgid "" +"Py_INCREF(&CustomType);\n" +"if (PyModule_AddObject(m, \"Custom\", (PyObject *) &CustomType) < 0) {\n" +" Py_DECREF(&CustomType);\n" +" Py_DECREF(m);\n" +" return NULL;\n" +"}" +msgstr "" + #: extending/newtypes_tutorial.rst:190 msgid "" "This adds the type to the module dictionary. This allows us to create :" "class:`!Custom` instances by calling the :class:`!Custom` class:" msgstr "" +#: extending/newtypes_tutorial.rst:193 +msgid "" +">>> import custom\n" +">>> mycustom = custom.Custom()" +msgstr "" + #: extending/newtypes_tutorial.rst:198 msgid "" "That's it! All that remains is to build it; put the above code in a file " "called :file:`custom.c`," msgstr "" +#: extending/newtypes_tutorial.rst:201 +msgid "" +"[build-system]\n" +"requires = [\"setuptools\"]\n" +"build-backend = \"setuptools.build_meta\"\n" +"\n" +"[project]\n" +"name = \"custom\"\n" +"version = \"1\"\n" +msgstr "" + #: extending/newtypes_tutorial.rst:203 msgid "in a file called :file:`pyproject.toml`, and" msgstr "" +#: extending/newtypes_tutorial.rst:205 +msgid "" +"from setuptools import Extension, setup\n" +"setup(ext_modules=[Extension(\"custom\", [\"custom.c\"])])" +msgstr "" + #: extending/newtypes_tutorial.rst:210 msgid "in a file called :file:`setup.py`; then typing" msgstr "" +#: extending/newtypes_tutorial.rst:212 extending/newtypes_tutorial.rst:527 +msgid "$ python -m pip install ." +msgstr "" + #: extending/newtypes_tutorial.rst:216 msgid "" "in a shell should produce a file :file:`custom.so` in a subdirectory and " @@ -270,6 +424,141 @@ msgid "" "custom2` that adds these capabilities:" msgstr "" +#: extending/newtypes_tutorial.rst:233 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include \n" +"#include /* for offsetof() */\n" +"\n" +"typedef struct {\n" +" PyObject_HEAD\n" +" PyObject *first; /* first name */\n" +" PyObject *last; /* last name */\n" +" int number;\n" +"} CustomObject;\n" +"\n" +"static void\n" +"Custom_dealloc(CustomObject *self)\n" +"{\n" +" Py_XDECREF(self->first);\n" +" Py_XDECREF(self->last);\n" +" Py_TYPE(self)->tp_free((PyObject *) self);\n" +"}\n" +"\n" +"static PyObject *\n" +"Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n" +"{\n" +" CustomObject *self;\n" +" self = (CustomObject *) type->tp_alloc(type, 0);\n" +" if (self != NULL) {\n" +" self->first = PyUnicode_FromString(\"\");\n" +" if (self->first == NULL) {\n" +" Py_DECREF(self);\n" +" return NULL;\n" +" }\n" +" self->last = PyUnicode_FromString(\"\");\n" +" if (self->last == NULL) {\n" +" Py_DECREF(self);\n" +" return NULL;\n" +" }\n" +" self->number = 0;\n" +" }\n" +" return (PyObject *) self;\n" +"}\n" +"\n" +"static int\n" +"Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)\n" +"{\n" +" static char *kwlist[] = {\"first\", \"last\", \"number\", NULL};\n" +" PyObject *first = NULL, *last = NULL;\n" +"\n" +" if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|OOi\", kwlist,\n" +" &first, &last,\n" +" &self->number))\n" +" return -1;\n" +"\n" +" if (first) {\n" +" Py_XSETREF(self->first, Py_NewRef(first));\n" +" }\n" +" if (last) {\n" +" Py_XSETREF(self->last, Py_NewRef(last));\n" +" }\n" +" return 0;\n" +"}\n" +"\n" +"static PyMemberDef Custom_members[] = {\n" +" {\"first\", Py_T_OBJECT_EX, offsetof(CustomObject, first), 0,\n" +" \"first name\"},\n" +" {\"last\", Py_T_OBJECT_EX, offsetof(CustomObject, last), 0,\n" +" \"last name\"},\n" +" {\"number\", Py_T_INT, offsetof(CustomObject, number), 0,\n" +" \"custom number\"},\n" +" {NULL} /* Sentinel */\n" +"};\n" +"\n" +"static PyObject *\n" +"Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))\n" +"{\n" +" if (self->first == NULL) {\n" +" PyErr_SetString(PyExc_AttributeError, \"first\");\n" +" return NULL;\n" +" }\n" +" if (self->last == NULL) {\n" +" PyErr_SetString(PyExc_AttributeError, \"last\");\n" +" return NULL;\n" +" }\n" +" return PyUnicode_FromFormat(\"%S %S\", self->first, self->last);\n" +"}\n" +"\n" +"static PyMethodDef Custom_methods[] = {\n" +" {\"name\", (PyCFunction) Custom_name, METH_NOARGS,\n" +" \"Return the name, combining the first and last name\"\n" +" },\n" +" {NULL} /* Sentinel */\n" +"};\n" +"\n" +"static PyTypeObject CustomType = {\n" +" .ob_base = PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"custom2.Custom\",\n" +" .tp_doc = PyDoc_STR(\"Custom objects\"),\n" +" .tp_basicsize = sizeof(CustomObject),\n" +" .tp_itemsize = 0,\n" +" .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,\n" +" .tp_new = Custom_new,\n" +" .tp_init = (initproc) Custom_init,\n" +" .tp_dealloc = (destructor) Custom_dealloc,\n" +" .tp_members = Custom_members,\n" +" .tp_methods = Custom_methods,\n" +"};\n" +"\n" +"static PyModuleDef custommodule = {\n" +" .m_base =PyModuleDef_HEAD_INIT,\n" +" .m_name = \"custom2\",\n" +" .m_doc = \"Example module that creates an extension type.\",\n" +" .m_size = -1,\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_custom2(void)\n" +"{\n" +" PyObject *m;\n" +" if (PyType_Ready(&CustomType) < 0)\n" +" return NULL;\n" +"\n" +" m = PyModule_Create(&custommodule);\n" +" if (m == NULL)\n" +" return NULL;\n" +"\n" +" if (PyModule_AddObjectRef(m, \"Custom\", (PyObject *) &CustomType) < 0) " +"{\n" +" Py_DECREF(m);\n" +" return NULL;\n" +" }\n" +"\n" +" return m;\n" +"}\n" +msgstr "" + #: extending/newtypes_tutorial.rst:236 msgid "This version of the module has a number of changes." msgstr "" @@ -286,16 +575,41 @@ msgstr "" msgid "The object structure is updated accordingly::" msgstr "" +#: extending/newtypes_tutorial.rst:244 +msgid "" +"typedef struct {\n" +" PyObject_HEAD\n" +" PyObject *first; /* first name */\n" +" PyObject *last; /* last name */\n" +" int number;\n" +"} CustomObject;" +msgstr "" + #: extending/newtypes_tutorial.rst:251 msgid "" "Because we now have data to manage, we have to be more careful about object " "allocation and deallocation. At a minimum, we need a deallocation method::" msgstr "" +#: extending/newtypes_tutorial.rst:254 +msgid "" +"static void\n" +"Custom_dealloc(CustomObject *self)\n" +"{\n" +" Py_XDECREF(self->first);\n" +" Py_XDECREF(self->last);\n" +" Py_TYPE(self)->tp_free((PyObject *) self);\n" +"}" +msgstr "" + #: extending/newtypes_tutorial.rst:262 msgid "which is assigned to the :c:member:`~PyTypeObject.tp_dealloc` member::" msgstr "" +#: extending/newtypes_tutorial.rst:264 +msgid ".tp_dealloc = (destructor) Custom_dealloc," +msgstr "" + #: extending/newtypes_tutorial.rst:266 msgid "" "This method first clears the reference counts of the two Python attributes. :" @@ -322,10 +636,38 @@ msgid "" "strings, so we provide a ``tp_new`` implementation::" msgstr "" +#: extending/newtypes_tutorial.rst:284 +msgid "" +"static PyObject *\n" +"Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n" +"{\n" +" CustomObject *self;\n" +" self = (CustomObject *) type->tp_alloc(type, 0);\n" +" if (self != NULL) {\n" +" self->first = PyUnicode_FromString(\"\");\n" +" if (self->first == NULL) {\n" +" Py_DECREF(self);\n" +" return NULL;\n" +" }\n" +" self->last = PyUnicode_FromString(\"\");\n" +" if (self->last == NULL) {\n" +" Py_DECREF(self);\n" +" return NULL;\n" +" }\n" +" self->number = 0;\n" +" }\n" +" return (PyObject *) self;\n" +"}" +msgstr "" + #: extending/newtypes_tutorial.rst:305 msgid "and install it in the :c:member:`~PyTypeObject.tp_new` member::" msgstr "" +#: extending/newtypes_tutorial.rst:307 +msgid ".tp_new = Custom_new," +msgstr "" + #: extending/newtypes_tutorial.rst:309 msgid "" "The ``tp_new`` handler is responsible for creating (as opposed to " @@ -359,6 +701,10 @@ msgid "" "slot to allocate memory::" msgstr "" +#: extending/newtypes_tutorial.rst:331 +msgid "self = (CustomObject *) type->tp_alloc(type, 0);" +msgstr "" + #: extending/newtypes_tutorial.rst:333 msgid "" "Since memory allocation may fail, we must check the :c:member:`~PyTypeObject." @@ -392,10 +738,43 @@ msgid "" "initial values for our instance::" msgstr "" +#: extending/newtypes_tutorial.rst:356 +msgid "" +"static int\n" +"Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)\n" +"{\n" +" static char *kwlist[] = {\"first\", \"last\", \"number\", NULL};\n" +" PyObject *first = NULL, *last = NULL, *tmp;\n" +"\n" +" if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|OOi\", kwlist,\n" +" &first, &last,\n" +" &self->number))\n" +" return -1;\n" +"\n" +" if (first) {\n" +" tmp = self->first;\n" +" Py_INCREF(first);\n" +" self->first = first;\n" +" Py_XDECREF(tmp);\n" +" }\n" +" if (last) {\n" +" tmp = self->last;\n" +" Py_INCREF(last);\n" +" self->last = last;\n" +" Py_XDECREF(tmp);\n" +" }\n" +" return 0;\n" +"}" +msgstr "" + #: extending/newtypes_tutorial.rst:382 msgid "by filling the :c:member:`~PyTypeObject.tp_init` slot. ::" msgstr "" +#: extending/newtypes_tutorial.rst:384 +msgid ".tp_init = (initproc) Custom_init," +msgstr "" + #: extending/newtypes_tutorial.rst:386 msgid "" "The :c:member:`~PyTypeObject.tp_init` slot is exposed in Python as the :meth:" @@ -415,6 +794,15 @@ msgid "" "``first`` member like this::" msgstr "" +#: extending/newtypes_tutorial.rst:399 +msgid "" +"if (first) {\n" +" Py_XDECREF(self->first);\n" +" Py_INCREF(first);\n" +" self->first = first;\n" +"}" +msgstr "" + #: extending/newtypes_tutorial.rst:405 msgid "" "But this would be risky. Our type doesn't restrict the type of the " @@ -455,11 +843,28 @@ msgid "" "of ways to do that. The simplest way is to define member definitions::" msgstr "" +#: extending/newtypes_tutorial.rst:427 +msgid "" +"static PyMemberDef Custom_members[] = {\n" +" {\"first\", Py_T_OBJECT_EX, offsetof(CustomObject, first), 0,\n" +" \"first name\"},\n" +" {\"last\", Py_T_OBJECT_EX, offsetof(CustomObject, last), 0,\n" +" \"last name\"},\n" +" {\"number\", Py_T_INT, offsetof(CustomObject, number), 0,\n" +" \"custom number\"},\n" +" {NULL} /* Sentinel */\n" +"};" +msgstr "" + #: extending/newtypes_tutorial.rst:437 msgid "" "and put the definitions in the :c:member:`~PyTypeObject.tp_members` slot::" msgstr "" +#: extending/newtypes_tutorial.rst:439 +msgid ".tp_members = Custom_members," +msgstr "" + #: extending/newtypes_tutorial.rst:441 msgid "" "Each member definition has a member name, type, offset, access flags and " @@ -480,10 +885,27 @@ msgstr "" #: extending/newtypes_tutorial.rst:452 msgid "" -"We define a single method, :meth:`!Custom.name()`, that outputs the objects " +"We define a single method, :meth:`!Custom.name`, that outputs the objects " "name as the concatenation of the first and last names. ::" msgstr "" +#: extending/newtypes_tutorial.rst:455 +msgid "" +"static PyObject *\n" +"Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))\n" +"{\n" +" if (self->first == NULL) {\n" +" PyErr_SetString(PyExc_AttributeError, \"first\");\n" +" return NULL;\n" +" }\n" +" if (self->last == NULL) {\n" +" PyErr_SetString(PyExc_AttributeError, \"last\");\n" +" return NULL;\n" +" }\n" +" return PyUnicode_FromFormat(\"%S %S\", self->first, self->last);\n" +"}" +msgstr "" + #: extending/newtypes_tutorial.rst:469 msgid "" "The method is implemented as a C function that takes a :class:`!Custom` (or :" @@ -494,6 +916,12 @@ msgid "" "method is equivalent to the Python method:" msgstr "" +#: extending/newtypes_tutorial.rst:476 +msgid "" +"def name(self):\n" +" return \"%s %s\" % (self.first, self.last)" +msgstr "" + #: extending/newtypes_tutorial.rst:481 msgid "" "Note that we have to check for the possibility that our :attr:`!first` and :" @@ -509,6 +937,16 @@ msgid "" "definitions::" msgstr "" +#: extending/newtypes_tutorial.rst:490 +msgid "" +"static PyMethodDef Custom_methods[] = {\n" +" {\"name\", (PyCFunction) Custom_name, METH_NOARGS,\n" +" \"Return the name, combining the first and last name\"\n" +" },\n" +" {NULL} /* Sentinel */\n" +"};" +msgstr "" + #: extending/newtypes_tutorial.rst:497 msgid "" "(note that we used the :c:macro:`METH_NOARGS` flag to indicate that the " @@ -519,6 +957,10 @@ msgstr "" msgid "and assign it to the :c:member:`~PyTypeObject.tp_methods` slot::" msgstr "" +#: extending/newtypes_tutorial.rst:502 +msgid ".tp_methods = Custom_methods," +msgstr "" + #: extending/newtypes_tutorial.rst:504 msgid "" "Finally, we'll make our type usable as a base class for subclassing. We've " @@ -527,6 +969,10 @@ msgid "" "to add the :c:macro:`Py_TPFLAGS_BASETYPE` to our class flag definition::" msgstr "" +#: extending/newtypes_tutorial.rst:509 +msgid ".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE," +msgstr "" + #: extending/newtypes_tutorial.rst:511 msgid "" "We rename :c:func:`!PyInit_custom` to :c:func:`!PyInit_custom2`, update the " @@ -538,6 +984,15 @@ msgstr "" msgid "Finally, we update our :file:`setup.py` file to include the new module," msgstr "" +#: extending/newtypes_tutorial.rst:517 +msgid "" +"from setuptools import Extension, setup\n" +"setup(ext_modules=[\n" +" Extension(\"custom\", [\"custom.c\"]),\n" +" Extension(\"custom2\", [\"custom2.c\"]),\n" +"])" +msgstr "" + #: extending/newtypes_tutorial.rst:525 msgid "and then we re-install so that we can ``import custom2``:" msgstr "" @@ -555,6 +1010,184 @@ msgid "" "make sure that these attributes always contain strings." msgstr "" +#: extending/newtypes_tutorial.rst:540 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include \n" +"#include /* for offsetof() */\n" +"\n" +"typedef struct {\n" +" PyObject_HEAD\n" +" PyObject *first; /* first name */\n" +" PyObject *last; /* last name */\n" +" int number;\n" +"} CustomObject;\n" +"\n" +"static void\n" +"Custom_dealloc(CustomObject *self)\n" +"{\n" +" Py_XDECREF(self->first);\n" +" Py_XDECREF(self->last);\n" +" Py_TYPE(self)->tp_free((PyObject *) self);\n" +"}\n" +"\n" +"static PyObject *\n" +"Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n" +"{\n" +" CustomObject *self;\n" +" self = (CustomObject *) type->tp_alloc(type, 0);\n" +" if (self != NULL) {\n" +" self->first = PyUnicode_FromString(\"\");\n" +" if (self->first == NULL) {\n" +" Py_DECREF(self);\n" +" return NULL;\n" +" }\n" +" self->last = PyUnicode_FromString(\"\");\n" +" if (self->last == NULL) {\n" +" Py_DECREF(self);\n" +" return NULL;\n" +" }\n" +" self->number = 0;\n" +" }\n" +" return (PyObject *) self;\n" +"}\n" +"\n" +"static int\n" +"Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)\n" +"{\n" +" static char *kwlist[] = {\"first\", \"last\", \"number\", NULL};\n" +" PyObject *first = NULL, *last = NULL;\n" +"\n" +" if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|UUi\", kwlist,\n" +" &first, &last,\n" +" &self->number))\n" +" return -1;\n" +"\n" +" if (first) {\n" +" Py_SETREF(self->first, Py_NewRef(first));\n" +" }\n" +" if (last) {\n" +" Py_SETREF(self->last, Py_NewRef(last));\n" +" }\n" +" return 0;\n" +"}\n" +"\n" +"static PyMemberDef Custom_members[] = {\n" +" {\"number\", Py_T_INT, offsetof(CustomObject, number), 0,\n" +" \"custom number\"},\n" +" {NULL} /* Sentinel */\n" +"};\n" +"\n" +"static PyObject *\n" +"Custom_getfirst(CustomObject *self, void *closure)\n" +"{\n" +" return Py_NewRef(self->first);\n" +"}\n" +"\n" +"static int\n" +"Custom_setfirst(CustomObject *self, PyObject *value, void *closure)\n" +"{\n" +" if (value == NULL) {\n" +" PyErr_SetString(PyExc_TypeError, \"Cannot delete the first " +"attribute\");\n" +" return -1;\n" +" }\n" +" if (!PyUnicode_Check(value)) {\n" +" PyErr_SetString(PyExc_TypeError,\n" +" \"The first attribute value must be a string\");\n" +" return -1;\n" +" }\n" +" Py_SETREF(self->first, Py_NewRef(value));\n" +" return 0;\n" +"}\n" +"\n" +"static PyObject *\n" +"Custom_getlast(CustomObject *self, void *closure)\n" +"{\n" +" return Py_NewRef(self->last);\n" +"}\n" +"\n" +"static int\n" +"Custom_setlast(CustomObject *self, PyObject *value, void *closure)\n" +"{\n" +" if (value == NULL) {\n" +" PyErr_SetString(PyExc_TypeError, \"Cannot delete the last " +"attribute\");\n" +" return -1;\n" +" }\n" +" if (!PyUnicode_Check(value)) {\n" +" PyErr_SetString(PyExc_TypeError,\n" +" \"The last attribute value must be a string\");\n" +" return -1;\n" +" }\n" +" Py_SETREF(self->last, Py_NewRef(value));\n" +" return 0;\n" +"}\n" +"\n" +"static PyGetSetDef Custom_getsetters[] = {\n" +" {\"first\", (getter) Custom_getfirst, (setter) Custom_setfirst,\n" +" \"first name\", NULL},\n" +" {\"last\", (getter) Custom_getlast, (setter) Custom_setlast,\n" +" \"last name\", NULL},\n" +" {NULL} /* Sentinel */\n" +"};\n" +"\n" +"static PyObject *\n" +"Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))\n" +"{\n" +" return PyUnicode_FromFormat(\"%S %S\", self->first, self->last);\n" +"}\n" +"\n" +"static PyMethodDef Custom_methods[] = {\n" +" {\"name\", (PyCFunction) Custom_name, METH_NOARGS,\n" +" \"Return the name, combining the first and last name\"\n" +" },\n" +" {NULL} /* Sentinel */\n" +"};\n" +"\n" +"static PyTypeObject CustomType = {\n" +" .ob_base = PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"custom3.Custom\",\n" +" .tp_doc = PyDoc_STR(\"Custom objects\"),\n" +" .tp_basicsize = sizeof(CustomObject),\n" +" .tp_itemsize = 0,\n" +" .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,\n" +" .tp_new = Custom_new,\n" +" .tp_init = (initproc) Custom_init,\n" +" .tp_dealloc = (destructor) Custom_dealloc,\n" +" .tp_members = Custom_members,\n" +" .tp_methods = Custom_methods,\n" +" .tp_getset = Custom_getsetters,\n" +"};\n" +"\n" +"static PyModuleDef custommodule = {\n" +" .m_base = PyModuleDef_HEAD_INIT,\n" +" .m_name = \"custom3\",\n" +" .m_doc = \"Example module that creates an extension type.\",\n" +" .m_size = -1,\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_custom3(void)\n" +"{\n" +" PyObject *m;\n" +" if (PyType_Ready(&CustomType) < 0)\n" +" return NULL;\n" +"\n" +" m = PyModule_Create(&custommodule);\n" +" if (m == NULL)\n" +" return NULL;\n" +"\n" +" if (PyModule_AddObjectRef(m, \"Custom\", (PyObject *) &CustomType) < 0) " +"{\n" +" Py_DECREF(m);\n" +" return NULL;\n" +" }\n" +"\n" +" return m;\n" +"}\n" +msgstr "" + #: extending/newtypes_tutorial.rst:543 msgid "" "To provide greater control, over the :attr:`!first` and :attr:`!last` " @@ -562,6 +1195,37 @@ msgid "" "functions for getting and setting the :attr:`!first` attribute::" msgstr "" +#: extending/newtypes_tutorial.rst:547 +msgid "" +"static PyObject *\n" +"Custom_getfirst(CustomObject *self, void *closure)\n" +"{\n" +" Py_INCREF(self->first);\n" +" return self->first;\n" +"}\n" +"\n" +"static int\n" +"Custom_setfirst(CustomObject *self, PyObject *value, void *closure)\n" +"{\n" +" PyObject *tmp;\n" +" if (value == NULL) {\n" +" PyErr_SetString(PyExc_TypeError, \"Cannot delete the first " +"attribute\");\n" +" return -1;\n" +" }\n" +" if (!PyUnicode_Check(value)) {\n" +" PyErr_SetString(PyExc_TypeError,\n" +" \"The first attribute value must be a string\");\n" +" return -1;\n" +" }\n" +" tmp = self->first;\n" +" Py_INCREF(value);\n" +" self->first = value;\n" +" Py_DECREF(tmp);\n" +" return 0;\n" +"}" +msgstr "" + #: extending/newtypes_tutorial.rst:574 msgid "" "The getter function is passed a :class:`!Custom` object and a \"closure\", " @@ -584,10 +1248,25 @@ msgstr "" msgid "We create an array of :c:type:`PyGetSetDef` structures::" msgstr "" +#: extending/newtypes_tutorial.rst:587 +msgid "" +"static PyGetSetDef Custom_getsetters[] = {\n" +" {\"first\", (getter) Custom_getfirst, (setter) Custom_setfirst,\n" +" \"first name\", NULL},\n" +" {\"last\", (getter) Custom_getlast, (setter) Custom_setlast,\n" +" \"last name\", NULL},\n" +" {NULL} /* Sentinel */\n" +"};" +msgstr "" + #: extending/newtypes_tutorial.rst:595 msgid "and register it in the :c:member:`~PyTypeObject.tp_getset` slot::" msgstr "" +#: extending/newtypes_tutorial.rst:597 +msgid ".tp_getset = Custom_getsetters," +msgstr "" + #: extending/newtypes_tutorial.rst:599 msgid "" "The last item in a :c:type:`PyGetSetDef` structure is the \"closure\" " @@ -599,12 +1278,50 @@ msgstr "" msgid "We also remove the member definitions for these attributes::" msgstr "" +#: extending/newtypes_tutorial.rst:604 +msgid "" +"static PyMemberDef Custom_members[] = {\n" +" {\"number\", Py_T_INT, offsetof(CustomObject, number), 0,\n" +" \"custom number\"},\n" +" {NULL} /* Sentinel */\n" +"};" +msgstr "" + #: extending/newtypes_tutorial.rst:610 msgid "" "We also need to update the :c:member:`~PyTypeObject.tp_init` handler to only " "allow strings [#]_ to be passed::" msgstr "" +#: extending/newtypes_tutorial.rst:613 +msgid "" +"static int\n" +"Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)\n" +"{\n" +" static char *kwlist[] = {\"first\", \"last\", \"number\", NULL};\n" +" PyObject *first = NULL, *last = NULL, *tmp;\n" +"\n" +" if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|UUi\", kwlist,\n" +" &first, &last,\n" +" &self->number))\n" +" return -1;\n" +"\n" +" if (first) {\n" +" tmp = self->first;\n" +" Py_INCREF(first);\n" +" self->first = first;\n" +" Py_DECREF(tmp);\n" +" }\n" +" if (last) {\n" +" tmp = self->last;\n" +" Py_INCREF(last);\n" +" self->last = last;\n" +" Py_DECREF(tmp);\n" +" }\n" +" return 0;\n" +"}" +msgstr "" + #: extending/newtypes_tutorial.rst:639 msgid "" "With these changes, we can assure that the ``first`` and ``last`` members " @@ -633,6 +1350,13 @@ msgid "" "This can happen when objects are involved in cycles. For example, consider:" msgstr "" +#: extending/newtypes_tutorial.rst:658 +msgid "" +">>> l = []\n" +">>> l.append(l)\n" +">>> del l" +msgstr "" + #: extending/newtypes_tutorial.rst:664 msgid "" "In this example, we create a list that contains itself. When we delete it, " @@ -650,6 +1374,15 @@ msgid "" "those two reasons, :class:`!Custom` objects can participate in cycles:" msgstr "" +#: extending/newtypes_tutorial.rst:675 +msgid "" +">>> import custom3\n" +">>> class Derived(custom3.Custom): pass\n" +"...\n" +">>> n = Derived()\n" +">>> n.some_attribute = n" +msgstr "" + #: extending/newtypes_tutorial.rst:683 msgid "" "To allow a :class:`!Custom` instance participating in a reference cycle to " @@ -658,12 +1391,229 @@ msgid "" "these slots:" msgstr "" +#: extending/newtypes_tutorial.rst:687 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include \n" +"#include /* for offsetof() */\n" +"\n" +"typedef struct {\n" +" PyObject_HEAD\n" +" PyObject *first; /* first name */\n" +" PyObject *last; /* last name */\n" +" int number;\n" +"} CustomObject;\n" +"\n" +"static int\n" +"Custom_traverse(CustomObject *self, visitproc visit, void *arg)\n" +"{\n" +" Py_VISIT(self->first);\n" +" Py_VISIT(self->last);\n" +" return 0;\n" +"}\n" +"\n" +"static int\n" +"Custom_clear(CustomObject *self)\n" +"{\n" +" Py_CLEAR(self->first);\n" +" Py_CLEAR(self->last);\n" +" return 0;\n" +"}\n" +"\n" +"static void\n" +"Custom_dealloc(CustomObject *self)\n" +"{\n" +" PyObject_GC_UnTrack(self);\n" +" Custom_clear(self);\n" +" Py_TYPE(self)->tp_free((PyObject *) self);\n" +"}\n" +"\n" +"static PyObject *\n" +"Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n" +"{\n" +" CustomObject *self;\n" +" self = (CustomObject *) type->tp_alloc(type, 0);\n" +" if (self != NULL) {\n" +" self->first = PyUnicode_FromString(\"\");\n" +" if (self->first == NULL) {\n" +" Py_DECREF(self);\n" +" return NULL;\n" +" }\n" +" self->last = PyUnicode_FromString(\"\");\n" +" if (self->last == NULL) {\n" +" Py_DECREF(self);\n" +" return NULL;\n" +" }\n" +" self->number = 0;\n" +" }\n" +" return (PyObject *) self;\n" +"}\n" +"\n" +"static int\n" +"Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)\n" +"{\n" +" static char *kwlist[] = {\"first\", \"last\", \"number\", NULL};\n" +" PyObject *first = NULL, *last = NULL;\n" +"\n" +" if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|UUi\", kwlist,\n" +" &first, &last,\n" +" &self->number))\n" +" return -1;\n" +"\n" +" if (first) {\n" +" Py_SETREF(self->first, Py_NewRef(first));\n" +" }\n" +" if (last) {\n" +" Py_SETREF(self->last, Py_NewRef(last));\n" +" }\n" +" return 0;\n" +"}\n" +"\n" +"static PyMemberDef Custom_members[] = {\n" +" {\"number\", Py_T_INT, offsetof(CustomObject, number), 0,\n" +" \"custom number\"},\n" +" {NULL} /* Sentinel */\n" +"};\n" +"\n" +"static PyObject *\n" +"Custom_getfirst(CustomObject *self, void *closure)\n" +"{\n" +" return Py_NewRef(self->first);\n" +"}\n" +"\n" +"static int\n" +"Custom_setfirst(CustomObject *self, PyObject *value, void *closure)\n" +"{\n" +" if (value == NULL) {\n" +" PyErr_SetString(PyExc_TypeError, \"Cannot delete the first " +"attribute\");\n" +" return -1;\n" +" }\n" +" if (!PyUnicode_Check(value)) {\n" +" PyErr_SetString(PyExc_TypeError,\n" +" \"The first attribute value must be a string\");\n" +" return -1;\n" +" }\n" +" Py_XSETREF(self->first, Py_NewRef(value));\n" +" return 0;\n" +"}\n" +"\n" +"static PyObject *\n" +"Custom_getlast(CustomObject *self, void *closure)\n" +"{\n" +" return Py_NewRef(self->last);\n" +"}\n" +"\n" +"static int\n" +"Custom_setlast(CustomObject *self, PyObject *value, void *closure)\n" +"{\n" +" if (value == NULL) {\n" +" PyErr_SetString(PyExc_TypeError, \"Cannot delete the last " +"attribute\");\n" +" return -1;\n" +" }\n" +" if (!PyUnicode_Check(value)) {\n" +" PyErr_SetString(PyExc_TypeError,\n" +" \"The last attribute value must be a string\");\n" +" return -1;\n" +" }\n" +" Py_XSETREF(self->last, Py_NewRef(value));\n" +" return 0;\n" +"}\n" +"\n" +"static PyGetSetDef Custom_getsetters[] = {\n" +" {\"first\", (getter) Custom_getfirst, (setter) Custom_setfirst,\n" +" \"first name\", NULL},\n" +" {\"last\", (getter) Custom_getlast, (setter) Custom_setlast,\n" +" \"last name\", NULL},\n" +" {NULL} /* Sentinel */\n" +"};\n" +"\n" +"static PyObject *\n" +"Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))\n" +"{\n" +" return PyUnicode_FromFormat(\"%S %S\", self->first, self->last);\n" +"}\n" +"\n" +"static PyMethodDef Custom_methods[] = {\n" +" {\"name\", (PyCFunction) Custom_name, METH_NOARGS,\n" +" \"Return the name, combining the first and last name\"\n" +" },\n" +" {NULL} /* Sentinel */\n" +"};\n" +"\n" +"static PyTypeObject CustomType = {\n" +" .ob_base = PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"custom4.Custom\",\n" +" .tp_doc = PyDoc_STR(\"Custom objects\"),\n" +" .tp_basicsize = sizeof(CustomObject),\n" +" .tp_itemsize = 0,\n" +" .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | " +"Py_TPFLAGS_HAVE_GC,\n" +" .tp_new = Custom_new,\n" +" .tp_init = (initproc) Custom_init,\n" +" .tp_dealloc = (destructor) Custom_dealloc,\n" +" .tp_traverse = (traverseproc) Custom_traverse,\n" +" .tp_clear = (inquiry) Custom_clear,\n" +" .tp_members = Custom_members,\n" +" .tp_methods = Custom_methods,\n" +" .tp_getset = Custom_getsetters,\n" +"};\n" +"\n" +"static PyModuleDef custommodule = {\n" +" .m_base = PyModuleDef_HEAD_INIT,\n" +" .m_name = \"custom4\",\n" +" .m_doc = \"Example module that creates an extension type.\",\n" +" .m_size = -1,\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_custom4(void)\n" +"{\n" +" PyObject *m;\n" +" if (PyType_Ready(&CustomType) < 0)\n" +" return NULL;\n" +"\n" +" m = PyModule_Create(&custommodule);\n" +" if (m == NULL)\n" +" return NULL;\n" +"\n" +" if (PyModule_AddObjectRef(m, \"Custom\", (PyObject *) &CustomType) < 0) " +"{\n" +" Py_DECREF(m);\n" +" return NULL;\n" +" }\n" +"\n" +" return m;\n" +"}\n" +msgstr "" + #: extending/newtypes_tutorial.rst:690 msgid "" "First, the traversal method lets the cyclic GC know about subobjects that " "could participate in cycles::" msgstr "" +#: extending/newtypes_tutorial.rst:693 +msgid "" +"static int\n" +"Custom_traverse(CustomObject *self, visitproc visit, void *arg)\n" +"{\n" +" int vret;\n" +" if (self->first) {\n" +" vret = visit(self->first, arg);\n" +" if (vret != 0)\n" +" return vret;\n" +" }\n" +" if (self->last) {\n" +" vret = visit(self->last, arg);\n" +" if (vret != 0)\n" +" return vret;\n" +" }\n" +" return 0;\n" +"}" +msgstr "" + #: extending/newtypes_tutorial.rst:710 msgid "" "For each subobject that can participate in cycles, we need to call the :c:" @@ -680,6 +1630,17 @@ msgid "" "boilerplate in ``Custom_traverse``::" msgstr "" +#: extending/newtypes_tutorial.rst:720 +msgid "" +"static int\n" +"Custom_traverse(CustomObject *self, visitproc visit, void *arg)\n" +"{\n" +" Py_VISIT(self->first);\n" +" Py_VISIT(self->last);\n" +" return 0;\n" +"}" +msgstr "" + #: extending/newtypes_tutorial.rst:729 msgid "" "The :c:member:`~PyTypeObject.tp_traverse` implementation must name its " @@ -692,6 +1653,17 @@ msgid "" "participate in cycles::" msgstr "" +#: extending/newtypes_tutorial.rst:735 +msgid "" +"static int\n" +"Custom_clear(CustomObject *self)\n" +"{\n" +" Py_CLEAR(self->first);\n" +" Py_CLEAR(self->last);\n" +" return 0;\n" +"}" +msgstr "" + #: extending/newtypes_tutorial.rst:743 msgid "" "Notice the use of the :c:func:`Py_CLEAR` macro. It is the recommended and " @@ -706,6 +1678,14 @@ msgstr "" msgid "You could emulate :c:func:`Py_CLEAR` by writing::" msgstr "" +#: extending/newtypes_tutorial.rst:753 +msgid "" +"PyObject *tmp;\n" +"tmp = self->first;\n" +"self->first = NULL;\n" +"Py_XDECREF(tmp);" +msgstr "" + #: extending/newtypes_tutorial.rst:758 msgid "" "Nevertheless, it is much easier and less error-prone to always use :c:func:" @@ -723,11 +1703,27 @@ msgid "" "`PyObject_GC_UnTrack` and ``Custom_clear``::" msgstr "" +#: extending/newtypes_tutorial.rst:769 +msgid "" +"static void\n" +"Custom_dealloc(CustomObject *self)\n" +"{\n" +" PyObject_GC_UnTrack(self);\n" +" Custom_clear(self);\n" +" Py_TYPE(self)->tp_free((PyObject *) self);\n" +"}" +msgstr "" + #: extending/newtypes_tutorial.rst:777 msgid "" "Finally, we add the :c:macro:`Py_TPFLAGS_HAVE_GC` flag to the class flags::" msgstr "" +#: extending/newtypes_tutorial.rst:779 +msgid "" +".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC," +msgstr "" + #: extending/newtypes_tutorial.rst:781 msgid "" "That's pretty much it. If we had written custom :c:member:`~PyTypeObject." @@ -756,6 +1752,93 @@ msgid "" "that increases an internal counter:" msgstr "" +#: extending/newtypes_tutorial.rst:799 +msgid "" +">>> import sublist\n" +">>> s = sublist.SubList(range(3))\n" +">>> s.extend(s)\n" +">>> print(len(s))\n" +"6\n" +">>> print(s.increment())\n" +"1\n" +">>> print(s.increment())\n" +"2" +msgstr "" + +#: extending/newtypes_tutorial.rst:811 +msgid "" +"#define PY_SSIZE_T_CLEAN\n" +"#include \n" +"\n" +"typedef struct {\n" +" PyListObject list;\n" +" int state;\n" +"} SubListObject;\n" +"\n" +"static PyObject *\n" +"SubList_increment(SubListObject *self, PyObject *unused)\n" +"{\n" +" self->state++;\n" +" return PyLong_FromLong(self->state);\n" +"}\n" +"\n" +"static PyMethodDef SubList_methods[] = {\n" +" {\"increment\", (PyCFunction) SubList_increment, METH_NOARGS,\n" +" PyDoc_STR(\"increment state counter\")},\n" +" {NULL},\n" +"};\n" +"\n" +"static int\n" +"SubList_init(SubListObject *self, PyObject *args, PyObject *kwds)\n" +"{\n" +" if (PyList_Type.tp_init((PyObject *) self, args, kwds) < 0)\n" +" return -1;\n" +" self->state = 0;\n" +" return 0;\n" +"}\n" +"\n" +"static PyTypeObject SubListType = {\n" +" PyVarObject_HEAD_INIT(NULL, 0)\n" +" .tp_name = \"sublist.SubList\",\n" +" .tp_doc = PyDoc_STR(\"SubList objects\"),\n" +" .tp_basicsize = sizeof(SubListObject),\n" +" .tp_itemsize = 0,\n" +" .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,\n" +" .tp_init = (initproc) SubList_init,\n" +" .tp_methods = SubList_methods,\n" +"};\n" +"\n" +"static PyModuleDef sublistmodule = {\n" +" PyModuleDef_HEAD_INIT,\n" +" .m_name = \"sublist\",\n" +" .m_doc = \"Example module that creates an extension type.\",\n" +" .m_size = -1,\n" +"};\n" +"\n" +"PyMODINIT_FUNC\n" +"PyInit_sublist(void)\n" +"{\n" +" PyObject *m;\n" +" SubListType.tp_base = &PyList_Type;\n" +" if (PyType_Ready(&SubListType) < 0)\n" +" return NULL;\n" +"\n" +" m = PyModule_Create(&sublistmodule);\n" +" if (m == NULL)\n" +" return NULL;\n" +"\n" +" Py_INCREF(&SubListType);\n" +" if (PyModule_AddObject(m, \"SubList\", (PyObject *) &SubListType) < 0) " +"{\n" +" Py_DECREF(&SubListType);\n" +" Py_DECREF(m);\n" +" return NULL;\n" +" }\n" +"\n" +" return m;\n" +"}\n" +msgstr "" + #: extending/newtypes_tutorial.rst:814 msgid "" "As you can see, the source code closely resembles the :class:`!Custom` " @@ -763,6 +1846,14 @@ msgid "" "between them. ::" msgstr "" +#: extending/newtypes_tutorial.rst:817 +msgid "" +"typedef struct {\n" +" PyListObject list;\n" +" int state;\n" +"} SubListObject;" +msgstr "" + #: extending/newtypes_tutorial.rst:822 msgid "" "The primary difference for derived type objects is that the base type's " @@ -777,6 +1868,18 @@ msgid "" "*``::" msgstr "" +#: extending/newtypes_tutorial.rst:829 +msgid "" +"static int\n" +"SubList_init(SubListObject *self, PyObject *args, PyObject *kwds)\n" +"{\n" +" if (PyList_Type.tp_init((PyObject *) self, args, kwds) < 0)\n" +" return -1;\n" +" self->state = 0;\n" +" return 0;\n" +"}" +msgstr "" + #: extending/newtypes_tutorial.rst:838 msgid "" "We see above how to call through to the :meth:`~object.__init__` method of " @@ -801,6 +1904,32 @@ msgid "" "function::" msgstr "" +#: extending/newtypes_tutorial.rst:853 +msgid "" +"PyMODINIT_FUNC\n" +"PyInit_sublist(void)\n" +"{\n" +" PyObject* m;\n" +" SubListType.tp_base = &PyList_Type;\n" +" if (PyType_Ready(&SubListType) < 0)\n" +" return NULL;\n" +"\n" +" m = PyModule_Create(&sublistmodule);\n" +" if (m == NULL)\n" +" return NULL;\n" +"\n" +" Py_INCREF(&SubListType);\n" +" if (PyModule_AddObject(m, \"SubList\", (PyObject *) &SubListType) < 0) " +"{\n" +" Py_DECREF(&SubListType);\n" +" Py_DECREF(m);\n" +" return NULL;\n" +" }\n" +"\n" +" return m;\n" +"}" +msgstr "" + #: extending/newtypes_tutorial.rst:875 msgid "" "Before calling :c:func:`PyType_Ready`, the type structure must have the :c:" diff --git a/extending/windows.po b/extending/windows.po index 89e19bf2c..90bd2dc54 100644 --- a/extending/windows.po +++ b/extending/windows.po @@ -6,7 +6,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-10-01 00:18+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: 2023-10-03 01:11+0300\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -227,6 +227,12 @@ msgstr "" "geçirmelisiniz. İki DLL oluşturmak için, spam ve ni (spam içinde bulunan C " "fonksiyonlarını kullanır), şu komutları kullanabilirsiniz::" +#: extending/windows.rst:115 +msgid "" +"cl /LD /I/python/include spam.c ../libs/pythonXY.lib\n" +"cl /LD /I/python/include ni.c spam.lib ../libs/pythonXY.lib" +msgstr "" + #: extending/windows.rst:118 msgid "" "The first command created three files: :file:`spam.obj`, :file:`spam.dll` " diff --git a/faq/design.po b/faq/design.po index f1e8c11dd..1d44b5423 100644 --- a/faq/design.po +++ b/faq/design.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -42,6 +42,14 @@ msgid "" "programmers will encounter a fragment of code like this::" msgstr "" +#: faq/design.rst:21 +msgid "" +"if (x <= y)\n" +" x++;\n" +" y--;\n" +"z++;" +msgstr "" + #: faq/design.rst:26 msgid "" "Only the ``x++`` statement is executed if the condition is true, but the " @@ -86,6 +94,12 @@ msgstr "" msgid "Users are often surprised by results like this::" msgstr "" +#: faq/design.rst:58 +msgid "" +">>> 1.2 - 1.0\n" +"0.19999999999999996" +msgstr "" + #: faq/design.rst:61 msgid "" "and think it is a bug in Python. It's not. This has little to do with " @@ -109,6 +123,10 @@ msgid "" "expressed exactly in binary floating point. For example, after::" msgstr "" +#: faq/design.rst:75 +msgid ">>> x = 1.2" +msgstr "" + #: faq/design.rst:77 msgid "" "the value stored for ``x`` is a (very good) approximation to the decimal " @@ -116,10 +134,18 @@ msgid "" "actual stored value is::" msgstr "" +#: faq/design.rst:81 +msgid "1.0011001100110011001100110011001100110011001100110011 (binary)" +msgstr "" + #: faq/design.rst:83 msgid "which is exactly::" msgstr "" +#: faq/design.rst:85 +msgid "1.1999999999999999555910790149937383830547332763671875 (decimal)" +msgstr "" + #: faq/design.rst:87 msgid "" "The typical precision of 53 bits provides Python floats with 15--16 decimal " @@ -223,6 +249,12 @@ msgid "" "an expression::" msgstr "" +#: faq/design.rst:161 +msgid "" +"while chunk := fp.read(200):\n" +" print(chunk)" +msgstr "" + #: faq/design.rst:164 msgid "See :pep:`572` for more information." msgstr "" @@ -275,10 +307,18 @@ msgid "" "programmers feel uncomfortable is::" msgstr "" +#: faq/design.rst:201 +msgid "\", \".join(['1', '2', '4', '8', '16'])" +msgstr "" + #: faq/design.rst:203 msgid "which gives the result::" msgstr "" +#: faq/design.rst:205 +msgid "\"1, 2, 4, 8, 16\"" +msgstr "" + #: faq/design.rst:207 msgid "There are two common arguments against this usage." msgstr "" @@ -300,6 +340,10 @@ msgid "" "`~str.split` as a string method, since in that case it is easy to see that ::" msgstr "" +#: faq/design.rst:220 +msgid "\"1, 2, 4, 8, 16\".split(\", \")" +msgstr "" + #: faq/design.rst:222 msgid "" "is an instruction to a string literal to return the substrings delimited by " @@ -326,12 +370,29 @@ msgid "" "versions of Python prior to 2.0 it was common to use this idiom::" msgstr "" +#: faq/design.rst:240 +msgid "" +"try:\n" +" value = mydict[key]\n" +"except KeyError:\n" +" mydict[key] = getvalue(key)\n" +" value = mydict[key]" +msgstr "" + #: faq/design.rst:246 msgid "" "This only made sense when you expected the dict to have the key almost all " "the time. If that wasn't the case, you coded it like this::" msgstr "" +#: faq/design.rst:249 +msgid "" +"if key in mydict:\n" +" value = mydict[key]\n" +"else:\n" +" value = mydict[key] = getvalue(key)" +msgstr "" + #: faq/design.rst:254 msgid "" "For this specific case, you could also use ``value = dict.setdefault(key, " @@ -359,12 +420,34 @@ msgid "" "to call. For example::" msgstr "" +#: faq/design.rst:272 +msgid "" +"functions = {'a': function_1,\n" +" 'b': function_2,\n" +" 'c': self.method_1}\n" +"\n" +"func = functions[value]\n" +"func()" +msgstr "" + #: faq/design.rst:279 msgid "" "For calling methods on objects, you can simplify yet further by using the :" "func:`getattr` built-in to retrieve methods with a particular name::" msgstr "" +#: faq/design.rst:282 +msgid "" +"class MyVisitor:\n" +" def visit_a(self):\n" +" ...\n" +"\n" +" def dispatch(self, value):\n" +" method_name = 'visit_' + str(value)\n" +" method = getattr(self, method_name)\n" +" method()" +msgstr "" + #: faq/design.rst:291 msgid "" "It's suggested that you use a prefix for the method names, such as " @@ -430,8 +513,8 @@ msgstr "" #: faq/design.rst:330 msgid "" "`Cython `_ compiles a modified version of Python with " -"optional annotations into C extensions. `Nuitka `_ " -"is an up-and-coming compiler of Python into C++ code, aiming to support the " +"optional annotations into C extensions. `Nuitka `_ is " +"an up-and-coming compiler of Python into C++ code, aiming to support the " "full Python language." msgstr "" @@ -453,10 +536,10 @@ msgstr "" #: faq/design.rst:347 msgid "" "Other implementations (such as `Jython `_ or `PyPy " -"`_), however, can rely on a different mechanism such " -"as a full-blown garbage collector. This difference can cause some subtle " -"porting problems if your Python code depends on the behavior of the " -"reference counting implementation." +"`_), however, can rely on a different mechanism such as a " +"full-blown garbage collector. This difference can cause some subtle porting " +"problems if your Python code depends on the behavior of the reference " +"counting implementation." msgstr "" #: faq/design.rst:353 @@ -465,6 +548,13 @@ msgid "" "CPython) will probably run out of file descriptors::" msgstr "" +#: faq/design.rst:356 +msgid "" +"for file in very_long_list_of_files:\n" +" f = open(file)\n" +" c = f.read(1)" +msgstr "" + #: faq/design.rst:360 msgid "" "Indeed, using CPython's reference counting and destructor scheme, each new " @@ -480,6 +570,13 @@ msgid "" "will work regardless of memory management scheme::" msgstr "" +#: faq/design.rst:369 +msgid "" +"for file in very_long_list_of_files:\n" +" with open(file) as f:\n" +" c = f.read(1)" +msgstr "" + #: faq/design.rst:375 msgid "Why doesn't CPython use a more traditional garbage collection scheme?" msgstr "" @@ -643,6 +740,12 @@ msgid "" "construct a new list with the same value it won't be found; e.g.::" msgstr "" +#: faq/design.rst:483 +msgid "" +"mydict = {[1, 2]: '12'}\n" +"print(mydict[[1, 2]])" +msgstr "" + #: faq/design.rst:486 msgid "" "would raise a :exc:`KeyError` exception because the id of the ``[1, 2]`` " @@ -686,6 +789,26 @@ msgid "" "the object is in the dictionary (or other structure). ::" msgstr "" +#: faq/design.rst:513 +msgid "" +"class ListWrapper:\n" +" def __init__(self, the_list):\n" +" self.the_list = the_list\n" +"\n" +" def __eq__(self, other):\n" +" return self.the_list == other.the_list\n" +"\n" +" def __hash__(self):\n" +" l = self.the_list\n" +" result = 98767 - len(l)*555\n" +" for i, el in enumerate(l):\n" +" try:\n" +" result = result + (hash(el) % 9999999) * 1001 + i\n" +" except Exception:\n" +" result = (result % 7777777) + i * 333\n" +" return result" +msgstr "" + #: faq/design.rst:530 msgid "" "Note that the hash computation is complicated by the possibility that some " @@ -732,6 +855,12 @@ msgid "" "dictionary in sorted order::" msgstr "" +#: faq/design.rst:559 +msgid "" +"for key in sorted(mydict):\n" +" ... # do whatever with mydict[key]..." +msgstr "" + #: faq/design.rst:564 msgid "How do you specify and enforce an interface spec in Python?" msgstr "" @@ -816,6 +945,19 @@ msgid "" "other languages. For example::" msgstr "" +#: faq/design.rst:620 +msgid "" +"class label(Exception): pass # declare a label\n" +"\n" +"try:\n" +" ...\n" +" if condition: raise label() # goto label\n" +" ...\n" +"except label: # where to goto\n" +" pass\n" +"..." +msgstr "" + #: faq/design.rst:630 msgid "" "This doesn't allow you to jump into the middle of a loop, but that's usually " @@ -849,11 +991,22 @@ msgid "" "calls accept forward slashes too::" msgstr "" +#: faq/design.rst:651 +msgid "f = open(\"/mydir/file.txt\") # works fine!" +msgstr "" + #: faq/design.rst:653 msgid "" "If you're trying to build a pathname for a DOS command, try e.g. one of ::" msgstr "" +#: faq/design.rst:655 +msgid "" +"dir = r\"\\this\\is\\my\\dos\\dir\" \"\\\\\"\n" +"dir = r\"\\this\\is\\my\\dos\\dir\\ \"[:-1]\n" +"dir = \"\\\\this\\\\is\\\\my\\\\dos\\\\dir\\\\\"" +msgstr "" + #: faq/design.rst:661 msgid "Why doesn't Python have a \"with\" statement for attribute assignments?" msgstr "" @@ -865,6 +1018,13 @@ msgid "" "construct that looks like this::" msgstr "" +#: faq/design.rst:667 +msgid "" +"with obj:\n" +" a = 1 # equivalent to obj.a = 1\n" +" total = total + 1 # obj.total = obj.total + 1" +msgstr "" + #: faq/design.rst:671 msgid "In Python, such a construct would be ambiguous." msgstr "" @@ -890,6 +1050,13 @@ msgstr "" msgid "For instance, take the following incomplete snippet::" msgstr "" +#: faq/design.rst:686 +msgid "" +"def foo(a):\n" +" with a:\n" +" print(x)" +msgstr "" + #: faq/design.rst:690 msgid "" "The snippet assumes that ``a`` must have a member attribute called ``x``. " @@ -906,10 +1073,25 @@ msgid "" "assignment. Instead of::" msgstr "" +#: faq/design.rst:699 +msgid "" +"function(args).mydict[index][index].a = 21\n" +"function(args).mydict[index][index].b = 42\n" +"function(args).mydict[index][index].c = 63" +msgstr "" + #: faq/design.rst:703 msgid "write this::" msgstr "" +#: faq/design.rst:705 +msgid "" +"ref = function(args).mydict[index][index]\n" +"ref.a = 21\n" +"ref.b = 42\n" +"ref.c = 63" +msgstr "" + #: faq/design.rst:710 msgid "" "This also has the side-effect of increasing execution speed because name " @@ -947,10 +1129,22 @@ msgid "" "of the experimental ABC language). Consider this::" msgstr "" +#: faq/design.rst:735 +msgid "" +"if a == b\n" +" print(a)" +msgstr "" + #: faq/design.rst:738 msgid "versus ::" msgstr "" +#: faq/design.rst:740 +msgid "" +"if a == b:\n" +" print(a)" +msgstr "" + #: faq/design.rst:743 msgid "" "Notice how the second one is slightly easier to read. Notice further how a " @@ -976,6 +1170,16 @@ msgid "" "dictionaries::" msgstr "" +#: faq/design.rst:757 +msgid "" +"[1, 2, 3,]\n" +"('a', 'b', 'c',)\n" +"d = {\n" +" \"A\": [1, 5],\n" +" \"B\": [6, 7], # last trailing comma is optional but good style\n" +"}" +msgstr "" + #: faq/design.rst:765 msgid "There are several reasons to allow this." msgstr "" @@ -994,6 +1198,16 @@ msgid "" "diagnose. For example::" msgstr "" +#: faq/design.rst:775 +msgid "" +"x = [\n" +" \"fee\",\n" +" \"fie\"\n" +" \"foo\",\n" +" \"fum\"\n" +"]" +msgstr "" + #: faq/design.rst:782 msgid "" "This list looks like it has four elements, but it actually contains three: " diff --git a/faq/extending.po b/faq/extending.po index 523375a26..69d77189b 100644 --- a/faq/extending.po +++ b/faq/extending.po @@ -6,7 +6,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-04-01 00:17+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: 2022-12-29 00:43-0500\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -223,6 +223,13 @@ msgstr "" "c:func:`Py_BuildValue` ile kullanılan gibi bir string ve değişken " "değerleridir::" +#: faq/extending.rst:117 +msgid "" +"PyObject *\n" +"PyObject_CallMethod(PyObject *object, const char *method_name,\n" +" const char *arg_format, ...);" +msgstr "" + #: faq/extending.rst:121 msgid "" "This works for any object that has methods -- whether built-in or user-" @@ -241,6 +248,17 @@ msgstr "" "Örneğin, bir dosya nesnesinin \"seek\" yöntemini 10, 0 argümanlarıyla " "çağırmak için (dosya nesnesi işaretçisinin \"f\" olduğunu varsayarak)::" +#: faq/extending.rst:127 +msgid "" +"res = PyObject_CallMethod(f, \"seek\", \"(ii)\", 10, 0);\n" +"if (res == NULL) {\n" +" ... an exception occurred ...\n" +"}\n" +"else {\n" +" Py_DECREF(res);\n" +"}" +msgstr "" + #: faq/extending.rst:135 msgid "" "Note that since :c:func:`PyObject_CallObject` *always* wants a tuple for the " @@ -279,10 +297,39 @@ msgid "The easiest way to do this is to use the :class:`io.StringIO` class:" msgstr "" "Bunu yapmanın en kolay yolu :class:`io.StringIO` sınıfını kullanmaktır:" +#: faq/extending.rst:151 +msgid "" +">>> import io, sys\n" +">>> sys.stdout = io.StringIO()\n" +">>> print('foo')\n" +">>> print('hello world!')\n" +">>> sys.stderr.write(sys.stdout.getvalue())\n" +"foo\n" +"hello world!" +msgstr "" + #: faq/extending.rst:161 msgid "A custom object to do the same would look like this:" msgstr "Aynı şeyi yapan özel bir nesne şöyle görünecektir:" +#: faq/extending.rst:163 +msgid "" +">>> import io, sys\n" +">>> class StdoutCatcher(io.TextIOBase):\n" +"... def __init__(self):\n" +"... self.data = []\n" +"... def write(self, stuff):\n" +"... self.data.append(stuff)\n" +"...\n" +">>> import sys\n" +">>> sys.stdout = StdoutCatcher()\n" +">>> print('foo')\n" +">>> print('hello world!')\n" +">>> sys.stderr.write(''.join(sys.stdout.data))\n" +"foo\n" +"hello world!" +msgstr "" + #: faq/extending.rst:182 msgid "How do I access a module written in Python from C?" msgstr "Python'da yazılmış bir modüle C'den nasıl erişebilirim?" @@ -291,6 +338,10 @@ msgstr "Python'da yazılmış bir modüle C'den nasıl erişebilirim?" msgid "You can get a pointer to the module object as follows::" msgstr "Modül nesnesine aşağıdaki gibi bir işaretçi alabilirsiniz::" +#: faq/extending.rst:186 +msgid "module = PyImport_ImportModule(\"\");" +msgstr "" + #: faq/extending.rst:188 msgid "" "If the module hasn't been imported yet (i.e. it is not yet present in :data:" @@ -313,6 +364,10 @@ msgstr "" "Daha sonra modülün özniteliklerine (yani modülde tanımlanan herhangi bir " "isme) aşağıdaki şekilde erişebilirsiniz::" +#: faq/extending.rst:197 +msgid "attr = PyObject_GetAttrString(module, \"\");" +msgstr "" + #: faq/extending.rst:199 msgid "" "Calling :c:func:`PyObject_SetAttrString` to assign to variables in the " @@ -377,10 +432,24 @@ msgstr "" msgid "In your ``.gdbinit`` file (or interactively), add the command:" msgstr "``.gdbinit`` dosyanıza (veya etkileşimli olarak) şu komutu ekleyin:" +#: faq/extending.rst:231 +msgid "br _PyImport_LoadDynamicModule" +msgstr "" + #: faq/extending.rst:235 msgid "Then, when you run GDB:" msgstr "Sonra, GDB'yi çalıştırdığınızda:" +#: faq/extending.rst:237 +msgid "" +"$ gdb /local/bin/python\n" +"gdb) run myscript.py\n" +"gdb) continue # repeat until your extension is loaded\n" +"gdb) finish # so that your extension is loaded\n" +"gdb) br myfunction.c:50\n" +"gdb) continue" +msgstr "" + #: faq/extending.rst:247 msgid "" "I want to compile a Python module on my Linux system, but some files are " @@ -390,28 +459,30 @@ msgstr "" "eksik. Neden?" #: faq/extending.rst:249 +#, fuzzy msgid "" -"Most packaged versions of Python don't include the :file:`/usr/lib/python2." -"{x}/config/` directory, which contains various files required for compiling " +"Most packaged versions of Python omit some files required for compiling " "Python extensions." msgstr "" "Python'un paketlenmiş sürümlerinin çoğu, Python uzantılarını derlemek için " "gerekli çeşitli dosyaları içeren :file:`/usr/lib/python2.{x}/config/` " "dizinini içermez." -#: faq/extending.rst:253 -msgid "For Red Hat, install the python-devel RPM to get the necessary files." +#: faq/extending.rst:252 +#, fuzzy +msgid "For Red Hat, install the python3-devel RPM to get the necessary files." msgstr "Red Hat için, gerekli dosyaları almak için python-devel RPM yükleyin." -#: faq/extending.rst:255 -msgid "For Debian, run ``apt-get install python-dev``." +#: faq/extending.rst:254 +#, fuzzy +msgid "For Debian, run ``apt-get install python3-dev``." msgstr "Debian için ``apt-get install python-dev`` komutunu çalıştırın." -#: faq/extending.rst:258 +#: faq/extending.rst:257 msgid "How do I tell \"incomplete input\" from \"invalid input\"?" msgstr "\"Eksik girdi\" ile \"geçersiz girdi'yi nasıl ayırt edebilirim?" -#: faq/extending.rst:260 +#: faq/extending.rst:259 msgid "" "Sometimes you want to emulate the Python interactive interpreter's behavior, " "where it gives you a continuation prompt when the input is incomplete (e.g. " @@ -425,7 +496,7 @@ msgstr "" "tırnaklarınızı kapatmadınız), ancak girdi geçersiz olduğunda size hemen bir " "sözdizimi hata mesajı verir." -#: faq/extending.rst:266 +#: faq/extending.rst:265 msgid "" "In Python you can use the :mod:`codeop` module, which approximates the " "parser's behavior sufficiently. IDLE uses this, for example." @@ -433,7 +504,7 @@ msgstr "" "Python'da, ayrıştırıcının davranışına yeterince yaklaşan :mod:`codeop` " "modülünü kullanabilirsiniz. Örneğin IDLE bunu kullanır." -#: faq/extending.rst:269 +#: faq/extending.rst:268 msgid "" "The easiest way to do it in C is to call :c:func:`PyRun_InteractiveLoop` " "(perhaps in a separate thread) and let the Python interpreter handle the " @@ -448,13 +519,13 @@ msgstr "" "şekilde ayarlayabilirsiniz. Daha fazla ipucu için ``Modules/readline.c`` ve " "``Parser/myreadline.c`` dosyalarına bakın." -#: faq/extending.rst:276 +#: faq/extending.rst:275 msgid "How do I find undefined g++ symbols __builtin_new or __pure_virtual?" msgstr "" "Tanımlanmamış g++ sembolleri __builtin_new veya __pure_virtual'ı nasıl " "bulabilirim?" -#: faq/extending.rst:278 +#: faq/extending.rst:277 msgid "" "To dynamically load g++ extension modules, you must recompile Python, relink " "it using g++ (change LINKCC in the Python Modules Makefile), and link your " @@ -465,7 +536,7 @@ msgstr "" "LINKCC'yi değiştirin) ve uzantı modülünüzü g++ kullanarak bağlamalısınız " "(örneğin, ``g++ -shared -o mymodule.so mymodule.o``)." -#: faq/extending.rst:284 +#: faq/extending.rst:283 msgid "" "Can I create an object class with some methods implemented in C and others " "in Python (e.g. through inheritance)?" @@ -473,7 +544,7 @@ msgstr "" "Bazı yöntemleri C'de, bazı yöntemleri Python'da (örneğin miras yoluyla) " "uygulanan bir nesne sınıfı oluşturabilir miyim?" -#: faq/extending.rst:286 +#: faq/extending.rst:285 msgid "" "Yes, you can inherit from built-in classes such as :class:`int`, :class:" "`list`, :class:`dict`, etc." @@ -481,7 +552,7 @@ msgstr "" "Evet, :class:`int`, :class:`list`, :class:`dict`, vb. gibi yerleşik " "sınıflardan miras alabilirsiniz." -#: faq/extending.rst:289 +#: faq/extending.rst:288 msgid "" "The Boost Python Library (BPL, https://www.boost.org/libs/python/doc/index." "html) provides a way of doing this from C++ (i.e. you can inherit from an " diff --git a/faq/general.po b/faq/general.po index 101138d32..a4f73ce1a 100644 --- a/faq/general.po +++ b/faq/general.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -486,40 +486,39 @@ msgstr "" #: faq/general.rst:311 msgid "" "The latest stable releases can always be found on the `Python download page " -"`_. There are two production-ready " -"versions of Python: 2.x and 3.x. The recommended version is 3.x, which is " -"supported by most widely used libraries. Although 2.x is still widely used, " -"`it is not maintained anymore `_." +"`_. Python 3.x is the recommended version " +"and supported by most widely used libraries. Python 2.x :pep:`is not " +"maintained anymore <373>`." msgstr "" -#: faq/general.rst:318 +#: faq/general.rst:317 msgid "How many people are using Python?" msgstr "" -#: faq/general.rst:320 +#: faq/general.rst:319 msgid "" "There are probably millions of users, though it's difficult to obtain an " "exact count." msgstr "" -#: faq/general.rst:323 +#: faq/general.rst:322 msgid "" "Python is available for free download, so there are no sales figures, and " "it's available from many different sites and packaged with many Linux " "distributions, so download statistics don't tell the whole story either." msgstr "" -#: faq/general.rst:327 +#: faq/general.rst:326 msgid "" "The comp.lang.python newsgroup is very active, but not all Python users post " "to the group or even read it." msgstr "" -#: faq/general.rst:332 +#: faq/general.rst:331 msgid "Have any significant projects been done in Python?" msgstr "" -#: faq/general.rst:334 +#: faq/general.rst:333 msgid "" "See https://www.python.org/about/success for a list of projects that use " "Python. Consulting the proceedings for `past Python conferences `_ and `the Zope application server `_." msgstr "" -#: faq/general.rst:361 +#: faq/general.rst:360 msgid "Is it reasonable to propose incompatible changes to Python?" msgstr "" -#: faq/general.rst:363 +#: faq/general.rst:362 msgid "" "In general, no. There are already millions of lines of Python code around " "the world, so any change in the language that invalidates more than a very " @@ -570,22 +569,22 @@ msgid "" "to invalidate them all at a single stroke." msgstr "" -#: faq/general.rst:370 +#: faq/general.rst:369 msgid "" "Providing a gradual upgrade path is necessary if a feature has to be " "changed. :pep:`5` describes the procedure followed for introducing backward-" "incompatible changes while minimizing disruption for users." msgstr "" -#: faq/general.rst:376 +#: faq/general.rst:375 msgid "Is Python a good language for beginning programmers?" msgstr "" -#: faq/general.rst:378 +#: faq/general.rst:377 msgid "Yes." msgstr "" -#: faq/general.rst:380 +#: faq/general.rst:379 msgid "" "It is still common to start students with a procedural and statically typed " "language such as Pascal, C, or a subset of C++ or Java. Students may be " @@ -598,7 +597,7 @@ msgid "" "with user-defined objects in their very first course." msgstr "" -#: faq/general.rst:390 +#: faq/general.rst:389 msgid "" "For a student who has never programmed before, using a statically typed " "language seems unnatural. It presents additional complexity that the " @@ -610,7 +609,7 @@ msgid "" "course." msgstr "" -#: faq/general.rst:398 +#: faq/general.rst:397 msgid "" "Many other aspects of Python make it a good first language. Like Java, " "Python has a large standard library so that students can be assigned " @@ -623,7 +622,7 @@ msgid "" "helpful in extending the students' reach." msgstr "" -#: faq/general.rst:407 +#: faq/general.rst:406 msgid "" "Python's interactive interpreter enables students to test language features " "while they're programming. They can keep a window with the interpreter " @@ -631,13 +630,41 @@ msgid "" "can't remember the methods for a list, they can do something like this::" msgstr "" -#: faq/general.rst:436 +#: faq/general.rst:411 +msgid "" +">>> L = []\n" +">>> dir(L) \n" +"['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',\n" +"'__dir__', '__doc__', '__eq__', '__format__', '__ge__',\n" +"'__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__',\n" +"'__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__',\n" +"'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',\n" +"'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__',\n" +"'__sizeof__', '__str__', '__subclasshook__', 'append', 'clear',\n" +"'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove',\n" +"'reverse', 'sort']\n" +">>> [d for d in dir(L) if '__' not in d]\n" +"['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', " +"'remove', 'reverse', 'sort']\n" +"\n" +">>> help(L.append)\n" +"Help on built-in function append:\n" +"\n" +"append(...)\n" +" L.append(object) -> None -- append object to end\n" +"\n" +">>> L.append(1)\n" +">>> L\n" +"[1]" +msgstr "" + +#: faq/general.rst:435 msgid "" "With the interpreter, documentation is never far from the student as they " "are programming." msgstr "" -#: faq/general.rst:439 +#: faq/general.rst:438 msgid "" "There are also good IDEs for Python. IDLE is a cross-platform IDE for " "Python that is written in Python using Tkinter. Emacs users will be happy to " @@ -648,7 +675,7 @@ msgid "" "Python editing environments." msgstr "" -#: faq/general.rst:447 +#: faq/general.rst:446 msgid "" "If you want to discuss Python's use in education, you may be interested in " "joining `the edu-sig mailing list \n" @@ -79,6 +79,12 @@ msgid "" "these, type::" msgstr "" +#: faq/library.rst:42 +msgid "" +"import sys\n" +"print(sys.builtin_module_names)" +msgstr "" + #: faq/library.rst:47 msgid "How do I make a Python script executable on Unix?" msgstr "" @@ -102,6 +108,10 @@ msgid "" "to write ::" msgstr "" +#: faq/library.rst:59 +msgid "#!/usr/local/bin/python" +msgstr "" + #: faq/library.rst:61 msgid "" "as the very first line of your file, using the pathname for where the Python " @@ -116,6 +126,10 @@ msgid "" "directory on the user's :envvar:`PATH`::" msgstr "" +#: faq/library.rst:69 +msgid "#!/usr/bin/env python" +msgstr "" + #: faq/library.rst:71 msgid "" "*Don't* do this for CGI scripts. The :envvar:`PATH` variable for CGI " @@ -130,12 +144,24 @@ msgid "" "try the following hack (due to Alex Rezinsky):" msgstr "" +#: faq/library.rst:79 +msgid "" +"#! /bin/sh\n" +"\"\"\":\"\n" +"exec python $0 ${1+\"$@\"}\n" +"\"\"\"" +msgstr "" + #: faq/library.rst:86 msgid "" "The minor disadvantage is that this defines the script's __doc__ string. " "However, you can fix that by adding ::" msgstr "" +#: faq/library.rst:89 +msgid "__doc__ = \"\"\"...Whatever...\"\"\"" +msgstr "" + #: faq/library.rst:94 msgid "Is there a curses/termcap package for Python?" msgstr "" @@ -178,10 +204,20 @@ msgid "" "wrong argument list. It is called as ::" msgstr "" +#: faq/library.rst:123 +msgid "handler(signum, frame)" +msgstr "" + #: faq/library.rst:125 msgid "so it should be declared with two parameters::" msgstr "" +#: faq/library.rst:127 +msgid "" +"def handler(signum, frame):\n" +" ..." +msgstr "" + #: faq/library.rst:132 msgid "Common tasks" msgstr "" @@ -218,6 +254,12 @@ msgstr "" msgid "The \"global main logic\" of your program may be as simple as ::" msgstr "" +#: faq/library.rst:154 +msgid "" +"if __name__ == \"__main__\":\n" +" main_logic()" +msgstr "" + #: faq/library.rst:157 msgid "at the bottom of the main module of your program." msgstr "" @@ -240,6 +282,12 @@ msgid "" "may include a self-test of the module. ::" msgstr "" +#: faq/library.rst:170 +msgid "" +"if __name__ == \"__main__\":\n" +" self_test()" +msgstr "" + #: faq/library.rst:173 msgid "" "Even programs that interact with complex external interfaces may be tested " @@ -300,6 +348,21 @@ msgid "" "for all the threads to finish::" msgstr "" +#: faq/library.rst:253 +msgid "" +"import threading, time\n" +"\n" +"def thread_task(name, n):\n" +" for i in range(n):\n" +" print(name, i)\n" +"\n" +"for i in range(10):\n" +" T = threading.Thread(target=thread_task, args=(str(i), i))\n" +" T.start()\n" +"\n" +"time.sleep(10) # <---------------------------!" +msgstr "" + #: faq/library.rst:265 msgid "" "But now (on many platforms) the threads don't run in parallel, but appear to " @@ -311,6 +374,20 @@ msgstr "" msgid "A simple fix is to add a tiny sleep to the start of the run function::" msgstr "" +#: faq/library.rst:271 +msgid "" +"def thread_task(name, n):\n" +" time.sleep(0.001) # <--------------------!\n" +" for i in range(n):\n" +" print(name, i)\n" +"\n" +"for i in range(10):\n" +" T = threading.Thread(target=thread_task, args=(str(i), i))\n" +" T.start()\n" +"\n" +"time.sleep(10)" +msgstr "" + #: faq/library.rst:282 msgid "" "Instead of trying to guess a good delay value for :func:`time.sleep`, it's " @@ -344,10 +421,66 @@ msgstr "" msgid "Here's a trivial example::" msgstr "" +#: faq/library.rst:304 +msgid "" +"import threading, queue, time\n" +"\n" +"# The worker thread gets jobs off the queue. When the queue is empty, it\n" +"# assumes there will be no more work and exits.\n" +"# (Realistically workers will run until terminated.)\n" +"def worker():\n" +" print('Running worker')\n" +" time.sleep(0.1)\n" +" while True:\n" +" try:\n" +" arg = q.get(block=False)\n" +" except queue.Empty:\n" +" print('Worker', threading.current_thread(), end=' ')\n" +" print('queue empty')\n" +" break\n" +" else:\n" +" print('Worker', threading.current_thread(), end=' ')\n" +" print('running with argument', arg)\n" +" time.sleep(0.5)\n" +"\n" +"# Create queue\n" +"q = queue.Queue()\n" +"\n" +"# Start a pool of 5 workers\n" +"for i in range(5):\n" +" t = threading.Thread(target=worker, name='worker %i' % (i+1))\n" +" t.start()\n" +"\n" +"# Begin adding work to the queue\n" +"for i in range(50):\n" +" q.put(i)\n" +"\n" +"# Give threads time to run\n" +"print('Main thread sleeping')\n" +"time.sleep(5)" +msgstr "" + #: faq/library.rst:340 msgid "When run, this will produce the following output:" msgstr "" +#: faq/library.rst:342 +msgid "" +"Running worker\n" +"Running worker\n" +"Running worker\n" +"Running worker\n" +"Running worker\n" +"Main thread sleeping\n" +"Worker running with argument 0\n" +"Worker running with argument 1\n" +"Worker running with argument 2\n" +"Worker running with argument 3\n" +"Worker running with argument 4\n" +"Worker running with argument 5\n" +"..." +msgstr "" + #: faq/library.rst:358 msgid "" "Consult the module's documentation for more details; the :class:`~queue." @@ -382,10 +515,33 @@ msgid "" "D, D1, D2 are dicts, x, y are objects, i, j are ints)::" msgstr "" +#: faq/library.rst:380 +msgid "" +"L.append(x)\n" +"L1.extend(L2)\n" +"x = L[i]\n" +"x = L.pop()\n" +"L1[i:j] = L2\n" +"L.sort()\n" +"x = y\n" +"x.field = y\n" +"D[x] = y\n" +"D1.update(D2)\n" +"D.keys()" +msgstr "" + #: faq/library.rst:392 msgid "These aren't::" msgstr "" +#: faq/library.rst:394 +msgid "" +"i = i+1\n" +"L.append(L[-1])\n" +"L[i] = L[j]\n" +"D[x] = D[x] + 1" +msgstr "" + #: faq/library.rst:399 msgid "" "Operations that replace other objects may invoke those other objects' :meth:" @@ -539,6 +695,15 @@ msgid "" "integer in big-endian format from a file::" msgstr "" +#: faq/library.rst:506 +msgid "" +"import struct\n" +"\n" +"with open(filename, \"rb\") as f:\n" +" s = f.read(8)\n" +" x, y, z = struct.unpack(\">hhl\", s)" +msgstr "" + #: faq/library.rst:512 msgid "" "The '>' in the format string forces big-endian data; the letter 'h' reads " @@ -627,6 +792,13 @@ msgid "" "extension modules trying to do I/O). If it is, use :func:`os.close`::" msgstr "" +#: faq/library.rst:649 +msgid "" +"os.close(stdin.fileno())\n" +"os.close(stdout.fileno())\n" +"os.close(stderr.fileno())" +msgstr "" + #: faq/library.rst:653 msgid "Or you can use the numeric constants 0, 1 and 2, respectively." msgstr "" @@ -673,6 +845,22 @@ msgstr "" msgid "Yes. Here's a simple example that uses :mod:`urllib.request`::" msgstr "" +#: faq/library.rst:683 +msgid "" +"#!/usr/local/bin/python\n" +"\n" +"import urllib.request\n" +"\n" +"# build the query string\n" +"qs = \"First=Josephine&MI=Q&Last=Public\"\n" +"\n" +"# connect and send the server a path\n" +"req = urllib.request.urlopen('http://www.some-server.out-there'\n" +" '/cgi-bin/some-cgi-script', data=qs)\n" +"with req:\n" +" msg, hdrs = req.read(), req.info()" +msgstr "" + #: faq/library.rst:696 msgid "" "Note that in general for percent-encoded POST operations, query strings must " @@ -680,6 +868,13 @@ msgid "" "``name=Guy Steele, Jr.``::" msgstr "" +#: faq/library.rst:700 +msgid "" +">>> import urllib.parse\n" +">>> urllib.parse.urlencode({'name': 'Guy Steele, Jr.'})\n" +"'name=Guy+Steele%2C+Jr.'" +msgstr "" + #: faq/library.rst:704 msgid ":ref:`urllib-howto` for extensive examples." msgstr "" @@ -708,6 +903,26 @@ msgid "" "work on any host that supports an SMTP listener. ::" msgstr "" +#: faq/library.rst:724 +msgid "" +"import sys, smtplib\n" +"\n" +"fromaddr = input(\"From: \")\n" +"toaddrs = input(\"To: \").split(',')\n" +"print(\"Enter message, end with ^D:\")\n" +"msg = ''\n" +"while True:\n" +" line = sys.stdin.readline()\n" +" if not line:\n" +" break\n" +" msg += line\n" +"\n" +"# The actual mail send\n" +"server = smtplib.SMTP('localhost')\n" +"server.sendmail(fromaddr, toaddrs, msg)\n" +"server.quit()" +msgstr "" + #: faq/library.rst:741 msgid "" "A Unix-only alternative uses sendmail. The location of the sendmail program " @@ -716,6 +931,22 @@ msgid "" "some sample code::" msgstr "" +#: faq/library.rst:746 +msgid "" +"import os\n" +"\n" +"SENDMAIL = \"/usr/sbin/sendmail\" # sendmail location\n" +"p = os.popen(\"%s -t -i\" % SENDMAIL, \"w\")\n" +"p.write(\"To: receiver@example.com\\n\")\n" +"p.write(\"Subject: test\\n\")\n" +"p.write(\"\\n\") # blank line separating headers from body\n" +"p.write(\"Some text\\n\")\n" +"p.write(\"some more text\\n\")\n" +"sts = p.close()\n" +"if sts != 0:\n" +" print(\"Sendmail exit status\", sts)" +msgstr "" + #: faq/library.rst:761 msgid "How do I avoid blocking in the connect() method of a socket?" msgstr "" @@ -807,6 +1038,12 @@ msgid "" "Usage is simple::" msgstr "" +#: faq/library.rst:825 +msgid "" +"import random\n" +"random.random()" +msgstr "" + #: faq/library.rst:828 msgid "This returns a random floating-point number in the range [0, 1)." msgstr "" diff --git a/faq/programming.po b/faq/programming.po index 9f11a8dee..19a66cad6 100644 --- a/faq/programming.po +++ b/faq/programming.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -292,6 +292,13 @@ msgid "" "functions), e.g.::" msgstr "" +#: faq/programming.rst:213 +msgid "" +">>> squares = []\n" +">>> for x in range(5):\n" +"... squares.append(lambda: x**2)" +msgstr "" + #: faq/programming.rst:217 msgid "" "This gives you a list that contains 5 lambdas that calculate ``x**2``. You " @@ -300,6 +307,14 @@ msgid "" "see that they all return ``16``::" msgstr "" +#: faq/programming.rst:222 +msgid "" +">>> squares[2]()\n" +"16\n" +">>> squares[4]()\n" +"16" +msgstr "" + #: faq/programming.rst:227 msgid "" "This happens because ``x`` is not local to the lambdas, but is defined in " @@ -309,12 +324,26 @@ msgid "" "changing the value of ``x`` and see how the results of the lambdas change::" msgstr "" +#: faq/programming.rst:233 +msgid "" +">>> x = 8\n" +">>> squares[2]()\n" +"64" +msgstr "" + #: faq/programming.rst:237 msgid "" "In order to avoid this, you need to save the values in variables local to " "the lambdas, so that they don't rely on the value of the global ``x``::" msgstr "" +#: faq/programming.rst:240 +msgid "" +">>> squares = []\n" +">>> for x in range(5):\n" +"... squares.append(lambda n=x: n**2)" +msgstr "" + #: faq/programming.rst:244 msgid "" "Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed " @@ -324,6 +353,14 @@ msgid "" "Therefore each lambda will now return the correct result::" msgstr "" +#: faq/programming.rst:250 +msgid "" +">>> squares[2]()\n" +"4\n" +">>> squares[4]()\n" +"16" +msgstr "" + #: faq/programming.rst:255 msgid "" "Note that this behaviour is not peculiar to lambdas, but applies to regular " @@ -348,14 +385,31 @@ msgstr "" msgid "config.py::" msgstr "" +#: faq/programming.rst:270 +msgid "x = 0 # Default value of the 'x' configuration setting" +msgstr "" + #: faq/programming.rst:272 msgid "mod.py::" msgstr "" +#: faq/programming.rst:274 +msgid "" +"import config\n" +"config.x = 1" +msgstr "" + #: faq/programming.rst:277 msgid "main.py::" msgstr "" +#: faq/programming.rst:279 +msgid "" +"import config\n" +"import mod\n" +"print(config.x)" +msgstr "" + #: faq/programming.rst:283 msgid "" "Note that using a module is also the basis for implementing the singleton " @@ -457,6 +511,14 @@ msgid "" "function::" msgstr "" +#: faq/programming.rst:342 +msgid "" +"def foo(mydict={}): # Danger: shared reference to one dict for all calls\n" +" ... compute something ...\n" +" mydict[key] = value\n" +" return mydict" +msgstr "" + #: faq/programming.rst:347 msgid "" "The first time you call this function, ``mydict`` contains a single item. " @@ -488,10 +550,23 @@ msgid "" "list/dictionary/whatever if it is. For example, don't write::" msgstr "" +#: faq/programming.rst:365 +msgid "" +"def foo(mydict={}):\n" +" ..." +msgstr "" + #: faq/programming.rst:368 msgid "but::" msgstr "" +#: faq/programming.rst:370 +msgid "" +"def foo(mydict=None):\n" +" if mydict is None:\n" +" mydict = {} # create a new dict for local namespace" +msgstr "" + #: faq/programming.rst:374 msgid "" "This feature can be useful. When you have a function that's time-consuming " @@ -501,6 +576,20 @@ msgid "" "implemented like this::" msgstr "" +#: faq/programming.rst:379 +msgid "" +"# Callers can only provide two parameters and optionally pass _cache by " +"keyword\n" +"def expensive(arg1, arg2, *, _cache={}):\n" +" if (arg1, arg2) in _cache:\n" +" return _cache[(arg1, arg2)]\n" +"\n" +" # Calculate the value\n" +" result = ... expensive computation ...\n" +" _cache[(arg1, arg2)] = result # Store result in the cache\n" +" return result" +msgstr "" + #: faq/programming.rst:389 msgid "" "You could use a global variable containing a dictionary instead of the " @@ -520,6 +609,15 @@ msgid "" "arguments when calling another function by using ``*`` and ``**``::" msgstr "" +#: faq/programming.rst:401 +msgid "" +"def f(x, *args, **kwargs):\n" +" ...\n" +" kwargs['width'] = '14.3c'\n" +" ...\n" +" g(x, *args, **kwargs)" +msgstr "" + #: faq/programming.rst:415 msgid "What is the difference between arguments and parameters?" msgstr "" @@ -533,12 +631,22 @@ msgid "" "the function definition::" msgstr "" +#: faq/programming.rst:423 +msgid "" +"def func(foo, bar=None, **kwargs):\n" +" pass" +msgstr "" + #: faq/programming.rst:426 msgid "" "*foo*, *bar* and *kwargs* are parameters of ``func``. However, when calling " "``func``, for example::" msgstr "" +#: faq/programming.rst:429 +msgid "func(42, bar=314, extra=somevar)" +msgstr "" + #: faq/programming.rst:431 msgid "the values ``42``, ``314``, and ``somevar`` are arguments." msgstr "" @@ -551,6 +659,17 @@ msgstr "" msgid "If you wrote code like::" msgstr "" +#: faq/programming.rst:439 +msgid "" +">>> x = []\n" +">>> y = x\n" +">>> y.append(10)\n" +">>> y\n" +"[10]\n" +">>> x\n" +"[10]" +msgstr "" + #: faq/programming.rst:447 msgid "" "you might be wondering why appending an element to ``y`` changed ``x`` too." @@ -584,6 +703,17 @@ msgstr "" msgid "If we instead assign an immutable object to ``x``::" msgstr "" +#: faq/programming.rst:463 +msgid "" +">>> x = 5 # ints are immutable\n" +">>> y = x\n" +">>> x = x + 1 # 5 can't be mutated, we are creating a new object here\n" +">>> x\n" +"6\n" +">>> y\n" +"5" +msgstr "" + #: faq/programming.rst:471 msgid "" "we can see that in this case ``x`` and ``y`` are not equal anymore. This is " @@ -658,6 +788,18 @@ msgstr "" msgid "By returning a tuple of the results::" msgstr "" +#: faq/programming.rst:519 +msgid "" +">>> def func1(a, b):\n" +"... a = 'new-value' # a and b are local names\n" +"... b = b + 1 # assigned to new objects\n" +"... return a, b # return new values\n" +"...\n" +">>> x, y = 'old-value', 99\n" +">>> func1(x, y)\n" +"('new-value', 100)" +msgstr "" + #: faq/programming.rst:528 msgid "This is almost always the clearest solution." msgstr "" @@ -671,14 +813,55 @@ msgstr "" msgid "By passing a mutable (changeable in-place) object::" msgstr "" +#: faq/programming.rst:534 +msgid "" +">>> def func2(a):\n" +"... a[0] = 'new-value' # 'a' references a mutable list\n" +"... a[1] = a[1] + 1 # changes a shared object\n" +"...\n" +">>> args = ['old-value', 99]\n" +">>> func2(args)\n" +">>> args\n" +"['new-value', 100]" +msgstr "" + #: faq/programming.rst:543 msgid "By passing in a dictionary that gets mutated::" msgstr "" +#: faq/programming.rst:545 +msgid "" +">>> def func3(args):\n" +"... args['a'] = 'new-value' # args is a mutable dictionary\n" +"... args['b'] = args['b'] + 1 # change it in-place\n" +"...\n" +">>> args = {'a': 'old-value', 'b': 99}\n" +">>> func3(args)\n" +">>> args\n" +"{'a': 'new-value', 'b': 100}" +msgstr "" + #: faq/programming.rst:554 msgid "Or bundle up values in a class instance::" msgstr "" +#: faq/programming.rst:556 +msgid "" +">>> class Namespace:\n" +"... def __init__(self, /, **args):\n" +"... for key, value in args.items():\n" +"... setattr(self, key, value)\n" +"...\n" +">>> def func4(args):\n" +"... args.a = 'new-value' # args is a mutable Namespace\n" +"... args.b = args.b + 1 # change object in-place\n" +"...\n" +">>> args = Namespace(a='old-value', b=99)\n" +">>> func4(args)\n" +">>> vars(args)\n" +"{'a': 'new-value', 'b': 100}" +msgstr "" + #: faq/programming.rst:571 msgid "There's almost never a good reason to get this complicated." msgstr "" @@ -699,14 +882,37 @@ msgid "" "scopes::" msgstr "" +#: faq/programming.rst:583 +msgid "" +"def linear(a, b):\n" +" def result(x):\n" +" return a * x + b\n" +" return result" +msgstr "" + #: faq/programming.rst:588 msgid "Or using a callable object::" msgstr "" +#: faq/programming.rst:590 +msgid "" +"class linear:\n" +"\n" +" def __init__(self, a, b):\n" +" self.a, self.b = a, b\n" +"\n" +" def __call__(self, x):\n" +" return self.a * x + self.b" +msgstr "" + #: faq/programming.rst:598 msgid "In both cases, ::" msgstr "" +#: faq/programming.rst:600 +msgid "taxes = linear(0.3, 2)" +msgstr "" + #: faq/programming.rst:602 msgid "gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``." msgstr "" @@ -718,10 +924,37 @@ msgid "" "callables can share their signature via inheritance::" msgstr "" +#: faq/programming.rst:608 +msgid "" +"class exponential(linear):\n" +" # __init__ inherited\n" +" def __call__(self, x):\n" +" return self.a * (x ** self.b)" +msgstr "" + #: faq/programming.rst:613 msgid "Object can encapsulate state for several methods::" msgstr "" +#: faq/programming.rst:615 +msgid "" +"class counter:\n" +"\n" +" value = 0\n" +"\n" +" def set(self, x):\n" +" self.value = x\n" +"\n" +" def up(self):\n" +" self.value = self.value + 1\n" +"\n" +" def down(self):\n" +" self.value = self.value - 1\n" +"\n" +"count = counter()\n" +"inc, dec, reset = count.up, count.down, count.set" +msgstr "" + #: faq/programming.rst:631 msgid "" "Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the " @@ -744,10 +977,18 @@ msgid "" "copy` method::" msgstr "" +#: faq/programming.rst:644 +msgid "newdict = olddict.copy()" +msgstr "" + #: faq/programming.rst:646 msgid "Sequences can be copied by slicing::" msgstr "" +#: faq/programming.rst:648 +msgid "new_l = l[:]" +msgstr "" + #: faq/programming.rst:652 msgid "How can I find the methods or attributes of an object?" msgstr "" @@ -771,6 +1012,20 @@ msgid "" "Consider the following code::" msgstr "" +#: faq/programming.rst:667 +msgid "" +">>> class A:\n" +"... pass\n" +"...\n" +">>> B = A\n" +">>> a = B()\n" +">>> b = a\n" +">>> print(b)\n" +"<__main__.A object at 0x16D07CC>\n" +">>> print(a)\n" +"<__main__.A object at 0x16D07CC>" +msgstr "" + #: faq/programming.rst:678 msgid "" "Arguably the class has a name: even though it is bound to two names and " @@ -816,16 +1071,30 @@ msgstr "" msgid "Comma is not an operator in Python. Consider this session::" msgstr "" +#: faq/programming.rst:705 +msgid "" +">>> \"a\" in \"b\", \"a\"\n" +"(False, 'a')" +msgstr "" + #: faq/programming.rst:708 msgid "" "Since the comma is not an operator, but a separator between expressions the " "above is evaluated as if you had entered::" msgstr "" +#: faq/programming.rst:711 +msgid "(\"a\" in \"b\"), \"a\"" +msgstr "" + #: faq/programming.rst:713 msgid "not::" msgstr "" +#: faq/programming.rst:715 +msgid "\"a\" in (\"b\", \"a\")" +msgstr "" + #: faq/programming.rst:717 msgid "" "The same is true of the various assignment operators (``=``, ``+=`` etc). " @@ -841,12 +1110,24 @@ msgstr "" msgid "Yes, there is. The syntax is as follows::" msgstr "" +#: faq/programming.rst:726 +msgid "" +"[on_true] if [expression] else [on_false]\n" +"\n" +"x, y = 50, 25\n" +"small = x if x < y else y" +msgstr "" + #: faq/programming.rst:731 msgid "" "Before this syntax was introduced in Python 2.5, a common idiom was to use " "logical operators::" msgstr "" +#: faq/programming.rst:734 +msgid "[expression] and [on_true] or [on_false]" +msgstr "" + #: faq/programming.rst:736 msgid "" "However, this idiom is unsafe, as it can give wrong results when *on_true* " @@ -865,6 +1146,34 @@ msgid "" "Bartelt::" msgstr "" +#: faq/programming.rst:747 +msgid "" +"from functools import reduce\n" +"\n" +"# Primes < 1000\n" +"print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,\n" +"map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))\n" +"\n" +"# First 10 Fibonacci numbers\n" +"print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:\n" +"f(x,f), range(10))))\n" +"\n" +"# Mandelbrot set\n" +"print((lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+'\\n'+y,map(lambda " +"y,\n" +"Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,\n" +"Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,\n" +"i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y\n" +">=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(\n" +"64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy\n" +"))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))\n" +"# \\___ ___/ \\___ ___/ | | |__ lines on screen\n" +"# V V | |______ columns on screen\n" +"# | | |__________ maximum of \"iterations\"\n" +"# | |_________________ range on y axis\n" +"# |____________________________ range on x axis" +msgstr "" + #: faq/programming.rst:771 msgid "Don't try this at home, kids!" msgstr "" @@ -883,6 +1192,15 @@ msgid "" "only parameters. Its documentation looks like this::" msgstr "" +#: faq/programming.rst:786 +msgid "" +">>> help(divmod)\n" +"Help on built-in function divmod in module builtins:\n" +"\n" +"divmod(x, y, /)\n" +" Return the tuple (x//y, x%y). Invariant: div*y + mod == x." +msgstr "" + #: faq/programming.rst:792 msgid "" "The slash at the end of the parameter list means that both parameters are " @@ -890,6 +1208,14 @@ msgid "" "lead to an error::" msgstr "" +#: faq/programming.rst:796 +msgid "" +">>> divmod(x=3, y=4)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: divmod() takes no keyword arguments" +msgstr "" + #: faq/programming.rst:803 msgid "Numbers and strings" msgstr "" @@ -905,6 +1231,13 @@ msgid "" "octal value \"10\" (8 in decimal), type::" msgstr "" +#: faq/programming.rst:812 +msgid "" +">>> a = 0o10\n" +">>> a\n" +"8" +msgstr "" + #: faq/programming.rst:816 msgid "" "Hexadecimal is just as easy. Simply precede the hexadecimal number with a " @@ -912,6 +1245,16 @@ msgid "" "specified in lower or uppercase. For example, in the Python interpreter::" msgstr "" +#: faq/programming.rst:820 +msgid "" +">>> a = 0xa5\n" +">>> a\n" +"165\n" +">>> b = 0XB2\n" +">>> b\n" +"178" +msgstr "" + #: faq/programming.rst:829 msgid "Why does -22 // 10 return -3?" msgstr "" @@ -922,6 +1265,10 @@ msgid "" "``j``. If you want that, and also want::" msgstr "" +#: faq/programming.rst:834 +msgid "i == (i // j) * j + (i % j)" +msgstr "" + #: faq/programming.rst:836 msgid "" "then integer division has to return the floor. C also requires that " @@ -948,6 +1295,15 @@ msgid "" "exc:`SyntaxError` because the period is seen as a decimal point::" msgstr "" +#: faq/programming.rst:853 +msgid "" +">>> 1.__class__\n" +" File \"\", line 1\n" +" 1.__class__\n" +" ^\n" +"SyntaxError: invalid decimal literal" +msgstr "" + #: faq/programming.rst:859 msgid "" "The solution is to separate the literal from the period with either a space " @@ -1019,6 +1375,31 @@ msgid "" "module::" msgstr "" +#: faq/programming.rst:914 +msgid "" +">>> import io\n" +">>> s = \"Hello, world\"\n" +">>> sio = io.StringIO(s)\n" +">>> sio.getvalue()\n" +"'Hello, world'\n" +">>> sio.seek(7)\n" +"7\n" +">>> sio.write(\"there!\")\n" +"6\n" +">>> sio.getvalue()\n" +"'Hello, there!'\n" +"\n" +">>> import array\n" +">>> a = array.array('u', s)\n" +">>> print(a)\n" +"array('u', 'Hello, world')\n" +">>> a[0] = 'y'\n" +">>> print(a)\n" +"array('u', 'yello, world')\n" +">>> a.tounicode()\n" +"'yello, world'" +msgstr "" + #: faq/programming.rst:938 msgid "How do I use strings to call functions/methods?" msgstr "" @@ -1035,10 +1416,29 @@ msgid "" "a case construct::" msgstr "" +#: faq/programming.rst:947 +msgid "" +"def a():\n" +" pass\n" +"\n" +"def b():\n" +" pass\n" +"\n" +"dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs\n" +"\n" +"dispatch[get_input()]() # Note trailing parens to call function" +msgstr "" + #: faq/programming.rst:957 msgid "Use the built-in function :func:`getattr`::" msgstr "" +#: faq/programming.rst:959 +msgid "" +"import foo\n" +"getattr(foo, 'bar')()" +msgstr "" + #: faq/programming.rst:962 msgid "" "Note that :func:`getattr` works on any object, including classes, class " @@ -1049,10 +1449,34 @@ msgstr "" msgid "This is used in several places in the standard library, like this::" msgstr "" +#: faq/programming.rst:967 +msgid "" +"class Foo:\n" +" def do_foo(self):\n" +" ...\n" +"\n" +" def do_bar(self):\n" +" ...\n" +"\n" +"f = getattr(foo_instance, 'do_' + opname)\n" +"f()" +msgstr "" + #: faq/programming.rst:978 msgid "Use :func:`locals` to resolve the function name::" msgstr "" +#: faq/programming.rst:980 +msgid "" +"def myFunc():\n" +" print(\"hello\")\n" +"\n" +"fname = \"myFunc\"\n" +"\n" +"f = locals()[fname]\n" +"f()" +msgstr "" + #: faq/programming.rst:990 msgid "" "Is there an equivalent to Perl's chomp() for removing trailing newlines from " @@ -1068,6 +1492,15 @@ msgid "" "removed::" msgstr "" +#: faq/programming.rst:998 +msgid "" +">>> lines = (\"line 1 \\r\\n\"\n" +"... \"\\r\\n\"\n" +"... \"\\r\\n\")\n" +">>> lines.rstrip(\"\\n\\r\")\n" +"'line 1 '" +msgstr "" + #: faq/programming.rst:1004 msgid "" "Since this is typically only desired when reading text one line at a time, " @@ -1087,7 +1520,7 @@ msgid "" "For simple input parsing, the easiest approach is usually to split the line " "into whitespace-delimited words using the :meth:`~str.split` method of " "string objects and then convert decimal strings to numeric values using :" -"func:`int` or :func:`float`. :meth:`!split()` supports an optional \"sep\" " +"func:`int` or :func:`float`. :meth:`!split` supports an optional \"sep\" " "parameter which is useful if the line uses something other than whitespace " "as a separator." msgstr "" @@ -1116,24 +1549,51 @@ msgid "" "string's quote::" msgstr "" +#: faq/programming.rst:1036 +msgid "" +">>> r'C:\\this\\will\\not\\work\\'\n" +" File \"\", line 1\n" +" r'C:\\this\\will\\not\\work\\'\n" +" ^\n" +"SyntaxError: unterminated string literal (detected at line 1)" +msgstr "" + #: faq/programming.rst:1042 msgid "" "There are several workarounds for this. One is to use regular strings and " "double the backslashes::" msgstr "" +#: faq/programming.rst:1045 +msgid "" +">>> 'C:\\\\this\\\\will\\\\work\\\\'\n" +"'C:\\\\this\\\\will\\\\work\\\\'" +msgstr "" + #: faq/programming.rst:1048 msgid "" "Another is to concatenate a regular string containing an escaped backslash " "to the raw string::" msgstr "" +#: faq/programming.rst:1051 +msgid "" +">>> r'C:\\this\\will\\work' '\\\\'\n" +"'C:\\\\this\\\\will\\\\work\\\\'" +msgstr "" + #: faq/programming.rst:1054 msgid "" "It is also possible to use :func:`os.path.join` to append a backslash on " "Windows::" msgstr "" +#: faq/programming.rst:1056 +msgid "" +">>> os.path.join(r'C:\\this\\will\\work', '')\n" +"'C:\\\\this\\\\will\\\\work\\\\'" +msgstr "" + #: faq/programming.rst:1059 msgid "" "Note that while a backslash will \"escape\" a quote for the purposes of " @@ -1142,6 +1602,12 @@ msgid "" "value of the raw string::" msgstr "" +#: faq/programming.rst:1064 +msgid "" +">>> r'backslash\\'preserved'\n" +"\"backslash\\\\'preserved\"" +msgstr "" + #: faq/programming.rst:1067 msgid "Also see the specification in the :ref:`language reference `." msgstr "" @@ -1267,6 +1733,14 @@ msgid "" "them into a list and call :meth:`str.join` at the end::" msgstr "" +#: faq/programming.rst:1141 +msgid "" +"chunks = []\n" +"for s in my_strings:\n" +" chunks.append(s)\n" +"result = ''.join(chunks)" +msgstr "" + #: faq/programming.rst:1146 msgid "(another reasonably efficient idiom is to use :class:`io.StringIO`)" msgstr "" @@ -1278,6 +1752,13 @@ msgid "" "operator)::" msgstr "" +#: faq/programming.rst:1151 +msgid "" +"result = bytearray()\n" +"for b in my_bytes_objects:\n" +" result += b" +msgstr "" + #: faq/programming.rst:1157 msgid "Sequences (Tuples/Lists)" msgstr "" @@ -1336,6 +1817,12 @@ msgstr "" msgid "Use the :func:`reversed` built-in function::" msgstr "" +#: faq/programming.rst:1194 +msgid "" +"for x in reversed(sequence):\n" +" ... # do something with x ..." +msgstr "" + #: faq/programming.rst:1197 msgid "" "This won't touch your original sequence, but build a new copy with reversed " @@ -1360,12 +1847,28 @@ msgid "" "the list, deleting duplicates as you go::" msgstr "" +#: faq/programming.rst:1211 +msgid "" +"if mylist:\n" +" mylist.sort()\n" +" last = mylist[-1]\n" +" for i in range(len(mylist)-2, -1, -1):\n" +" if last == mylist[i]:\n" +" del mylist[i]\n" +" else:\n" +" last = mylist[i]" +msgstr "" + #: faq/programming.rst:1220 msgid "" "If all elements of the list may be used as set keys (i.e. they are all :term:" "`hashable`) this is often faster ::" msgstr "" +#: faq/programming.rst:1223 +msgid "mylist = list(set(mylist))" +msgstr "" + #: faq/programming.rst:1225 msgid "" "This converts the list into a set, thereby removing duplicates, and then " @@ -1384,6 +1887,13 @@ msgid "" "variations.::" msgstr "" +#: faq/programming.rst:1237 +msgid "" +"mylist[:] = filter(keep_function, mylist)\n" +"mylist[:] = (x for x in mylist if keep_condition)\n" +"mylist[:] = [x for x in mylist if keep_condition]" +msgstr "" + #: faq/programming.rst:1241 msgid "The list comprehension may be fastest." msgstr "" @@ -1396,6 +1906,10 @@ msgstr "" msgid "Use a list::" msgstr "" +#: faq/programming.rst:1249 +msgid "[\"this\", 1, \"is\", \"an\", \"array\"]" +msgstr "" + #: faq/programming.rst:1251 msgid "" "Lists are equivalent to C or Pascal arrays in their time complexity; the " @@ -1416,6 +1930,10 @@ msgid "" "To get Lisp-style linked lists, you can emulate *cons cells* using tuples::" msgstr "" +#: faq/programming.rst:1262 +msgid "lisp_list = (\"like\", (\"this\", (\"example\", None) ) )" +msgstr "" + #: faq/programming.rst:1264 msgid "" "If mutability is desired, you could use lists instead of tuples. Here the " @@ -1432,14 +1950,31 @@ msgstr "" msgid "You probably tried to make a multidimensional array like this::" msgstr "" +#: faq/programming.rst:1277 +msgid ">>> A = [[None] * 2] * 3" +msgstr "" + #: faq/programming.rst:1279 msgid "This looks correct if you print it:" msgstr "" +#: faq/programming.rst:1285 +msgid "" +">>> A\n" +"[[None, None], [None, None], [None, None]]" +msgstr "" + #: faq/programming.rst:1290 msgid "But when you assign a value, it shows up in multiple places:" msgstr "" +#: faq/programming.rst:1296 +msgid "" +">>> A[0][0] = 5\n" +">>> A\n" +"[[5, None], [5, None], [5, None]]" +msgstr "" + #: faq/programming.rst:1302 msgid "" "The reason is that replicating a list with ``*`` doesn't create copies, it " @@ -1454,12 +1989,25 @@ msgid "" "then fill in each element with a newly created list::" msgstr "" +#: faq/programming.rst:1310 +msgid "" +"A = [None] * 3\n" +"for i in range(3):\n" +" A[i] = [None] * 2" +msgstr "" + #: faq/programming.rst:1314 msgid "" "This generates a list containing 3 different lists of length two. You can " "also use a list comprehension::" msgstr "" +#: faq/programming.rst:1317 +msgid "" +"w, h = 2, 3\n" +"A = [[None] * w for i in range(h)]" +msgstr "" + #: faq/programming.rst:1320 msgid "" "Or, you can use an extension that provides a matrix datatype; `NumPy " @@ -1476,12 +2024,28 @@ msgid "" "term:`list comprehension` is an elegant solution::" msgstr "" +#: faq/programming.rst:1330 +msgid "" +"result = [obj.method() for obj in mylist]\n" +"\n" +"result = [function(obj) for obj in mylist]" +msgstr "" + #: faq/programming.rst:1334 msgid "" "To just run the method or function without saving the return values, a " "plain :keyword:`for` loop will suffice::" msgstr "" +#: faq/programming.rst:1337 +msgid "" +"for obj in mylist:\n" +" obj.method()\n" +"\n" +"for obj in mylist:\n" +" function(obj)" +msgstr "" + #: faq/programming.rst:1346 msgid "" "Why does a_tuple[i] += ['item'] raise an exception when the addition works?" @@ -1505,6 +2069,15 @@ msgstr "" msgid "If you wrote::" msgstr "" +#: faq/programming.rst:1358 +msgid "" +">>> a_tuple = (1, 2)\n" +">>> a_tuple[0] += 1\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: 'tuple' object does not support item assignment" +msgstr "" + #: faq/programming.rst:1364 msgid "" "The reason for the exception should be immediately clear: ``1`` is added to " @@ -1520,6 +2093,15 @@ msgid "" "approximately this::" msgstr "" +#: faq/programming.rst:1373 +msgid "" +">>> result = a_tuple[0] + 1\n" +">>> a_tuple[0] = result\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: 'tuple' object does not support item assignment" +msgstr "" + #: faq/programming.rst:1379 msgid "" "It is the assignment part of the operation that produces the error, since a " @@ -1530,12 +2112,27 @@ msgstr "" msgid "When you write something like::" msgstr "" +#: faq/programming.rst:1384 +msgid "" +">>> a_tuple = (['foo'], 'bar')\n" +">>> a_tuple[0] += ['item']\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: 'tuple' object does not support item assignment" +msgstr "" + #: faq/programming.rst:1390 msgid "" "The exception is a bit more surprising, and even more surprising is the fact " "that even though there was an error, the append worked::" msgstr "" +#: faq/programming.rst:1393 +msgid "" +">>> a_tuple[0]\n" +"['foo', 'item']" +msgstr "" + #: faq/programming.rst:1396 msgid "" "To see why this happens, you need to know that (a) if an object implements " @@ -1546,10 +2143,24 @@ msgid "" "we say that for lists, ``+=`` is a \"shorthand\" for :meth:`!list.extend`::" msgstr "" +#: faq/programming.rst:1404 +msgid "" +">>> a_list = []\n" +">>> a_list += [1]\n" +">>> a_list\n" +"[1]" +msgstr "" + #: faq/programming.rst:1409 msgid "This is equivalent to::" msgstr "" +#: faq/programming.rst:1411 +msgid "" +">>> result = a_list.__iadd__([1])\n" +">>> a_list = result" +msgstr "" + #: faq/programming.rst:1414 msgid "" "The object pointed to by a_list has been mutated, and the pointer to the " @@ -1562,6 +2173,15 @@ msgstr "" msgid "Thus, in our tuple example what is happening is equivalent to::" msgstr "" +#: faq/programming.rst:1421 +msgid "" +">>> result = a_tuple[0].__iadd__(['item'])\n" +">>> a_tuple[0] = result\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: 'tuple' object does not support item assignment" +msgstr "" + #: faq/programming.rst:1427 msgid "" "The :meth:`!__iadd__` succeeds, and thus the list is extended, but even " @@ -1584,6 +2204,12 @@ msgid "" "method::" msgstr "" +#: faq/programming.rst:1439 +msgid "" +"Isorted = L[:]\n" +"Isorted.sort(key=lambda s: int(s[10:15]))" +msgstr "" + #: faq/programming.rst:1444 msgid "How can I sort one list by values from another list?" msgstr "" @@ -1594,6 +2220,20 @@ msgid "" "pick out the element you want. ::" msgstr "" +#: faq/programming.rst:1449 +msgid "" +">>> list1 = [\"what\", \"I'm\", \"sorting\", \"by\"]\n" +">>> list2 = [\"something\", \"else\", \"to\", \"sort\"]\n" +">>> pairs = zip(list1, list2)\n" +">>> pairs = sorted(pairs)\n" +">>> pairs\n" +"[(\"I'm\", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', " +"'something')]\n" +">>> result = [x[1] for x in pairs]\n" +">>> result\n" +"['else', 'sort', 'to', 'something']" +msgstr "" + #: faq/programming.rst:1461 msgid "Objects" msgstr "" @@ -1631,6 +2271,13 @@ msgid "" "definition::" msgstr "" +#: faq/programming.rst:1485 +msgid "" +"class C:\n" +" def meth(self, arg):\n" +" return arg * 2 + self.attribute" +msgstr "" + #: faq/programming.rst:1491 msgid "What is self?" msgstr "" @@ -1671,6 +2318,38 @@ msgid "" "To test for \"true inheritance\", scan the :term:`MRO` of the class:" msgstr "" +#: faq/programming.rst:1516 +msgid "" +"from collections.abc import Mapping\n" +"\n" +"class P:\n" +" pass\n" +"\n" +"class C(P):\n" +" pass\n" +"\n" +"Mapping.register(P)" +msgstr "" + +#: faq/programming.rst:1528 +msgid "" +">>> c = C()\n" +">>> isinstance(c, C) # direct\n" +"True\n" +">>> isinstance(c, P) # indirect\n" +"True\n" +">>> isinstance(c, Mapping) # virtual\n" +"True\n" +"\n" +"# Actual inheritance chain\n" +">>> type(c).__mro__\n" +"(, , )\n" +"\n" +"# Test for \"true inheritance\"\n" +">>> Mapping in type(c).__mro__\n" +"False" +msgstr "" + #: faq/programming.rst:1546 msgid "" "Note that most programs do not use :func:`isinstance` on user-defined " @@ -1681,12 +2360,35 @@ msgid "" "have a function that does something::" msgstr "" +#: faq/programming.rst:1553 +msgid "" +"def search(obj):\n" +" if isinstance(obj, Mailbox):\n" +" ... # code to search a mailbox\n" +" elif isinstance(obj, Document):\n" +" ... # code to search a document\n" +" elif ..." +msgstr "" + #: faq/programming.rst:1560 msgid "" "A better approach is to define a ``search()`` method on all the classes and " "just call it::" msgstr "" +#: faq/programming.rst:1563 +msgid "" +"class Mailbox:\n" +" def search(self):\n" +" ... # code to search a mailbox\n" +"\n" +"class Document:\n" +" def search(self):\n" +" ... # code to search a document\n" +"\n" +"obj.search()" +msgstr "" + #: faq/programming.rst:1575 msgid "What is delegation?" msgstr "" @@ -1707,6 +2409,20 @@ msgid "" "written data to uppercase::" msgstr "" +#: faq/programming.rst:1587 +msgid "" +"class UpperOut:\n" +"\n" +" def __init__(self, outfile):\n" +" self._outfile = outfile\n" +"\n" +" def write(self, s):\n" +" self._outfile.write(s.upper())\n" +"\n" +" def __getattr__(self, name):\n" +" return getattr(self._outfile, name)" +msgstr "" + #: faq/programming.rst:1598 msgid "" "Here the ``UpperOut`` class redefines the ``write()`` method to convert the " @@ -1726,24 +2442,53 @@ msgid "" "following::" msgstr "" +#: faq/programming.rst:1610 +msgid "" +"class X:\n" +" ...\n" +" def __setattr__(self, name, value):\n" +" self.__dict__[name] = value\n" +" ..." +msgstr "" + #: faq/programming.rst:1616 msgid "" -"Most :meth:`!__setattr__` implementations must modify :meth:`self.__dict__ " -"` to store local state for self without causing an infinite " -"recursion." +"Many :meth:`~object.__setattr__` implementations call :meth:`!object." +"__setattr__` to set an attribute on self without causing infinite recursion::" +msgstr "" + +#: faq/programming.rst:1619 +msgid "" +"class X:\n" +" def __setattr__(self, name, value):\n" +" # Custom logic here...\n" +" object.__setattr__(self, name, value)" +msgstr "" + +#: faq/programming.rst:1624 +msgid "" +"Alternatively, it is possible to set attributes by inserting entries into :" +"attr:`self.__dict__ ` directly." msgstr "" -#: faq/programming.rst:1622 +#: faq/programming.rst:1629 msgid "" "How do I call a method defined in a base class from a derived class that " "extends it?" msgstr "" -#: faq/programming.rst:1624 +#: faq/programming.rst:1631 msgid "Use the built-in :func:`super` function::" msgstr "" -#: faq/programming.rst:1630 +#: faq/programming.rst:1633 +msgid "" +"class Derived(Base):\n" +" def meth(self):\n" +" super().meth() # calls Base.meth" +msgstr "" + +#: faq/programming.rst:1637 msgid "" "In the example, :func:`super` will automatically determine the instance from " "which it was called (the ``self`` value), look up the :term:`method " @@ -1751,11 +2496,11 @@ msgid "" "line after ``Derived`` in the MRO: ``Base``." msgstr "" -#: faq/programming.rst:1637 +#: faq/programming.rst:1644 msgid "How can I organize my code to make it easier to change the base class?" msgstr "" -#: faq/programming.rst:1639 +#: faq/programming.rst:1646 msgid "" "You could assign the base class to an alias and derive from the alias. Then " "all you have to change is the value assigned to the alias. Incidentally, " @@ -1763,30 +2508,53 @@ msgid "" "on availability of resources) which base class to use. Example::" msgstr "" -#: faq/programming.rst:1654 +#: faq/programming.rst:1651 +msgid "" +"class Base:\n" +" ...\n" +"\n" +"BaseAlias = Base\n" +"\n" +"class Derived(BaseAlias):\n" +" ..." +msgstr "" + +#: faq/programming.rst:1661 msgid "How do I create static class data and static class methods?" msgstr "" -#: faq/programming.rst:1656 +#: faq/programming.rst:1663 msgid "" "Both static data and static methods (in the sense of C++ or Java) are " "supported in Python." msgstr "" -#: faq/programming.rst:1659 +#: faq/programming.rst:1666 msgid "" "For static data, simply define a class attribute. To assign a new value to " "the attribute, you have to explicitly use the class name in the assignment::" msgstr "" -#: faq/programming.rst:1671 +#: faq/programming.rst:1669 +msgid "" +"class C:\n" +" count = 0 # number of times C.__init__ called\n" +"\n" +" def __init__(self):\n" +" C.count = C.count + 1\n" +"\n" +" def getcount(self):\n" +" return C.count # or return self.count" +msgstr "" + +#: faq/programming.rst:1678 msgid "" "``c.count`` also refers to ``C.count`` for any ``c`` such that " "``isinstance(c, C)`` holds, unless overridden by ``c`` itself or by some " "class on the base-class search path from ``c.__class__`` back to ``C``." msgstr "" -#: faq/programming.rst:1675 +#: faq/programming.rst:1682 msgid "" "Caution: within a method of C, an assignment like ``self.count = 42`` " "creates a new and unrelated instance named \"count\" in ``self``'s own " @@ -1794,59 +2562,102 @@ msgid "" "whether inside a method or not::" msgstr "" -#: faq/programming.rst:1682 +#: faq/programming.rst:1687 +msgid "C.count = 314" +msgstr "" + +#: faq/programming.rst:1689 msgid "Static methods are possible::" msgstr "" -#: faq/programming.rst:1690 +#: faq/programming.rst:1691 +msgid "" +"class C:\n" +" @staticmethod\n" +" def static(arg1, arg2, arg3):\n" +" # No 'self' parameter!\n" +" ..." +msgstr "" + +#: faq/programming.rst:1697 msgid "" "However, a far more straightforward way to get the effect of a static method " "is via a simple module-level function::" msgstr "" -#: faq/programming.rst:1696 +#: faq/programming.rst:1700 +msgid "" +"def getcount():\n" +" return C.count" +msgstr "" + +#: faq/programming.rst:1703 msgid "" "If your code is structured so as to define one class (or tightly related " "class hierarchy) per module, this supplies the desired encapsulation." msgstr "" -#: faq/programming.rst:1701 +#: faq/programming.rst:1708 msgid "How can I overload constructors (or methods) in Python?" msgstr "" -#: faq/programming.rst:1703 +#: faq/programming.rst:1710 msgid "" "This answer actually applies to all methods, but the question usually comes " "up first in the context of constructors." msgstr "" -#: faq/programming.rst:1706 +#: faq/programming.rst:1713 msgid "In C++ you'd write" msgstr "" #: faq/programming.rst:1715 msgid "" +"class C {\n" +" C() { cout << \"No arguments\\n\"; }\n" +" C(int i) { cout << \"Argument is \" << i << \"\\n\"; }\n" +"}" +msgstr "" + +#: faq/programming.rst:1722 +msgid "" "In Python you have to write a single constructor that catches all cases " "using default arguments. For example::" msgstr "" #: faq/programming.rst:1725 +msgid "" +"class C:\n" +" def __init__(self, i=None):\n" +" if i is None:\n" +" print(\"No arguments\")\n" +" else:\n" +" print(\"Argument is\", i)" +msgstr "" + +#: faq/programming.rst:1732 msgid "This is not entirely equivalent, but close enough in practice." msgstr "" -#: faq/programming.rst:1727 +#: faq/programming.rst:1734 msgid "You could also try a variable-length argument list, e.g. ::" msgstr "" -#: faq/programming.rst:1732 +#: faq/programming.rst:1736 +msgid "" +"def __init__(self, *args):\n" +" ..." +msgstr "" + +#: faq/programming.rst:1739 msgid "The same approach works for all method definitions." msgstr "" -#: faq/programming.rst:1736 +#: faq/programming.rst:1743 msgid "I try to use __spam and I get an error about _SomeClassName__spam." msgstr "" -#: faq/programming.rst:1738 +#: faq/programming.rst:1745 msgid "" "Variable names with double leading underscores are \"mangled\" to provide a " "simple but effective way to define class private variables. Any identifier " @@ -1856,41 +2667,56 @@ msgid "" "stripped." msgstr "" -#: faq/programming.rst:1744 +#: faq/programming.rst:1751 msgid "" "The identifier can be used unchanged within the class, but to access it " "outside the class, the mangled name must be used:" msgstr "" -#: faq/programming.rst:1761 +#: faq/programming.rst:1754 +msgid "" +"class A:\n" +" def __one(self):\n" +" return 1\n" +" def two(self):\n" +" return 2 * self.__one()\n" +"\n" +"class B(A):\n" +" def three(self):\n" +" return 3 * self._A__one()\n" +"\n" +"four = 4 * A()._A__one()" +msgstr "" + +#: faq/programming.rst:1768 msgid "" "In particular, this does not guarantee privacy since an outside user can " "still deliberately access the private attribute; many Python programmers " "never bother to use private variable names at all." msgstr "" -#: faq/programming.rst:1767 +#: faq/programming.rst:1774 msgid "" "The :ref:`private name mangling specifications ` for " "details and special cases." msgstr "" -#: faq/programming.rst:1771 +#: faq/programming.rst:1778 msgid "My class defines __del__ but it is not called when I delete the object." msgstr "" -#: faq/programming.rst:1773 +#: faq/programming.rst:1780 msgid "There are several possible reasons for this." msgstr "" -#: faq/programming.rst:1775 +#: faq/programming.rst:1782 msgid "" "The :keyword:`del` statement does not necessarily call :meth:`~object." "__del__` -- it simply decrements the object's reference count, and if this " "reaches zero :meth:`!__del__` is called." msgstr "" -#: faq/programming.rst:1779 +#: faq/programming.rst:1786 msgid "" "If your data structures contain circular links (e.g. a tree where each child " "has a parent reference and each parent has a list of children) the reference " @@ -1904,7 +2730,7 @@ msgid "" "cases where objects will never be collected." msgstr "" -#: faq/programming.rst:1790 +#: faq/programming.rst:1797 msgid "" "Despite the cycle collector, it's still a good idea to define an explicit " "``close()`` method on objects to be called whenever you're done with them. " @@ -1914,7 +2740,7 @@ msgid "" "once for the same object." msgstr "" -#: faq/programming.rst:1797 +#: faq/programming.rst:1804 msgid "" "Another way to avoid cyclical references is to use the :mod:`weakref` " "module, which allows you to point to objects without incrementing their " @@ -1922,28 +2748,28 @@ msgid "" "references for their parent and sibling references (if they need them!)." msgstr "" -#: faq/programming.rst:1810 +#: faq/programming.rst:1817 msgid "" "Finally, if your :meth:`!__del__` method raises an exception, a warning " "message is printed to :data:`sys.stderr`." msgstr "" -#: faq/programming.rst:1815 +#: faq/programming.rst:1822 msgid "How do I get a list of all instances of a given class?" msgstr "" -#: faq/programming.rst:1817 +#: faq/programming.rst:1824 msgid "" "Python does not keep track of all instances of a class (or of a built-in " "type). You can program the class's constructor to keep track of all " "instances by keeping a list of weak references to each instance." msgstr "" -#: faq/programming.rst:1823 +#: faq/programming.rst:1830 msgid "Why does the result of ``id()`` appear to be not unique?" msgstr "" -#: faq/programming.rst:1825 +#: faq/programming.rst:1832 msgid "" "The :func:`id` builtin returns an integer that is guaranteed to be unique " "during the lifetime of the object. Since in CPython, this is the object's " @@ -1952,7 +2778,7 @@ msgid "" "memory. This is illustrated by this example:" msgstr "" -#: faq/programming.rst:1836 +#: faq/programming.rst:1843 msgid "" "The two ids belong to different integer objects that are created before, and " "deleted immediately after execution of the ``id()`` call. To be sure that " @@ -1960,17 +2786,17 @@ msgid "" "reference to the object:" msgstr "" -#: faq/programming.rst:1849 +#: faq/programming.rst:1856 msgid "When can I rely on identity tests with the *is* operator?" msgstr "" -#: faq/programming.rst:1851 +#: faq/programming.rst:1858 msgid "" "The ``is`` operator tests for object identity. The test ``a is b`` is " "equivalent to ``id(a) == id(b)``." msgstr "" -#: faq/programming.rst:1854 +#: faq/programming.rst:1861 msgid "" "The most important property of an identity test is that an object is always " "identical to itself, ``a is a`` always returns ``True``. Identity tests are " @@ -1978,34 +2804,34 @@ msgid "" "tests are guaranteed to return a boolean ``True`` or ``False``." msgstr "" -#: faq/programming.rst:1859 +#: faq/programming.rst:1866 msgid "" "However, identity tests can *only* be substituted for equality tests when " "object identity is assured. Generally, there are three circumstances where " "identity is guaranteed:" msgstr "" -#: faq/programming.rst:1863 +#: faq/programming.rst:1870 msgid "" "1) Assignments create new names but do not change object identity. After " "the assignment ``new = old``, it is guaranteed that ``new is old``." msgstr "" -#: faq/programming.rst:1866 +#: faq/programming.rst:1873 msgid "" "2) Putting an object in a container that stores object references does not " "change object identity. After the list assignment ``s[0] = x``, it is " "guaranteed that ``s[0] is x``." msgstr "" -#: faq/programming.rst:1870 +#: faq/programming.rst:1877 msgid "" "3) If an object is a singleton, it means that only one instance of that " "object can exist. After the assignments ``a = None`` and ``b = None``, it " "is guaranteed that ``a is b`` because ``None`` is a singleton." msgstr "" -#: faq/programming.rst:1874 +#: faq/programming.rst:1881 msgid "" "In most other circumstances, identity tests are inadvisable and equality " "tests are preferred. In particular, identity tests should not be used to " @@ -2013,17 +2839,40 @@ msgid "" "guaranteed to be singletons::" msgstr "" -#: faq/programming.rst:1891 -msgid "Likewise, new instances of mutable containers are never identical::" +#: faq/programming.rst:1886 +msgid "" +">>> a = 1000\n" +">>> b = 500\n" +">>> c = b + 500\n" +">>> a is c\n" +"False\n" +"\n" +">>> a = 'Python'\n" +">>> b = 'Py'\n" +">>> c = b + 'thon'\n" +">>> a is c\n" +"False" msgstr "" #: faq/programming.rst:1898 +msgid "Likewise, new instances of mutable containers are never identical::" +msgstr "" + +#: faq/programming.rst:1900 +msgid "" +">>> a = []\n" +">>> b = []\n" +">>> a is b\n" +"False" +msgstr "" + +#: faq/programming.rst:1905 msgid "" "In the standard library code, you will see several common patterns for " "correctly using identity tests:" msgstr "" -#: faq/programming.rst:1901 +#: faq/programming.rst:1908 msgid "" "1) As recommended by :pep:`8`, an identity test is the preferred way to " "check for ``None``. This reads like plain English in code and avoids " @@ -2031,7 +2880,7 @@ msgid "" "false." msgstr "" -#: faq/programming.rst:1905 +#: faq/programming.rst:1912 msgid "" "2) Detecting optional arguments can be tricky when ``None`` is a valid input " "value. In those situations, you can create a singleton sentinel object " @@ -2039,25 +2888,48 @@ msgid "" "implement a method that behaves like :meth:`dict.pop`::" msgstr "" -#: faq/programming.rst:1921 +#: faq/programming.rst:1917 +msgid "" +"_sentinel = object()\n" +"\n" +"def pop(self, key, default=_sentinel):\n" +" if key in self:\n" +" value = self[key]\n" +" del self[key]\n" +" return value\n" +" if default is _sentinel:\n" +" raise KeyError(key)\n" +" return default" +msgstr "" + +#: faq/programming.rst:1928 msgid "" "3) Container implementations sometimes need to augment equality tests with " "identity tests. This prevents the code from being confused by objects such " "as ``float('NaN')`` that are not equal to themselves." msgstr "" -#: faq/programming.rst:1925 +#: faq/programming.rst:1932 msgid "" "For example, here is the implementation of :meth:`!collections.abc.Sequence." "__contains__`::" msgstr "" -#: faq/programming.rst:1936 +#: faq/programming.rst:1935 +msgid "" +"def __contains__(self, value):\n" +" for v in self:\n" +" if v is value or v == value:\n" +" return True\n" +" return False" +msgstr "" + +#: faq/programming.rst:1943 msgid "" "How can a subclass control what data is stored in an immutable instance?" msgstr "" -#: faq/programming.rst:1938 +#: faq/programming.rst:1945 msgid "" "When subclassing an immutable type, override the :meth:`~object.__new__` " "method instead of the :meth:`~object.__init__` method. The latter only runs " @@ -2065,35 +2937,71 @@ msgid "" "immutable instance." msgstr "" -#: faq/programming.rst:1943 +#: faq/programming.rst:1950 msgid "" "All of these immutable classes have a different signature than their parent " "class:" msgstr "" -#: faq/programming.rst:1969 +#: faq/programming.rst:1953 +msgid "" +"from datetime import date\n" +"\n" +"class FirstOfMonthDate(date):\n" +" \"Always choose the first day of the month\"\n" +" def __new__(cls, year, month, day):\n" +" return super().__new__(cls, year, month, 1)\n" +"\n" +"class NamedInt(int):\n" +" \"Allow text names for some numbers\"\n" +" xlat = {'zero': 0, 'one': 1, 'ten': 10}\n" +" def __new__(cls, value):\n" +" value = cls.xlat.get(value, value)\n" +" return super().__new__(cls, value)\n" +"\n" +"class TitleStr(str):\n" +" \"Convert str to name suitable for a URL path\"\n" +" def __new__(cls, s):\n" +" s = s.lower().replace(' ', '-')\n" +" s = ''.join([c for c in s if c.isalnum() or c == '-'])\n" +" return super().__new__(cls, s)" +msgstr "" + +#: faq/programming.rst:1976 msgid "The classes can be used like this:" msgstr "" -#: faq/programming.rst:1986 +#: faq/programming.rst:1978 +msgid "" +">>> FirstOfMonthDate(2012, 2, 14)\n" +"FirstOfMonthDate(2012, 2, 1)\n" +">>> NamedInt('ten')\n" +"10\n" +">>> NamedInt(20)\n" +"20\n" +">>> TitleStr('Blog: Why Python Rocks')\n" +"'blog-why-python-rocks'" +msgstr "" + +#: faq/programming.rst:1993 msgid "How do I cache method calls?" msgstr "" -#: faq/programming.rst:1988 +#: faq/programming.rst:1995 msgid "" "The two principal tools for caching methods are :func:`functools." "cached_property` and :func:`functools.lru_cache`. The former stores results " "at the instance level and the latter at the class level." msgstr "" -#: faq/programming.rst:1993 +#: faq/programming.rst:2000 msgid "" "The *cached_property* approach only works with methods that do not take any " "arguments. It does not create a reference to the instance. The cached " "method result will be kept only as long as the instance is alive." msgstr "" -#: faq/programming.rst:1997 +#: faq/programming.rst:2004 msgid "" "The advantage is that when an instance is no longer used, the cached method " "result will be released right away. The disadvantage is that if instances " @@ -2101,47 +3009,95 @@ msgid "" "without bound." msgstr "" -#: faq/programming.rst:2002 +#: faq/programming.rst:2009 msgid "" "The *lru_cache* approach works with methods that have :term:`hashable` " "arguments. It creates a reference to the instance unless special efforts " "are made to pass in weak references." msgstr "" -#: faq/programming.rst:2006 +#: faq/programming.rst:2013 msgid "" "The advantage of the least recently used algorithm is that the cache is " "bounded by the specified *maxsize*. The disadvantage is that instances are " "kept alive until they age out of the cache or until the cache is cleared." msgstr "" -#: faq/programming.rst:2011 +#: faq/programming.rst:2018 msgid "This example shows the various techniques::" msgstr "" -#: faq/programming.rst:2035 +#: faq/programming.rst:2020 +msgid "" +"class Weather:\n" +" \"Lookup weather information on a government website\"\n" +"\n" +" def __init__(self, station_id):\n" +" self._station_id = station_id\n" +" # The _station_id is private and immutable\n" +"\n" +" def current_temperature(self):\n" +" \"Latest hourly observation\"\n" +" # Do not cache this because old results\n" +" # can be out of date.\n" +"\n" +" @cached_property\n" +" def location(self):\n" +" \"Return the longitude/latitude coordinates of the station\"\n" +" # Result only depends on the station_id\n" +"\n" +" @lru_cache(maxsize=20)\n" +" def historic_rainfall(self, date, units='mm'):\n" +" \"Rainfall on a given date\"\n" +" # Depends on the station_id, date, and units." +msgstr "" + +#: faq/programming.rst:2042 msgid "" "The above example assumes that the *station_id* never changes. If the " "relevant instance attributes are mutable, the *cached_property* approach " "can't be made to work because it cannot detect changes to the attributes." msgstr "" -#: faq/programming.rst:2040 +#: faq/programming.rst:2047 msgid "" "To make the *lru_cache* approach work when the *station_id* is mutable, the " "class needs to define the :meth:`~object.__eq__` and :meth:`~object." "__hash__` methods so that the cache can detect relevant attribute updates::" msgstr "" -#: faq/programming.rst:2066 +#: faq/programming.rst:2051 +msgid "" +"class Weather:\n" +" \"Example with a mutable station identifier\"\n" +"\n" +" def __init__(self, station_id):\n" +" self.station_id = station_id\n" +"\n" +" def change_station(self, station_id):\n" +" self.station_id = station_id\n" +"\n" +" def __eq__(self, other):\n" +" return self.station_id == other.station_id\n" +"\n" +" def __hash__(self):\n" +" return hash(self.station_id)\n" +"\n" +" @lru_cache(maxsize=20)\n" +" def historic_rainfall(self, date, units='cm'):\n" +" 'Rainfall on a given date'\n" +" # Depends on the station_id, date, and units." +msgstr "" + +#: faq/programming.rst:2073 msgid "Modules" msgstr "" -#: faq/programming.rst:2069 +#: faq/programming.rst:2076 msgid "How do I create a .pyc file?" msgstr "" -#: faq/programming.rst:2071 +#: faq/programming.rst:2078 msgid "" "When a module is imported for the first time (or when the source file has " "changed since the current compiled file was created) a ``.pyc`` file " @@ -2152,7 +3108,7 @@ msgid "" "particular ``python`` binary that created it. (See :pep:`3147` for details.)" msgstr "" -#: faq/programming.rst:2079 +#: faq/programming.rst:2086 msgid "" "One reason that a ``.pyc`` file may not be created is a permissions problem " "with the directory containing the source file, meaning that the " @@ -2161,7 +3117,7 @@ msgid "" "testing with a web server." msgstr "" -#: faq/programming.rst:2084 +#: faq/programming.rst:2091 msgid "" "Unless the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable is set, " "creation of a .pyc file is automatic if you're importing a module and Python " @@ -2170,7 +3126,7 @@ msgid "" "subdirectory." msgstr "" -#: faq/programming.rst:2089 +#: faq/programming.rst:2096 msgid "" "Running Python on a top level script is not considered an import and no ``." "pyc`` will be created. For example, if you have a top-level module ``foo." @@ -2180,27 +3136,33 @@ msgid "" "for ``foo`` since ``foo.py`` isn't being imported." msgstr "" -#: faq/programming.rst:2096 +#: faq/programming.rst:2103 msgid "" "If you need to create a ``.pyc`` file for ``foo`` -- that is, to create a ``." "pyc`` file for a module that is not imported -- you can, using the :mod:" "`py_compile` and :mod:`compileall` modules." msgstr "" -#: faq/programming.rst:2100 +#: faq/programming.rst:2107 msgid "" "The :mod:`py_compile` module can manually compile any module. One way is to " "use the ``compile()`` function in that module interactively::" msgstr "" -#: faq/programming.rst:2106 +#: faq/programming.rst:2110 +msgid "" +">>> import py_compile\n" +">>> py_compile.compile('foo.py') " +msgstr "" + +#: faq/programming.rst:2113 msgid "" "This will write the ``.pyc`` to a ``__pycache__`` subdirectory in the same " "location as ``foo.py`` (or you can override that with the optional parameter " "``cfile``)." msgstr "" -#: faq/programming.rst:2110 +#: faq/programming.rst:2117 msgid "" "You can also automatically compile all files in a directory or directories " "using the :mod:`compileall` module. You can do it from the shell prompt by " @@ -2208,11 +3170,15 @@ msgid "" "Python files to compile::" msgstr "" -#: faq/programming.rst:2119 +#: faq/programming.rst:2122 +msgid "python -m compileall ." +msgstr "" + +#: faq/programming.rst:2126 msgid "How do I find the current module name?" msgstr "" -#: faq/programming.rst:2121 +#: faq/programming.rst:2128 msgid "" "A module can find out its own module name by looking at the predefined " "global variable ``__name__``. If this has the value ``'__main__'``, the " @@ -2221,79 +3187,101 @@ msgid "" "only execute this code after checking ``__name__``::" msgstr "" -#: faq/programming.rst:2136 +#: faq/programming.rst:2134 +msgid "" +"def main():\n" +" print('Running test...')\n" +" ...\n" +"\n" +"if __name__ == '__main__':\n" +" main()" +msgstr "" + +#: faq/programming.rst:2143 msgid "How can I have modules that mutually import each other?" msgstr "" -#: faq/programming.rst:2138 +#: faq/programming.rst:2145 msgid "Suppose you have the following modules:" msgstr "" -#: faq/programming.rst:2140 +#: faq/programming.rst:2147 msgid ":file:`foo.py`::" msgstr "" -#: faq/programming.rst:2145 +#: faq/programming.rst:2149 +msgid "" +"from bar import bar_var\n" +"foo_var = 1" +msgstr "" + +#: faq/programming.rst:2152 msgid ":file:`bar.py`::" msgstr "" -#: faq/programming.rst:2150 +#: faq/programming.rst:2154 +msgid "" +"from foo import foo_var\n" +"bar_var = 2" +msgstr "" + +#: faq/programming.rst:2157 msgid "The problem is that the interpreter will perform the following steps:" msgstr "" -#: faq/programming.rst:2152 +#: faq/programming.rst:2159 msgid "main imports ``foo``" msgstr "" -#: faq/programming.rst:2153 +#: faq/programming.rst:2160 msgid "Empty globals for ``foo`` are created" msgstr "" -#: faq/programming.rst:2154 +#: faq/programming.rst:2161 msgid "``foo`` is compiled and starts executing" msgstr "" -#: faq/programming.rst:2155 +#: faq/programming.rst:2162 msgid "``foo`` imports ``bar``" msgstr "" -#: faq/programming.rst:2156 +#: faq/programming.rst:2163 msgid "Empty globals for ``bar`` are created" msgstr "" -#: faq/programming.rst:2157 +#: faq/programming.rst:2164 msgid "``bar`` is compiled and starts executing" msgstr "" -#: faq/programming.rst:2158 +#: faq/programming.rst:2165 msgid "" "``bar`` imports ``foo`` (which is a no-op since there already is a module " "named ``foo``)" msgstr "" -#: faq/programming.rst:2159 +#: faq/programming.rst:2166 msgid "" "The import mechanism tries to read ``foo_var`` from ``foo`` globals, to set " "``bar.foo_var = foo.foo_var``" msgstr "" -#: faq/programming.rst:2161 +#: faq/programming.rst:2168 msgid "" "The last step fails, because Python isn't done with interpreting ``foo`` yet " "and the global symbol dictionary for ``foo`` is still empty." msgstr "" -#: faq/programming.rst:2164 +#: faq/programming.rst:2171 msgid "" "The same thing happens when you use ``import foo``, and then try to access " "``foo.foo_var`` in global code." msgstr "" -#: faq/programming.rst:2167 +#: faq/programming.rst:2174 msgid "There are (at least) three possible workarounds for this problem." msgstr "" -#: faq/programming.rst:2169 +#: faq/programming.rst:2176 msgid "" "Guido van Rossum recommends avoiding all uses of ``from import ..." "``, and placing all code inside functions. Initializations of global " @@ -2302,59 +3290,63 @@ msgid "" "``.``." msgstr "" -#: faq/programming.rst:2174 +#: faq/programming.rst:2181 msgid "" "Jim Roskind suggests performing steps in the following order in each module:" msgstr "" -#: faq/programming.rst:2176 +#: faq/programming.rst:2183 msgid "" "exports (globals, functions, and classes that don't need imported base " "classes)" msgstr "" -#: faq/programming.rst:2178 +#: faq/programming.rst:2185 msgid "``import`` statements" msgstr "" -#: faq/programming.rst:2179 +#: faq/programming.rst:2186 msgid "" "active code (including globals that are initialized from imported values)." msgstr "" -#: faq/programming.rst:2181 +#: faq/programming.rst:2188 msgid "" "Van Rossum doesn't like this approach much because the imports appear in a " "strange place, but it does work." msgstr "" -#: faq/programming.rst:2184 +#: faq/programming.rst:2191 msgid "" "Matthias Urlichs recommends restructuring your code so that the recursive " "import is not necessary in the first place." msgstr "" -#: faq/programming.rst:2187 +#: faq/programming.rst:2194 msgid "These solutions are not mutually exclusive." msgstr "" -#: faq/programming.rst:2191 +#: faq/programming.rst:2198 msgid "__import__('x.y.z') returns ; how do I get z?" msgstr "" -#: faq/programming.rst:2193 +#: faq/programming.rst:2200 msgid "" "Consider using the convenience function :func:`~importlib.import_module` " "from :mod:`importlib` instead::" msgstr "" -#: faq/programming.rst:2200 +#: faq/programming.rst:2203 +msgid "z = importlib.import_module('x.y.z')" +msgstr "" + +#: faq/programming.rst:2207 msgid "" "When I edit an imported module and reimport it, the changes don't show up. " "Why does this happen?" msgstr "" -#: faq/programming.rst:2202 +#: faq/programming.rst:2209 msgid "" "For reasons of efficiency as well as consistency, Python only reads the " "module file on the first time a module is imported. If it didn't, in a " @@ -2363,13 +3355,24 @@ msgid "" "re-reading of a changed module, do this::" msgstr "" -#: faq/programming.rst:2212 +#: faq/programming.rst:2215 +msgid "" +"import importlib\n" +"import modname\n" +"importlib.reload(modname)" +msgstr "" + +#: faq/programming.rst:2219 msgid "" "Warning: this technique is not 100% fool-proof. In particular, modules " "containing statements like ::" msgstr "" -#: faq/programming.rst:2217 +#: faq/programming.rst:2222 +msgid "from modname import some_objects" +msgstr "" + +#: faq/programming.rst:2224 msgid "" "will continue to work with the old version of the imported objects. If the " "module contains class definitions, existing class instances will *not* be " @@ -2377,12 +3380,31 @@ msgid "" "paradoxical behaviour::" msgstr "" -#: faq/programming.rst:2230 +#: faq/programming.rst:2229 +msgid "" +">>> import importlib\n" +">>> import cls\n" +">>> c = cls.C() # Create an instance of C\n" +">>> importlib.reload(cls)\n" +"\n" +">>> isinstance(c, cls.C) # isinstance is false?!?\n" +"False" +msgstr "" + +#: faq/programming.rst:2237 msgid "" "The nature of the problem is made clear if you print out the \"identity\" of " "the class objects::" msgstr "" +#: faq/programming.rst:2240 +msgid "" +">>> hex(id(c.__class__))\n" +"'0x7352a0'\n" +">>> hex(id(cls.C))\n" +"'0x4198d0'" +msgstr "" + #: faq/programming.rst:408 msgid "argument" msgstr "" diff --git a/faq/windows.po b/faq/windows.po index cc96c27b7..6f90e4381 100644 --- a/faq/windows.po +++ b/faq/windows.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2022-12-17 01:28+0300\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -45,12 +45,20 @@ msgid "" "which usually looks like this:" msgstr "" +#: faq/windows.rst:35 +msgid "C:\\>" +msgstr "" + #: faq/windows.rst:39 msgid "" "The letter may be different, and there might be other things after it, so " "you might just as easily see something like:" msgstr "" +#: faq/windows.rst:42 +msgid "D:\\YourName\\Projects\\Python>" +msgstr "" + #: faq/windows.rst:46 msgid "" "depending on how your computer has been set up and what else you have " @@ -74,10 +82,23 @@ msgid "" "return:" msgstr "" +#: faq/windows.rst:60 +msgid "C:\\Users\\YourName> py" +msgstr "" + #: faq/windows.rst:64 msgid "You should then see something like:" msgstr "" +#: faq/windows.rst:66 +msgid "" +"Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit " +"(Intel)] on win32\n" +"Type \"help\", \"copyright\", \"credits\" or \"license\" for more " +"information.\n" +">>>" +msgstr "" + #: faq/windows.rst:72 msgid "" "You have started the interpreter in \"interactive mode\". That means you can " @@ -86,6 +107,14 @@ msgid "" "Check it by entering a few expressions of your choice and seeing the results:" msgstr "" +#: faq/windows.rst:77 +msgid "" +">>> print(\"Hello\")\n" +"Hello\n" +">>> \"Hello\" * 3\n" +"'HelloHelloHello'" +msgstr "" + #: faq/windows.rst:84 msgid "" "Many people use the interactive mode as a convenient yet highly programmable " @@ -114,12 +143,22 @@ msgid "" "home directory so you're seeing something similar to::" msgstr "" +#: faq/windows.rst:104 +msgid "C:\\Users\\YourName>" +msgstr "" + #: faq/windows.rst:106 msgid "" "So now you'll ask the ``py`` command to give your script to Python by typing " "``py`` followed by your script path::" msgstr "" +#: faq/windows.rst:110 +msgid "" +"C:\\Users\\YourName> py Desktop\\hello.py\n" +"hello" +msgstr "" + #: faq/windows.rst:114 msgid "How do I make Python scripts executable?" msgstr "" @@ -263,6 +302,15 @@ msgid "" "interpreter with your extension module." msgstr "" +#: faq/windows.rst:210 +msgid "" +"#include \n" +"...\n" +"Py_Initialize(); // Initialize Python.\n" +"initmyAppc(); // Initialize (import) the helper class.\n" +"PyRun_SimpleString(\"import myApp\"); // Import the shadow class." +msgstr "" + #: faq/windows.rst:218 msgid "" "There are two problems with Python's C API which will become apparent if you " @@ -283,6 +331,13 @@ msgid "" "void functions:" msgstr "" +#: faq/windows.rst:229 +msgid "" +"Py_INCREF(Py_None);\n" +"_resultobj = Py_None;\n" +"return _resultobj;" +msgstr "" + #: faq/windows.rst:235 msgid "" "Alas, Py_None is a macro that expands to a reference to a complex data " @@ -290,6 +345,10 @@ msgid "" "fail in a mult-compiler environment. Replace such code by:" msgstr "" +#: faq/windows.rst:239 +msgid "return Py_BuildValue(\"\");" +msgstr "" + #: faq/windows.rst:243 msgid "" "It may be possible to use SWIG's ``%typemap`` command to make the change " diff --git a/glossary.po b/glossary.po index a527828c9..0dae09fa2 100644 --- a/glossary.po +++ b/glossary.po @@ -6,7 +6,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: 2022-12-28 16:12-0500\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -166,6 +166,12 @@ msgstr "" "geçirilen bir argüman. Örneğin, ``3`` ve ``5``, aşağıdaki :func:`complex`: " "çağrılarında anahtar kelimenin argümanleridir:" +#: glossary.rst:72 +msgid "" +"complex(real=3, imag=5)\n" +"complex(**{'real': 3, 'imag': 5})" +msgstr "" + #: glossary.rst:75 msgid "" ":dfn:`positional argument`: an argument that is not a keyword argument. " @@ -179,6 +185,12 @@ msgstr "" "iletilebilir. Örneğin, ``3`` ve ``5``, aşağıdaki çağrılarda konumsal " "argümanlerdir:" +#: glossary.rst:81 +msgid "" +"complex(3, 5)\n" +"complex(*(3, 5))" +msgstr "" + #: glossary.rst:84 msgid "" "Arguments are assigned to the named local variables in a function body. See " @@ -514,6 +526,10 @@ msgstr "" "Bir çağrılabilir, muhtemelen bir dizi argümanla (bkz. :term:`argument`) ve " "aşağıdaki sözdizimiyle çağrılabilen bir nesnedir::" +#: glossary.rst:218 +msgid "callable(argument1, argument2, argumentN)" +msgstr "" + #: glossary.rst:220 msgid "" "A :term:`function`, and by extension a :term:`method`, is a callable. An " @@ -714,6 +730,17 @@ msgstr "" "Dekoratör sözdizimi yalnızca sözdizimsel şekerdir, aşağıdaki iki işlev " "tanımı anlamsal olarak eş değerdir:" +#: glossary.rst:303 +msgid "" +"def f(arg):\n" +" ...\n" +"f = staticmethod(f)\n" +"\n" +"@staticmethod\n" +"def f(arg):\n" +" ..." +msgstr "" + #: glossary.rst:311 msgid "" "The same concept exists for classes, but is less commonly used there. See " @@ -817,9 +844,9 @@ msgstr "belge dizisi" msgid "" "A string literal which appears as the first expression in a class, function " "or module. While ignored when the suite is executed, it is recognized by " -"the compiler and put into the :attr:`!__doc__` attribute of the enclosing " -"class, function or module. Since it is available via introspection, it is " -"the canonical place for documentation of the object." +"the compiler and put into the :attr:`~definition.__doc__` attribute of the " +"enclosing class, function or module. Since it is available via " +"introspection, it is the canonical place for documentation of the object." msgstr "" "Bir sınıf, işlev veya modülde ilk ifade olarak görünen bir dize değişmezi. " "Paket yürütüldüğünde yoksayılırken, derleyici tarafından tanınır ve " @@ -1037,7 +1064,8 @@ msgstr "" #: glossary.rst:440 #, fuzzy -msgid "See :ref:`importsystem` and :mod:`importlib` for much more detail." +msgid "" +"See :ref:`finders-and-loaders` and :mod:`importlib` for much more detail." msgstr "Daha fazla ayrıntı için :pep:`302`, :pep:`420` ve :pep:`451` bakın." #: glossary.rst:441 @@ -1094,6 +1122,12 @@ msgstr "" "kullanılır: örneğin, bu fonksiyonun iki :class:`int` argüman alması ve " "ayrıca bir :class:`int` dönüş değerine sahip olması beklenir ::" +#: glossary.rst:463 +msgid "" +"def sum_two_numbers(a: int, b: int) -> int:\n" +" return a + b" +msgstr "" + #: glossary.rst:466 msgid "Function annotation syntax is explained in section :ref:`function`." msgstr "İşlev açıklama sözdizimi :ref:`function` bölümünde açıklanmaktadır." @@ -1130,6 +1164,13 @@ msgstr "" "özelliğin ne zaman eklendiğini ve ne zaman varsayılan olacağını (ya da " "yaptığını) görebilirsiniz:" +#: glossary.rst:482 +msgid "" +">>> import __future__\n" +">>> __future__.division\n" +"_Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)" +msgstr "" + #: glossary.rst:485 msgid "garbage collection" msgstr "çöp toplama" @@ -1208,6 +1249,12 @@ msgstr "" "tümcesinin takip ettiği normal bir ifadeye benziyor. Birleştirilmiş ifade, " "bir çevreleyen için değerler üretir::" +#: glossary.rst:521 +msgid "" +">>> sum(i*i for i in range(10)) # sum of squares 0, 1, 4, ... 81\n" +"285" +msgstr "" + #: glossary.rst:523 msgid "generic function" msgstr "genel işlev" @@ -1379,10 +1426,27 @@ msgstr "" "dağıtımıyla birlikte gelen temel bir düzenleyici ve yorumlayıcı ortamıdır." #: glossary.rst:593 +msgid "immortal" +msgstr "" + +#: glossary.rst:595 +msgid "" +"*Immortal objects* are a CPython implementation detail introduced in :pep:" +"`683`." +msgstr "" + +#: glossary.rst:598 +msgid "" +"If an object is immortal, its :term:`reference count` is never modified, and " +"therefore it is never deallocated while the interpreter is running. For " +"example, :const:`True` and :const:`None` are immortal in CPython." +msgstr "" + +#: glossary.rst:601 msgid "immutable" msgstr "değişmez" -#: glossary.rst:595 +#: glossary.rst:603 msgid "" "An object with a fixed value. Immutable objects include numbers, strings " "and tuples. Such an object cannot be altered. A new object has to be " @@ -1396,11 +1460,11 @@ msgstr "" "sözlükte anahtar olarak, sabit bir karma değerinin gerekli olduğu yerlerde " "önemli bir rol oynarlar." -#: glossary.rst:600 +#: glossary.rst:608 msgid "import path" msgstr "içe aktarım yolu" -#: glossary.rst:602 +#: glossary.rst:610 msgid "" "A list of locations (or :term:`path entries `) that are searched " "by the :term:`path based finder` for modules to import. During import, this " @@ -1412,11 +1476,11 @@ msgstr "" "sırasında, bu konum listesi genellikle :data:`sys.path` adresinden gelir, " "ancak alt paketler için üst paketin ``__path__`` özelliğinden de gelebilir." -#: glossary.rst:607 +#: glossary.rst:615 msgid "importing" msgstr "içe aktarma" -#: glossary.rst:609 +#: glossary.rst:617 msgid "" "The process by which Python code in one module is made available to Python " "code in another module." @@ -1424,11 +1488,11 @@ msgstr "" "Bir modüldeki Python kodunun başka bir modüldeki Python koduna sunulması " "süreci." -#: glossary.rst:611 +#: glossary.rst:619 msgid "importer" msgstr "içe aktarıcı" -#: glossary.rst:613 +#: glossary.rst:621 msgid "" "An object that both finds and loads a module; both a :term:`finder` and :" "term:`loader` object." @@ -1436,11 +1500,11 @@ msgstr "" "Bir modülü hem bulan hem de yükleyen bir nesne; hem bir :term:`finder` hem " "de :term:`loader` nesnesi." -#: glossary.rst:615 +#: glossary.rst:623 msgid "interactive" msgstr "etkileşimli" -#: glossary.rst:617 +#: glossary.rst:625 msgid "" "Python has an interactive interpreter which means you can enter statements " "and expressions at the interpreter prompt, immediately execute them and see " @@ -1455,11 +1519,11 @@ msgstr "" "menüsünden seçerek). Yeni fikirleri test etmenin veya modülleri ve paketleri " "incelemenin çok güçlü bir yoludur (``help(x)`` 'i unutmayın)." -#: glossary.rst:623 +#: glossary.rst:631 msgid "interpreted" msgstr "yorumlanmış" -#: glossary.rst:625 +#: glossary.rst:633 msgid "" "Python is an interpreted language, as opposed to a compiled one, though the " "distinction can be blurry because of the presence of the bytecode compiler. " @@ -1476,11 +1540,11 @@ msgstr "" "sahiptir, ancak programları genellikle daha yavaş çalışır. Ayrıca bkz. :" "term:`interactive`." -#: glossary.rst:632 +#: glossary.rst:640 msgid "interpreter shutdown" msgstr "tercüman kapatma" -#: glossary.rst:634 +#: glossary.rst:642 msgid "" "When asked to shut down, the Python interpreter enters a special phase where " "it gradually releases all allocated resources, such as modules and various " @@ -1500,7 +1564,7 @@ msgstr "" "çeşitli istisnalarla karşılaşabilir (yaygın örnekler kütüphane modülleri " "veya uyarı makineleridir)." -#: glossary.rst:643 +#: glossary.rst:651 msgid "" "The main reason for interpreter shutdown is that the ``__main__`` module or " "the script being run has finished executing." @@ -1508,11 +1572,11 @@ msgstr "" "Yorumlayıcının kapatılmasının ana nedeni, ``__main__`` modülünün veya " "çalıştırılan betiğin yürütmeyi bitirmiş olmasıdır." -#: glossary.rst:645 +#: glossary.rst:653 msgid "iterable" msgstr "yinelenebilir" -#: glossary.rst:647 +#: glossary.rst:655 #, fuzzy msgid "" "An object capable of returning its members one at a time. Examples of " @@ -1529,7 +1593,7 @@ msgstr "" "uygulayan bir :meth:`__getitem__` yöntemiyle tanımladığınız tüm sınıfların " "nesnelerini içerir." -#: glossary.rst:655 +#: glossary.rst:663 #, fuzzy msgid "" "Iterables can be used in a :keyword:`for` loop and in many other places " @@ -1553,11 +1617,11 @@ msgstr "" "oluşturur. Ayrıca bkz. :term:`iterator`, :term:`sequence` ve :term:" "`generator`." -#: glossary.rst:665 +#: glossary.rst:673 msgid "iterator" msgstr "yineleyici" -#: glossary.rst:667 +#: glossary.rst:675 #, fuzzy msgid "" "An object representing a stream of data. Repeated calls to the iterator's :" @@ -1591,11 +1655,11 @@ msgstr "" "yineleyiciyle denemek, önceki yineleme geçişinde kullanılan aynı tükenmiş " "yineleyici nesnesini döndürerek boş bir kap gibi görünmesini sağlar." -#: glossary.rst:682 +#: glossary.rst:690 msgid "More information can be found in :ref:`typeiter`." msgstr "Daha fazla bilgi :ref:`typeiter` içinde bulunabilir." -#: glossary.rst:686 +#: glossary.rst:694 #, fuzzy msgid "" "CPython does not consistently apply the requirement that an iterator define :" @@ -1604,11 +1668,11 @@ msgstr "" "CPython, bir yineleyicinin :meth:`__iter__` tanımlaması gereksinimini " "tutarlı bir şekilde uygulamaz." -#: glossary.rst:688 +#: glossary.rst:696 msgid "key function" msgstr "anahtar işlev" -#: glossary.rst:690 +#: glossary.rst:698 msgid "" "A key function or collation function is a callable that returns a value used " "for sorting or ordering. For example, :func:`locale.strxfrm` is used to " @@ -1619,7 +1683,7 @@ msgstr "" "strxfrm`, yerel ayara özgü sıralama kurallarının farkında olan bir sıralama " "anahtarı üretmek için kullanılır." -#: glossary.rst:695 +#: glossary.rst:703 msgid "" "A number of tools in Python accept key functions to control how elements are " "ordered or grouped. They include :func:`min`, :func:`max`, :func:`sorted`, :" @@ -1632,7 +1696,7 @@ msgstr "" "merge`, :func:`heapq.nsmallest`, :func:`heapq.nlargest` ve :func:`itertools." "groupby`." -#: glossary.rst:701 +#: glossary.rst:709 msgid "" "There are several ways to create a key function. For example. the :meth:" "`str.lower` method can serve as a key function for case insensitive sorts. " @@ -1652,19 +1716,19 @@ msgstr "" "kullanılacağına ilişkin örnekler için :ref:`Sorting HOW TO ` " "bölümüne bakın." -#: glossary.rst:708 +#: glossary.rst:716 msgid "keyword argument" msgstr "anahtar kelime argümanı" -#: glossary.rst:1000 +#: glossary.rst:1013 msgid "See :term:`argument`." msgstr "Bakınız :term:`argument`." -#: glossary.rst:711 +#: glossary.rst:719 msgid "lambda" msgstr "lambda" -#: glossary.rst:713 +#: glossary.rst:721 msgid "" "An anonymous inline function consisting of a single :term:`expression` which " "is evaluated when the function is called. The syntax to create a lambda " @@ -1674,11 +1738,11 @@ msgstr "" "anonim bir satır içi işlev. Bir lambda işlevi oluşturmak için sözdizimi " "``lambda [parametreler]: ifade`` şeklindedir" -#: glossary.rst:716 +#: glossary.rst:724 msgid "LBYL" msgstr "LBYL" -#: glossary.rst:718 +#: glossary.rst:726 msgid "" "Look before you leap. This coding style explicitly tests for pre-conditions " "before making calls or lookups. This style contrasts with the :term:`EAFP` " @@ -1689,7 +1753,7 @@ msgstr "" "koşulları açıkça test eder. Bu stil, :term:`EAFP` yaklaşımıyla çelişir ve " "birçok :keyword:`if` ifadesinin varlığı ile karakterize edilir." -#: glossary.rst:723 +#: glossary.rst:731 msgid "" "In a multi-threaded environment, the LBYL approach can risk introducing a " "race condition between \"the looking\" and \"the leaping\". For example, " @@ -1703,11 +1767,11 @@ msgstr "" "başka bir iş parçacığı *eşlemeden* *key* kaldırırsa başarısız olabilir. Bu " "sorun, kilitlerle veya EAFP yaklaşımı kullanılarak çözülebilir." -#: glossary.rst:728 +#: glossary.rst:736 msgid "list" msgstr "liste" -#: glossary.rst:730 +#: glossary.rst:738 #, fuzzy msgid "" "A built-in Python :term:`sequence`. Despite its name it is more akin to an " @@ -1718,11 +1782,11 @@ msgstr "" "olduğundan, diğer dillerdeki bir diziye, bağlantılı bir listeden daha " "yakındır." -#: glossary.rst:733 +#: glossary.rst:741 msgid "list comprehension" msgstr "liste anlama" -#: glossary.rst:735 +#: glossary.rst:743 msgid "" "A compact way to process all or part of the elements in a sequence and " "return a list with the results. ``result = ['{:#04x}'.format(x) for x in " @@ -1737,27 +1801,39 @@ msgstr "" "tümcesi isteğe bağlıdır. Atlanırsa, \"aralık(256)\" içindeki tüm öğeler " "işlenir." -#: glossary.rst:741 +#: glossary.rst:749 msgid "loader" msgstr "yükleyici" -#: glossary.rst:743 +#: glossary.rst:751 +#, fuzzy msgid "" "An object that loads a module. It must define a method named :meth:" -"`load_module`. A loader is typically returned by a :term:`finder`. See :pep:" -"`302` for details and :class:`importlib.abc.Loader` for an :term:`abstract " -"base class`." +"`load_module`. A loader is typically returned by a :term:`finder`. See also:" msgstr "" "Modül yükleyen bir nesne. :meth:`load_module` adında bir yöntem " "tanımlamalıdır. Bir yükleyici genellikle bir :term:`finder` ile döndürülür. " "Ayrıntılar için :pep:`302` ve bir :term:`soyut temel sınıf` için :class:" "`importlib.abc.Loader` bölümüne bakın." -#: glossary.rst:747 +#: glossary.rst:755 +msgid ":ref:`finders-and-loaders`" +msgstr "" + +#: glossary.rst:756 +msgid ":class:`importlib.abc.Loader`" +msgstr "" + +#: glossary.rst:757 +#, fuzzy +msgid ":pep:`302`" +msgstr "Bakınız :pep:`1`." + +#: glossary.rst:758 msgid "locale encoding" msgstr "yerel kodlama" -#: glossary.rst:749 +#: glossary.rst:760 msgid "" "On Unix, it is the encoding of the LC_CTYPE locale. It can be set with :func:" "`locale.setlocale(locale.LC_CTYPE, new_locale) `." @@ -1765,38 +1841,38 @@ msgstr "" "Unix'te, LC_CTYPE yerel ayarının kodlamasıdır. :func:`locale." "setlocale(locale.LC_CTYPE, new_locale) ` ile ayarlanabilir." -#: glossary.rst:752 +#: glossary.rst:763 msgid "On Windows, it is the ANSI code page (ex: ``\"cp1252\"``)." msgstr "Windows'ta bu, ANSI kod sayfasıdır (ör. ``\"cp1252\"``)." -#: glossary.rst:754 +#: glossary.rst:765 msgid "" "On Android and VxWorks, Python uses ``\"utf-8\"`` as the locale encoding." msgstr "" "Android ve VxWorks'te Python, yerel kodlama olarak ``\"utf-8\"`` kullanır." -#: glossary.rst:756 +#: glossary.rst:767 #, fuzzy msgid ":func:`locale.getencoding` can be used to get the locale encoding." msgstr "Yerel kodlamayı almak için ``locale.getencoding()`` kullanılabilir." -#: glossary.rst:758 +#: glossary.rst:769 msgid "See also the :term:`filesystem encoding and error handler`." msgstr "Ayrıca :term:`filesystem encoding and error handler` 'ne bakın." -#: glossary.rst:759 +#: glossary.rst:770 msgid "magic method" msgstr "sihirli yöntem" -#: glossary.rst:763 +#: glossary.rst:774 msgid "An informal synonym for :term:`special method`." msgstr ":term:`special method` için gayri resmi bir eşanlamlı." -#: glossary.rst:764 +#: glossary.rst:775 msgid "mapping" msgstr "haritalama" -#: glossary.rst:766 +#: glossary.rst:777 msgid "" "A container object that supports arbitrary key lookups and implements the " "methods specified in the :class:`collections.abc.Mapping` or :class:" @@ -1811,11 +1887,11 @@ msgstr "" "Örnekler arasında :class:`dict`, :class:`collections.defaultdict`, :class:" "`collections.OrderedDict` ve :class:`collections.Counter` sayılabilir." -#: glossary.rst:772 +#: glossary.rst:783 msgid "meta path finder" msgstr "meta yol bulucu" -#: glossary.rst:774 +#: glossary.rst:785 msgid "" "A :term:`finder` returned by a search of :data:`sys.meta_path`. Meta path " "finders are related to, but different from :term:`path entry finders ` ile " "ilişkilidir, ancak onlardan farklıdır." -#: glossary.rst:778 +#: glossary.rst:789 msgid "" "See :class:`importlib.abc.MetaPathFinder` for the methods that meta path " "finders implement." @@ -1833,11 +1909,11 @@ msgstr "" "Meta yol bulucuların uyguladığı yöntemler için :class:`importlib.abc." "MetaPathFinder` bölümüne bakın." -#: glossary.rst:780 +#: glossary.rst:791 msgid "metaclass" msgstr "metasınıf" -#: glossary.rst:782 +#: glossary.rst:793 msgid "" "The class of a class. Class definitions create a class name, a class " "dictionary, and a list of base classes. The metaclass is responsible for " @@ -1859,15 +1935,15 @@ msgstr "" "parçacığı güvenliği eklemek, nesne oluşturmayı izlemek, tekilleri uygulamak " "ve diğer birçok görev için kullanılmışlardır." -#: glossary.rst:792 +#: glossary.rst:803 msgid "More information can be found in :ref:`metaclasses`." msgstr "Daha fazla bilgi :ref:`metaclasses` içinde bulunabilir." -#: glossary.rst:1130 +#: glossary.rst:1154 msgid "method" msgstr "metot" -#: glossary.rst:795 +#: glossary.rst:806 msgid "" "A function which is defined inside a class body. If called as an attribute " "of an instance of that class, the method will get the instance object as its " @@ -1879,11 +1955,11 @@ msgstr "" "(genellikle ``self`` olarak adlandırılır) olarak alır. Bkz. :term:`function` " "ve :term:`nested scope`." -#: glossary.rst:799 +#: glossary.rst:810 msgid "method resolution order" msgstr "metot kalite sıralaması" -#: glossary.rst:801 +#: glossary.rst:812 #, fuzzy msgid "" "Method Resolution Order is the order in which base classes are searched for " @@ -1895,11 +1971,11 @@ msgstr "" "algoritmanın ayrıntıları için bkz. `The Python 2.3 Method Resolution Order " "`_." -#: glossary.rst:804 +#: glossary.rst:815 msgid "module" msgstr "modül" -#: glossary.rst:806 +#: glossary.rst:817 msgid "" "An object that serves as an organizational unit of Python code. Modules " "have a namespace containing arbitrary Python objects. Modules are loaded " @@ -1909,15 +1985,15 @@ msgstr "" "rastgele Python nesneleri içeren bir ad alanına sahiptir. Modüller, :term:" "`importing` işlemiyle Python'a yüklenir." -#: glossary.rst:810 +#: glossary.rst:821 msgid "See also :term:`package`." msgstr "Ayrıca bakınız :term:`package`." -#: glossary.rst:811 +#: glossary.rst:822 msgid "module spec" msgstr "modül özelliği" -#: glossary.rst:813 +#: glossary.rst:824 msgid "" "A namespace containing the import-related information used to load a module. " "An instance of :class:`importlib.machinery.ModuleSpec`." @@ -1925,19 +2001,24 @@ msgstr "" "Bir modülü yüklemek için kullanılan içe aktarmayla ilgili bilgileri içeren " "bir ad alanı. Bir :class:`importlib.machinery.ModuleSpec` örneği." -#: glossary.rst:815 +#: glossary.rst:827 +#, fuzzy +msgid "See also :ref:`module-specs`." +msgstr "Ayrıca bkz. :term:`module`." + +#: glossary.rst:828 msgid "MRO" msgstr "MRO" -#: glossary.rst:817 +#: glossary.rst:830 msgid "See :term:`method resolution order`." msgstr "Bakınız :term:`metot çözüm sırası `." -#: glossary.rst:818 +#: glossary.rst:831 msgid "mutable" msgstr "değiştirilebilir" -#: glossary.rst:820 +#: glossary.rst:833 msgid "" "Mutable objects can change their value but keep their :func:`id`. See also :" "term:`immutable`." @@ -1945,11 +2026,11 @@ msgstr "" "Değiştirilebilir (mutable) nesneler değerlerini değiştirebilir ancak :func:" "`idlerini ` koruyabilirler. Ayrıca bkz. :term:`immutable`." -#: glossary.rst:822 +#: glossary.rst:835 msgid "named tuple" msgstr "adlandırılmış demet" -#: glossary.rst:824 +#: glossary.rst:837 msgid "" "The term \"named tuple\" applies to any type or class that inherits from " "tuple and whose indexable elements are also accessible using named " @@ -1959,7 +2040,7 @@ msgstr "" "adlandırılmış nitelikler kullanılarak erişilebilen herhangi bir tür veya " "sınıf için geçerlidir. Tür veya sınıfın başka özellikleri de olabilir." -#: glossary.rst:828 +#: glossary.rst:841 msgid "" "Several built-in types are named tuples, including the values returned by :" "func:`time.localtime` and :func:`os.stat`. Another example is :data:`sys." @@ -1969,7 +2050,17 @@ msgstr "" "tarafından döndürülen değerler de dahil olmak üzere, tanımlama grupları " "olarak adlandırılır. Başka bir örnek :data:`sys.float_info`::" -#: glossary.rst:839 +#: glossary.rst:845 +msgid "" +">>> sys.float_info[1] # indexed access\n" +"1024\n" +">>> sys.float_info.max_exp # named field access\n" +"1024\n" +">>> isinstance(sys.float_info, tuple) # kind of tuple\n" +"True" +msgstr "" + +#: glossary.rst:852 #, fuzzy msgid "" "Some named tuples are built-in types (such as the above examples). " @@ -1988,11 +2079,11 @@ msgstr "" "yazılmış veya yerleşik adlandırılmış demetlerde bulunmayan bazı ekstra " "yöntemler ekler." -#: glossary.rst:847 +#: glossary.rst:860 msgid "namespace" msgstr "ad alanı" -#: glossary.rst:849 +#: glossary.rst:862 msgid "" "The place where a variable is stored. Namespaces are implemented as " "dictionaries. There are the local, global and built-in namespaces as well " @@ -2014,11 +2105,11 @@ msgstr "" "yazmak, bu işlevlerin sırasıyla :mod:`random` ve :mod:`itertools` modülleri " "tarafından uygulandığını açıkça gösterir." -#: glossary.rst:859 +#: glossary.rst:872 msgid "namespace package" msgstr "ad alanı paketi" -#: glossary.rst:861 +#: glossary.rst:874 msgid "" "A :pep:`420` :term:`package` which serves only as a container for " "subpackages. Namespace packages may have no physical representation, and " @@ -2030,15 +2121,15 @@ msgstr "" "``__init__.py`` dosyası olmadığından özellikle :term:`regular package` gibi " "değildirler." -#: glossary.rst:866 +#: glossary.rst:879 msgid "See also :term:`module`." msgstr "Ayrıca bkz. :term:`module`." -#: glossary.rst:867 +#: glossary.rst:880 msgid "nested scope" msgstr "iç içe kapsam" -#: glossary.rst:869 +#: glossary.rst:882 msgid "" "The ability to refer to a variable in an enclosing definition. For " "instance, a function defined inside another function can refer to variables " @@ -2055,11 +2146,11 @@ msgstr "" "global değişkenler global ad alanını okur ve yazar. :keyword:`nonlocal`, dış " "kapsamlara yazmaya izin verir." -#: glossary.rst:876 +#: glossary.rst:889 msgid "new-style class" msgstr "yeni stil sınıf" -#: glossary.rst:878 +#: glossary.rst:891 #, fuzzy msgid "" "Old name for the flavor of classes now used for all class objects. In " @@ -2073,11 +2164,11 @@ msgstr "" "sınıf yöntemleri ve statik yöntemler gibi daha yeni, çok yönlü özelliklerini " "kullanabilirdi." -#: glossary.rst:883 +#: glossary.rst:896 msgid "object" msgstr "obje" -#: glossary.rst:885 +#: glossary.rst:898 msgid "" "Any data with state (attributes or value) and defined behavior (methods). " "Also the ultimate base class of any :term:`new-style class`." @@ -2086,11 +2177,11 @@ msgstr "" "herhangi bir veri. Ayrıca herhangi bir :term:`yeni tarz sınıfın ` nihai temel sınıfı." -#: glossary.rst:888 +#: glossary.rst:901 msgid "package" msgstr "paket" -#: glossary.rst:890 +#: glossary.rst:903 msgid "" "A Python :term:`module` which can contain submodules or recursively, " "subpackages. Technically, a package is a Python module with a ``__path__`` " @@ -2100,15 +2191,15 @@ msgstr "" "`module`. Teknik olarak bir paket, ``__path__`` özniteliğine sahip bir " "Python modülüdür." -#: glossary.rst:894 +#: glossary.rst:907 msgid "See also :term:`regular package` and :term:`namespace package`." msgstr "Ayrıca bkz. :term:`regular package` ve :term:`namespace package`." -#: glossary.rst:895 +#: glossary.rst:908 msgid "parameter" msgstr "parametre" -#: glossary.rst:897 +#: glossary.rst:910 msgid "" "A named entity in a :term:`function` (or method) definition that specifies " "an :term:`argument` (or in some cases, arguments) that the function can " @@ -2118,7 +2209,7 @@ msgstr "" "term:`argument` (veya bazı durumlarda, argümanlar) belirten adlandırılmış " "bir varlık. Beş çeşit parametre vardır:" -#: glossary.rst:901 +#: glossary.rst:914 msgid "" ":dfn:`positional-or-keyword`: specifies an argument that can be passed " "either :term:`positionally ` or as a :term:`keyword argument " @@ -2129,7 +2220,11 @@ msgstr "" "`keyword argümanı ` olarak iletilebilen bir argüman belirtir. Bu, " "varsayılan parametre türüdür, örneğin aşağıdakilerde *foo* ve *bar*::" -#: glossary.rst:910 +#: glossary.rst:919 +msgid "def func(foo, bar=None): ..." +msgstr "" + +#: glossary.rst:923 msgid "" ":dfn:`positional-only`: specifies an argument that can be supplied only by " "position. Positional-only parameters can be defined by including a ``/`` " @@ -2141,7 +2236,11 @@ msgstr "" "parametre listesine bir ``/`` karakteri eklenerek tanımlanabilir, örneğin " "aşağıdakilerde *posonly1* ve *posonly2*::" -#: glossary.rst:919 +#: glossary.rst:928 +msgid "def func(posonly1, posonly2, /, positional_or_keyword): ..." +msgstr "" + +#: glossary.rst:932 msgid "" ":dfn:`keyword-only`: specifies an argument that can be supplied only by " "keyword. Keyword-only parameters can be defined by including a single var-" @@ -2155,7 +2254,11 @@ msgstr "" "parametre veya çıplak ``*`` dahil edilerek tanımlanabilir, örneğin " "aşağıdakilerde *kw_only1* ve *kw_only2*::" -#: glossary.rst:927 +#: glossary.rst:938 +msgid "def func(arg, *, kw_only1, kw_only2): ..." +msgstr "" + +#: glossary.rst:940 msgid "" ":dfn:`var-positional`: specifies that an arbitrary sequence of positional " "arguments can be provided (in addition to any positional arguments already " @@ -2169,7 +2272,11 @@ msgstr "" "parametre adının başına ``*`` eklenerek tanımlanabilir, örneğin " "aşağıdakilerde *args*::" -#: glossary.rst:935 +#: glossary.rst:946 +msgid "def func(*args, **kwargs): ..." +msgstr "" + +#: glossary.rst:948 msgid "" ":dfn:`var-keyword`: specifies that arbitrarily many keyword arguments can be " "provided (in addition to any keyword arguments already accepted by other " @@ -2182,7 +2289,7 @@ msgstr "" "parametre adının başına ``**``, örneğin yukarıdaki örnekte *kwargs* " "eklenerek tanımlanabilir." -#: glossary.rst:941 +#: glossary.rst:954 msgid "" "Parameters can specify both optional and required arguments, as well as " "default values for some optional arguments." @@ -2190,7 +2297,7 @@ msgstr "" "Parametreler, hem isteğe bağlı hem de gerekli argümanleri ve ayrıca bazı " "isteğe bağlı bağımsız değişkenler için varsayılan değerleri belirtebilir." -#: glossary.rst:944 +#: glossary.rst:957 msgid "" "See also the :term:`argument` glossary entry, the FAQ question on :ref:`the " "difference between arguments and parameters `, " @@ -2201,11 +2308,11 @@ msgstr "" "arasındaki fark `, :class:`inspect.Parameter`, :" "ref:`function` ve :pep:`362`." -#: glossary.rst:948 +#: glossary.rst:961 msgid "path entry" msgstr "yol girişi" -#: glossary.rst:950 +#: glossary.rst:963 msgid "" "A single location on the :term:`import path` which the :term:`path based " "finder` consults to find modules for importing." @@ -2213,11 +2320,11 @@ msgstr "" ":term:`path based finder` içe aktarma modüllerini bulmak için başvurduğu :" "term:`import path` üzerindeki tek bir konum." -#: glossary.rst:952 +#: glossary.rst:965 msgid "path entry finder" msgstr "yol girişi bulucu" -#: glossary.rst:954 +#: glossary.rst:967 msgid "" "A :term:`finder` returned by a callable on :data:`sys.path_hooks` (i.e. a :" "term:`path entry hook`) which knows how to locate modules given a :term:" @@ -2227,7 +2334,7 @@ msgstr "" "kancası`) üzerinde bir çağrılabilir tarafından döndürülür ve :term:`path " "entry` verilen modüllerin nasıl bulunacağını bilir." -#: glossary.rst:958 +#: glossary.rst:971 msgid "" "See :class:`importlib.abc.PathEntryFinder` for the methods that path entry " "finders implement." @@ -2235,11 +2342,11 @@ msgstr "" "Yol girişi bulucularının uyguladığı yöntemler için :class:`importlib.abc." "PathEntryFinder` bölümüne bakın." -#: glossary.rst:960 +#: glossary.rst:973 msgid "path entry hook" msgstr "yol giriş kancası" -#: glossary.rst:962 +#: glossary.rst:975 #, fuzzy msgid "" "A callable on the :data:`sys.path_hooks` list which returns a :term:`path " @@ -2250,11 +2357,11 @@ msgstr "" "entry>` modülleri nasıl bulacağını biliyorsa, bir :term:`yol girişi bulucu " "` döndüren bir çağrılabilir." -#: glossary.rst:965 +#: glossary.rst:978 msgid "path based finder" msgstr "yol tabanlı bulucu" -#: glossary.rst:967 +#: glossary.rst:980 msgid "" "One of the default :term:`meta path finders ` which " "searches an :term:`import path` for modules." @@ -2262,11 +2369,11 @@ msgstr "" "Modüller için bir :term:`import path` arayan varsayılan :term:`meta yol " "buluculardan ` biri." -#: glossary.rst:969 +#: glossary.rst:982 msgid "path-like object" msgstr "yol benzeri nesne" -#: glossary.rst:971 +#: glossary.rst:984 msgid "" "An object representing a file system path. A path-like object is either a :" "class:`str` or :class:`bytes` object representing a path, or an object " @@ -2286,11 +2393,11 @@ msgstr "" "veya :class:`bytes` sonucunu garanti etmek için kullanılabilir. :pep:`519` " "tarafından tanıtıldı." -#: glossary.rst:979 +#: glossary.rst:992 msgid "PEP" msgstr "PEP" -#: glossary.rst:981 +#: glossary.rst:994 msgid "" "Python Enhancement Proposal. A PEP is a design document providing " "information to the Python community, or describing a new feature for Python " @@ -2302,7 +2409,7 @@ msgstr "" "tasarım belgesidir. PEP'ler, önerilen özellikler için özlü bir teknik " "şartname ve bir gerekçe sağlamalıdır." -#: glossary.rst:987 +#: glossary.rst:1000 msgid "" "PEPs are intended to be the primary mechanisms for proposing major new " "features, for collecting community input on an issue, and for documenting " @@ -2315,15 +2422,15 @@ msgstr "" "birincil mekanizmalar olması amaçlanmıştır. PEP yazarı, topluluk içinde " "fikir birliği oluşturmaktan ve muhalif görüşleri belgelemekten sorumludur." -#: glossary.rst:993 +#: glossary.rst:1006 msgid "See :pep:`1`." msgstr "Bakınız :pep:`1`." -#: glossary.rst:994 +#: glossary.rst:1007 msgid "portion" msgstr "kısım" -#: glossary.rst:996 +#: glossary.rst:1009 msgid "" "A set of files in a single directory (possibly stored in a zip file) that " "contribute to a namespace package, as defined in :pep:`420`." @@ -2331,15 +2438,15 @@ msgstr "" ":pep:`420` içinde tanımlandığı gibi, bir ad alanı paketine katkıda bulunan " "tek bir dizindeki (muhtemelen bir zip dosyasında depolanan) bir dizi dosya." -#: glossary.rst:998 +#: glossary.rst:1011 msgid "positional argument" msgstr "konumsal argüman" -#: glossary.rst:1001 +#: glossary.rst:1014 msgid "provisional API" msgstr "geçici API" -#: glossary.rst:1003 +#: glossary.rst:1016 msgid "" "A provisional API is one which has been deliberately excluded from the " "standard library's backwards compatibility guarantees. While major changes " @@ -2358,7 +2465,7 @@ msgstr "" "yalnızca API'nin eklenmesinden önce gözden kaçan ciddi temel kusurlar ortaya " "çıkarsa gerçekleşecektir." -#: glossary.rst:1012 +#: glossary.rst:1025 msgid "" "Even for provisional APIs, backwards incompatible changes are seen as a " "\"solution of last resort\" - every attempt will still be made to find a " @@ -2368,7 +2475,7 @@ msgstr "" "çözümü\" olarak görülür - tanımlanan herhangi bir soruna geriye dönük uyumlu " "bir çözüm bulmak için her türlü girişimde bulunulacaktır." -#: glossary.rst:1016 +#: glossary.rst:1029 msgid "" "This process allows the standard library to continue to evolve over time, " "without locking in problematic design errors for extended periods of time. " @@ -2378,19 +2485,19 @@ msgstr "" "hatalarına kilitlenmeden zaman içinde gelişmeye devam etmesini sağlar. Daha " "fazla ayrıntı için bkz. :pep:`411`." -#: glossary.rst:1019 +#: glossary.rst:1032 msgid "provisional package" msgstr "geçici paket" -#: glossary.rst:1021 +#: glossary.rst:1034 msgid "See :term:`provisional API`." msgstr "Bakınız :term:`provisional API`." -#: glossary.rst:1022 +#: glossary.rst:1035 msgid "Python 3000" msgstr "Python 3000" -#: glossary.rst:1024 +#: glossary.rst:1037 msgid "" "Nickname for the Python 3.x release line (coined long ago when the release " "of version 3 was something in the distant future.) This is also abbreviated " @@ -2400,11 +2507,11 @@ msgstr "" "sürülmesi uzak bir gelecekte olduğu zaman ortaya çıktı.) Bu aynı zamanda " "\"Py3k\" olarak da kısaltılır." -#: glossary.rst:1027 +#: glossary.rst:1040 msgid "Pythonic" msgstr "Pythonic" -#: glossary.rst:1029 +#: glossary.rst:1042 msgid "" "An idea or piece of code which closely follows the most common idioms of the " "Python language, rather than implementing code using concepts common to " @@ -2420,15 +2527,27 @@ msgstr "" "oluşturmaktır. Diğer birçok dilde bu tür bir yapı yoktur, bu nedenle " "Python'a aşina olmayan kişiler bazen bunun yerine sayısal bir sayaç kullanır:" -#: glossary.rst:1039 +#: glossary.rst:1049 +msgid "" +"for i in range(len(food)):\n" +" print(food[i])" +msgstr "" + +#: glossary.rst:1052 msgid "As opposed to the cleaner, Pythonic method::" msgstr "Temizleyicinin aksine, Pythonic yöntemi::" -#: glossary.rst:1043 +#: glossary.rst:1054 +msgid "" +"for piece in food:\n" +" print(piece)" +msgstr "" + +#: glossary.rst:1056 msgid "qualified name" msgstr "nitelikli isim" -#: glossary.rst:1045 +#: glossary.rst:1058 msgid "" "A dotted name showing the \"path\" from a module's global scope to a class, " "function or method defined in that module, as defined in :pep:`3155`. For " @@ -2440,7 +2559,22 @@ msgstr "" "noktalı ad. Üst düzey işlevler ve sınıflar için nitelikli ad, nesnenin " "adıyla aynıdır::" -#: glossary.rst:1062 +#: glossary.rst:1063 +msgid "" +">>> class C:\n" +"... class D:\n" +"... def meth(self):\n" +"... pass\n" +"...\n" +">>> C.__qualname__\n" +"'C'\n" +">>> C.D.__qualname__\n" +"'C.D'\n" +">>> C.D.meth.__qualname__\n" +"'C.D.meth'" +msgstr "" + +#: glossary.rst:1075 msgid "" "When used to refer to modules, the *fully qualified name* means the entire " "dotted path to the module, including any parent packages, e.g. ``email.mime." @@ -2450,11 +2584,18 @@ msgstr "" "herhangi bir üst paket de dahil olmak üzere, modüle giden tüm noktalı yol " "anlamına gelir, örn. ``email.mime.text``::" -#: glossary.rst:1069 +#: glossary.rst:1079 +msgid "" +">>> import email.mime.text\n" +">>> email.mime.text.__name__\n" +"'email.mime.text'" +msgstr "" + +#: glossary.rst:1082 msgid "reference count" msgstr "referans sayısı" -#: glossary.rst:1071 +#: glossary.rst:1084 #, fuzzy msgid "" "The number of references to an object. When the reference count of an " @@ -2471,26 +2612,26 @@ msgstr "" "öğesidir. Programcılar, belirli bir nesne için başvuru sayısını döndürmek " "için :func:`sys.getrefcount` işlevini çağırabilir." -#: glossary.rst:1079 +#: glossary.rst:1092 msgid "regular package" msgstr "sürekli paketleme" -#: glossary.rst:1081 +#: glossary.rst:1094 msgid "" "A traditional :term:`package`, such as a directory containing an ``__init__." "py`` file." msgstr "" "``__init__.py`` dosyası içeren bir dizin gibi geleneksel bir :term:`package`." -#: glossary.rst:1084 +#: glossary.rst:1097 msgid "See also :term:`namespace package`." msgstr "Ayrıca bkz. :term:`ad alanı paketi`." -#: glossary.rst:1085 +#: glossary.rst:1098 msgid "__slots__" msgstr "__slots__" -#: glossary.rst:1087 +#: glossary.rst:1100 msgid "" "A declaration inside a class that saves memory by pre-declaring space for " "instance attributes and eliminating instance dictionaries. Though popular, " @@ -2504,11 +2645,11 @@ msgstr "" "açısından kritik bir uygulamada çok sayıda örneğin bulunduğu nadir durumlar " "için ayrılmıştır." -#: glossary.rst:1092 +#: glossary.rst:1105 msgid "sequence" msgstr "dizi" -#: glossary.rst:1094 +#: glossary.rst:1107 #, fuzzy msgid "" "An :term:`iterable` which supports efficient element access using integer " @@ -2517,8 +2658,8 @@ msgid "" "built-in sequence types are :class:`list`, :class:`str`, :class:`tuple`, " "and :class:`bytes`. Note that :class:`dict` also supports :meth:`~object." "__getitem__` and :meth:`!__len__`, but is considered a mapping rather than a " -"sequence because the lookups use arbitrary :term:`immutable` keys rather " -"than integers." +"sequence because the lookups use arbitrary :term:`hashable` keys rather than " +"integers." msgstr "" ":meth:`__getitem__` özel yöntemi aracılığıyla tamsayı dizinlerini kullanarak " "verimli öğe erişimini destekleyen ve dizinin uzunluğunu döndüren bir :meth:" @@ -2529,7 +2670,7 @@ msgstr "" "`immutable` anahtarları kullandığından bir diziden ziyade bir eşleme olarak " "kabul edilir." -#: glossary.rst:1103 +#: glossary.rst:1116 #, fuzzy msgid "" "The :class:`collections.abc.Sequence` abstract base class defines a much " @@ -2546,11 +2687,11 @@ msgstr "" "arayüzü tanımlar. Bu genişletilmiş arabirimi uygulayan türler, :func:`~abc." "ABCMeta.register` kullanılarak açıkça kaydedilebilir." -#: glossary.rst:1112 +#: glossary.rst:1125 msgid "set comprehension" msgstr "anlamak" -#: glossary.rst:1114 +#: glossary.rst:1127 msgid "" "A compact way to process all or part of the elements in an iterable and " "return a set with the results. ``results = {c for c in 'abracadabra' if c " @@ -2562,11 +2703,11 @@ msgstr "" "for c in 'abracadabra' if c not in 'abc'}``, ``{'r', 'd'}`` dizelerini " "oluşturur. Bakınız :ref:`comprehensions`." -#: glossary.rst:1118 +#: glossary.rst:1131 msgid "single dispatch" msgstr "tek sevk" -#: glossary.rst:1120 +#: glossary.rst:1133 msgid "" "A form of :term:`generic function` dispatch where the implementation is " "chosen based on the type of a single argument." @@ -2574,11 +2715,11 @@ msgstr "" "Uygulamanın tek bir argüman türüne göre seçildiği bir :term:`generic " "function` gönderimi biçimi." -#: glossary.rst:1122 +#: glossary.rst:1135 msgid "slice" msgstr "parçalamak" -#: glossary.rst:1124 +#: glossary.rst:1137 msgid "" "An object usually containing a portion of a :term:`sequence`. A slice is " "created using the subscript notation, ``[]`` with colons between numbers " @@ -2591,11 +2732,34 @@ msgstr "" "gösterimi kullanılarak oluşturulur. Köşeli ayraç (alt simge) gösterimi, " "dahili olarak :class:`slice` nesnelerini kullanır." -#: glossary.rst:1128 +#: glossary.rst:1141 +msgid "soft deprecated" +msgstr "" + +#: glossary.rst:1143 +msgid "" +"A soft deprecated API should not be used in new code, but it is safe for " +"already existing code to use it. The API remains documented and tested, but " +"will not be enhanced further." +msgstr "" + +#: glossary.rst:1147 +msgid "" +"Soft deprecation, unlike normal deprecation, does not plan on removing the " +"API and will not emit warnings." +msgstr "" + +#: glossary.rst:1150 +msgid "" +"See `PEP 387: Soft Deprecation `_." +msgstr "" + +#: glossary.rst:1152 msgid "special method" msgstr "özel metod" -#: glossary.rst:1132 +#: glossary.rst:1156 msgid "" "A method that is called implicitly by Python to execute a certain operation " "on a type, such as addition. Such methods have names starting and ending " @@ -2607,11 +2771,11 @@ msgstr "" "çizgi ile başlayan ve biten adları vardır. Özel yöntemler :ref:" "`specialnames` içinde belgelenmiştir." -#: glossary.rst:1136 +#: glossary.rst:1160 msgid "statement" msgstr "ifade (değer döndürmez)" -#: glossary.rst:1138 +#: glossary.rst:1162 msgid "" "A statement is part of a suite (a \"block\" of code). A statement is either " "an :term:`expression` or one of several constructs with a keyword, such as :" @@ -2621,22 +2785,22 @@ msgstr "" "`expression` veya :keyword:`if`, :keyword:`while` veya :keyword:`for` gibi " "bir anahtar kelimeye sahip birkaç yapıdan biridir." -#: glossary.rst:1141 +#: glossary.rst:1165 msgid "static type checker" msgstr "" -#: glossary.rst:1143 +#: glossary.rst:1167 msgid "" "An external tool that reads Python code and analyzes it, looking for issues " "such as incorrect types. See also :term:`type hints ` and the :" "mod:`typing` module." msgstr "" -#: glossary.rst:1146 +#: glossary.rst:1170 msgid "strong reference" msgstr "güçlü referans" -#: glossary.rst:1148 +#: glossary.rst:1172 #, fuzzy msgid "" "In Python's C API, a strong reference is a reference to an object which is " @@ -2648,7 +2812,7 @@ msgstr "" "referans sayısını artıran ve silindiğinde nesnenin referans sayısını azaltan " "bir nesneye yapılan referanstır." -#: glossary.rst:1154 +#: glossary.rst:1178 msgid "" "The :c:func:`Py_NewRef` function can be used to create a strong reference to " "an object. Usually, the :c:func:`Py_DECREF` function must be called on the " @@ -2660,15 +2824,15 @@ msgstr "" "referansın sızmasını önlemek için güçlü referans kapsamından çıkmadan önce " "güçlü referansta çağrılmalıdır." -#: glossary.rst:1159 +#: glossary.rst:1183 msgid "See also :term:`borrowed reference`." msgstr "Ayrıca bkz. :term:`ödünç alınan referans `." -#: glossary.rst:1160 +#: glossary.rst:1184 msgid "text encoding" msgstr "yazı çözümleme" -#: glossary.rst:1162 +#: glossary.rst:1186 msgid "" "A string in Python is a sequence of Unicode code points (in range " "``U+0000``--``U+10FFFF``). To store or transfer a string, it needs to be " @@ -2678,7 +2842,7 @@ msgstr "" "``U+10FFFF`` aralığında). Bir dizeyi depolamak veya aktarmak için, bir bayt " "dizisi olarak seri hale getirilmesi gerekir." -#: glossary.rst:1166 +#: glossary.rst:1190 msgid "" "Serializing a string into a sequence of bytes is known as \"encoding\", and " "recreating the string from the sequence of bytes is known as \"decoding\"." @@ -2687,7 +2851,7 @@ msgstr "" "olarak bilinir ve dizeyi bayt dizisinden yeniden oluşturmak \"kod çözme " "(decoding)\" olarak bilinir." -#: glossary.rst:1169 +#: glossary.rst:1193 msgid "" "There are a variety of different text serialization :ref:`codecs `, which are collectively referred to as \"text encodings\"." @@ -2695,11 +2859,11 @@ msgstr "" "Toplu olarak \"metin kodlamaları\" olarak adlandırılan çeşitli farklı metin " "serileştirme :ref:`kodekleri ` vardır." -#: glossary.rst:1172 +#: glossary.rst:1196 msgid "text file" msgstr "yazı dosyası" -#: glossary.rst:1174 +#: glossary.rst:1198 msgid "" "A :term:`file object` able to read and write :class:`str` objects. Often, a " "text file actually accesses a byte-oriented datastream and handles the :term:" @@ -2713,7 +2877,7 @@ msgstr "" "metin modunda açılan dosyalar (``'r'`` veya ``'w'``), :data:`sys.stdin`, :" "data:`sys.stdout` ve :class:`io.StringIO` örnekleri verilebilir." -#: glossary.rst:1181 +#: glossary.rst:1205 msgid "" "See also :term:`binary file` for a file object able to read and write :term:" "`bytes-like objects `." @@ -2721,11 +2885,11 @@ msgstr "" "Ayrıca :term:`ikili dosyaları ` okuyabilen ve yazabilen bir " "dosya nesnesi için :term:`bayt benzeri nesnelere ` bakın." -#: glossary.rst:1183 +#: glossary.rst:1207 msgid "triple-quoted string" msgstr "üç tırnaklı dize" -#: glossary.rst:1185 +#: glossary.rst:1209 msgid "" "A string which is bound by three instances of either a quotation mark (\") " "or an apostrophe ('). While they don't provide any functionality not " @@ -2742,29 +2906,30 @@ msgstr "" "yayılabilir, bu da onları özellikle belge dizileri yazarken kullanışlı hale " "getirir." -#: glossary.rst:1192 +#: glossary.rst:1216 msgid "type" msgstr "tip" -#: glossary.rst:1194 +#: glossary.rst:1218 +#, fuzzy msgid "" "The type of a Python object determines what kind of object it is; every " -"object has a type. An object's type is accessible as its :attr:`~instance." +"object has a type. An object's type is accessible as its :attr:`~object." "__class__` attribute or can be retrieved with ``type(obj)``." msgstr "" "Bir Python nesnesinin türü, onun ne tür bir nesne olduğunu belirler; her " "nesnenin bir türü vardır. Bir nesnenin tipine :attr:`~instance.__class__` " "niteliği ile erişilebilir veya ``type(obj)`` ile alınabilir." -#: glossary.rst:1198 +#: glossary.rst:1222 msgid "type alias" msgstr "tip takma adı" -#: glossary.rst:1200 +#: glossary.rst:1224 msgid "A synonym for a type, created by assigning the type to an identifier." msgstr "Bir tanımlayıcıya tür atanarak oluşturulan, bir tür için eş anlamlı." -#: glossary.rst:1202 +#: glossary.rst:1226 msgid "" "Type aliases are useful for simplifying :term:`type hints `. For " "example::" @@ -2772,19 +2937,34 @@ msgstr "" "Tür takma adları, :term:`tür ipuçlarını ` basitleştirmek için " "kullanışlıdır. Örneğin::" -#: glossary.rst:1209 +#: glossary.rst:1229 +msgid "" +"def remove_gray_shades(\n" +" colors: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:\n" +" pass" +msgstr "" + +#: glossary.rst:1233 msgid "could be made more readable like this::" msgstr "bu şekilde daha okunaklı hale getirilebilir::" -#: glossary.rst:1230 +#: glossary.rst:1235 +msgid "" +"Color = tuple[int, int, int]\n" +"\n" +"def remove_gray_shades(colors: list[Color]) -> list[Color]:\n" +" pass" +msgstr "" + +#: glossary.rst:1254 msgid "See :mod:`typing` and :pep:`484`, which describe this functionality." msgstr "Bu işlevi açıklayan :mod:`typing` ve :pep:`484` bölümlerine bakın." -#: glossary.rst:1217 +#: glossary.rst:1241 msgid "type hint" msgstr "tür ipucu" -#: glossary.rst:1219 +#: glossary.rst:1243 msgid "" "An :term:`annotation` that specifies the expected type for a variable, a " "class attribute, or a function parameter or return value." @@ -2792,7 +2972,7 @@ msgstr "" "Bir değişken, bir sınıf niteliği veya bir işlev parametresi veya dönüş " "değeri için beklenen türü belirten bir :term:`ek açıklama `." -#: glossary.rst:1222 +#: glossary.rst:1246 #, fuzzy msgid "" "Type hints are optional and are not enforced by Python but they are useful " @@ -2803,7 +2983,7 @@ msgstr "" "statik tip analiz araçları için faydalıdır ve kod tamamlama ve yeniden " "düzenleme ile IDE'lere yardımcı olur." -#: glossary.rst:1226 +#: glossary.rst:1250 msgid "" "Type hints of global variables, class attributes, and functions, but not " "local variables, can be accessed using :func:`typing.get_type_hints`." @@ -2812,11 +2992,11 @@ msgstr "" "yerel değişkenlere değil, :func:`typing.get_type_hints` kullanılarak " "erişilebilir." -#: glossary.rst:1231 +#: glossary.rst:1255 msgid "universal newlines" msgstr "evrensel yeni satırlar" -#: glossary.rst:1233 +#: glossary.rst:1257 msgid "" "A manner of interpreting text streams in which all of the following are " "recognized as ending a line: the Unix end-of-line convention ``'\\n'``, the " @@ -2829,23 +3009,29 @@ msgstr "" "kuralı ``'\\r\\n'``, ve eski Macintosh kuralı ``'\\r'``. Ek bir kullanım " "için :pep:`278` ve :pep:`3116` ve ayrıca :func:`bytes.splitlines` bakın." -#: glossary.rst:1238 +#: glossary.rst:1262 msgid "variable annotation" msgstr "değişken açıklama" -#: glossary.rst:1240 +#: glossary.rst:1264 msgid "An :term:`annotation` of a variable or a class attribute." msgstr "" "Bir değişkenin veya bir sınıf özniteliğinin :term:`ek açıklaması " "`." -#: glossary.rst:1242 +#: glossary.rst:1266 msgid "" "When annotating a variable or a class attribute, assignment is optional::" msgstr "" "Bir değişkene veya sınıf niteliğine açıklama eklerken atama isteğe bağlıdır::" -#: glossary.rst:1247 +#: glossary.rst:1268 +msgid "" +"class C:\n" +" field: 'annotation'" +msgstr "" + +#: glossary.rst:1271 msgid "" "Variable annotations are usually used for :term:`type hints `: " "for example this variable is expected to take :class:`int` values::" @@ -2853,11 +3039,15 @@ msgstr "" "Değişken açıklamaları genellikle :term:`tür ipuçları ` için " "kullanılır: örneğin, bu değişkenin :class:`int` değerlerini alması beklenir::" -#: glossary.rst:1253 +#: glossary.rst:1275 +msgid "count: int = 0" +msgstr "" + +#: glossary.rst:1277 msgid "Variable annotation syntax is explained in section :ref:`annassign`." msgstr "Değişken açıklama sözdizimi :ref:`annassign` bölümünde açıklanmıştır." -#: glossary.rst:1255 +#: glossary.rst:1279 msgid "" "See :term:`function annotation`, :pep:`484` and :pep:`526`, which describe " "this functionality. Also see :ref:`annotations-howto` for best practices on " @@ -2867,11 +3057,11 @@ msgstr "" "bölümlerine bakın. Ek açıklamalarla çalışmaya ilişkin en iyi uygulamalar " "için ayrıca bkz. :ref:`annotations-howto`." -#: glossary.rst:1259 +#: glossary.rst:1283 msgid "virtual environment" msgstr "sanal ortam" -#: glossary.rst:1261 +#: glossary.rst:1285 msgid "" "A cooperatively isolated runtime environment that allows Python users and " "applications to install and upgrade Python distribution packages without " @@ -2883,15 +3073,15 @@ msgstr "" "paketlerini kurmasına ve yükseltmesine olanak tanıyan, işbirliği içinde " "yalıtılmış bir çalışma zamanı ortamı." -#: glossary.rst:1266 +#: glossary.rst:1290 msgid "See also :mod:`venv`." msgstr "Ayrıca bakınız :mod:`venv`." -#: glossary.rst:1267 +#: glossary.rst:1291 msgid "virtual machine" msgstr "sanal makine" -#: glossary.rst:1269 +#: glossary.rst:1293 msgid "" "A computer defined entirely in software. Python's virtual machine executes " "the :term:`bytecode` emitted by the bytecode compiler." @@ -2899,11 +3089,11 @@ msgstr "" "Tamamen yazılımla tanımlanmış bir bilgisayar. Python'un sanal makinesi, bayt " "kodu derleyicisi tarafından yayınlanan :term:`bytecode` 'u çalıştırır." -#: glossary.rst:1271 +#: glossary.rst:1295 msgid "Zen of Python" msgstr "Python'un Zen'i" -#: glossary.rst:1273 +#: glossary.rst:1297 msgid "" "Listing of Python design principles and philosophies that are helpful in " "understanding and using the language. The listing can be found by typing " @@ -2923,11 +3113,11 @@ msgstr "bitişik" msgid "Fortran contiguous" msgstr "bitişik" -#: glossary.rst:761 +#: glossary.rst:772 msgid "magic" msgstr "" -#: glossary.rst:1130 +#: glossary.rst:1154 #, fuzzy msgid "special" msgstr "özel metod" diff --git a/howto/annotations.po b/howto/annotations.po index 51524b21a..5565a55fa 100644 --- a/howto/annotations.po +++ b/howto/annotations.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-02-24 17:22+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -127,6 +127,18 @@ msgid "" "annotations dict of a *base class.* As an example::" msgstr "" +#: howto/annotations.rst:89 +msgid "" +"class Base:\n" +" a: int = 3\n" +" b: str = 'abc'\n" +"\n" +"class Derived(Base):\n" +" pass\n" +"\n" +"print(Derived.__annotations__)" +msgstr "" + #: howto/annotations.rst:98 msgid "This will print the annotations dict from ``Base``, not ``Derived``." msgstr "" @@ -136,9 +148,9 @@ msgid "" "Your code will have to have a separate code path if the object you're " "examining is a class (``isinstance(o, type)``). In that case, best practice " "relies on an implementation detail of Python 3.9 and before: if a class has " -"annotations defined, they are stored in the class's ``__dict__`` " +"annotations defined, they are stored in the class's :attr:`~type.__dict__` " "dictionary. Since the class may or may not have annotations defined, best " -"practice is to call the ``get`` method on the class dict." +"practice is to call the :meth:`~dict.get` method on the class dict." msgstr "" #: howto/annotations.rst:109 @@ -148,6 +160,14 @@ msgid "" "before::" msgstr "" +#: howto/annotations.rst:113 +msgid "" +"if isinstance(o, type):\n" +" ann = o.__dict__.get('__annotations__', None)\n" +"else:\n" +" ann = getattr(o, '__annotations__', None)" +msgstr "" + #: howto/annotations.rst:118 msgid "" "After running this code, ``ann`` should be either a dictionary or ``None``. " @@ -157,9 +177,9 @@ msgstr "" #: howto/annotations.rst:123 msgid "" -"Note that some exotic or malformed type objects may not have a ``__dict__`` " -"attribute, so for extra safety you may also wish to use :func:`getattr` to " -"access ``__dict__``." +"Note that some exotic or malformed type objects may not have a :attr:`~type." +"__dict__` attribute, so for extra safety you may also wish to use :func:" +"`getattr` to access :attr:`!__dict__`." msgstr "" #: howto/annotations.rst:129 @@ -317,6 +337,14 @@ msgid "" "example::" msgstr "" +#: howto/annotations.rst:227 +msgid "" +"from __future__ import annotations\n" +"def foo(a: \"str\"): pass\n" +"\n" +"print(foo.__annotations__)" +msgstr "" + #: howto/annotations.rst:232 msgid "" "This prints ``{'a': \"'str'\"}``. This shouldn't really be considered a " diff --git a/howto/argparse-optparse.po b/howto/argparse-optparse.po new file mode 100644 index 000000000..2ec77acc0 --- /dev/null +++ b/howto/argparse-optparse.po @@ -0,0 +1,118 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) 2001-2024, Python Software Foundation +# This file is distributed under the same license as the Python package. +# FIRST AUTHOR , YEAR. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: Python 3.12\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +#: howto/argparse-optparse.rst:7 +msgid "Upgrading optparse code" +msgstr "" + +#: howto/argparse-optparse.rst:9 +msgid "" +"Originally, the :mod:`argparse` module had attempted to maintain " +"compatibility with :mod:`optparse`. However, :mod:`optparse` was difficult " +"to extend transparently, particularly with the changes required to support " +"``nargs=`` specifiers and better usage messages. When most everything in :" +"mod:`optparse` had either been copy-pasted over or monkey-patched, it no " +"longer seemed practical to try to maintain the backwards compatibility." +msgstr "" + +#: howto/argparse-optparse.rst:16 +msgid "" +"The :mod:`argparse` module improves on the :mod:`optparse` module in a " +"number of ways including:" +msgstr "" + +#: howto/argparse-optparse.rst:19 +msgid "Handling positional arguments." +msgstr "" + +#: howto/argparse-optparse.rst:20 +msgid "Supporting subcommands." +msgstr "" + +#: howto/argparse-optparse.rst:21 +msgid "Allowing alternative option prefixes like ``+`` and ``/``." +msgstr "" + +#: howto/argparse-optparse.rst:22 +msgid "Handling zero-or-more and one-or-more style arguments." +msgstr "" + +#: howto/argparse-optparse.rst:23 +msgid "Producing more informative usage messages." +msgstr "" + +#: howto/argparse-optparse.rst:24 +msgid "Providing a much simpler interface for custom ``type`` and ``action``." +msgstr "" + +#: howto/argparse-optparse.rst:26 +msgid "A partial upgrade path from :mod:`optparse` to :mod:`argparse`:" +msgstr "" + +#: howto/argparse-optparse.rst:28 +msgid "" +"Replace all :meth:`optparse.OptionParser.add_option` calls with :meth:" +"`ArgumentParser.add_argument` calls." +msgstr "" + +#: howto/argparse-optparse.rst:31 +msgid "" +"Replace ``(options, args) = parser.parse_args()`` with ``args = parser." +"parse_args()`` and add additional :meth:`ArgumentParser.add_argument` calls " +"for the positional arguments. Keep in mind that what was previously called " +"``options``, now in the :mod:`argparse` context is called ``args``." +msgstr "" + +#: howto/argparse-optparse.rst:36 +msgid "" +"Replace :meth:`optparse.OptionParser.disable_interspersed_args` by using :" +"meth:`~ArgumentParser.parse_intermixed_args` instead of :meth:" +"`~ArgumentParser.parse_args`." +msgstr "" + +#: howto/argparse-optparse.rst:40 +msgid "" +"Replace callback actions and the ``callback_*`` keyword arguments with " +"``type`` or ``action`` arguments." +msgstr "" + +#: howto/argparse-optparse.rst:43 +msgid "" +"Replace string names for ``type`` keyword arguments with the corresponding " +"type objects (e.g. int, float, complex, etc)." +msgstr "" + +#: howto/argparse-optparse.rst:46 +msgid "" +"Replace :class:`optparse.Values` with :class:`Namespace` and :exc:`optparse." +"OptionError` and :exc:`optparse.OptionValueError` with :exc:`ArgumentError`." +msgstr "" + +#: howto/argparse-optparse.rst:50 +msgid "" +"Replace strings with implicit arguments such as ``%default`` or ``%prog`` " +"with the standard Python syntax to use dictionaries to format strings, that " +"is, ``%(default)s`` and ``%(prog)s``." +msgstr "" + +#: howto/argparse-optparse.rst:54 +msgid "" +"Replace the OptionParser constructor ``version`` argument with a call to " +"``parser.add_argument('--version', action='version', version='')``." +msgstr "" diff --git a/howto/argparse.po b/howto/argparse.po index 136836708..0d67b6625 100644 --- a/howto/argparse.po +++ b/howto/argparse.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-09-18 22:33+0300\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -52,6 +52,26 @@ msgid "" "introductory tutorial by making use of the :command:`ls` command:" msgstr "" +#: howto/argparse.rst:29 +msgid "" +"$ ls\n" +"cpython devguide prog.py pypy rm-unused-function.patch\n" +"$ ls pypy\n" +"ctypes_configure demo dotviewer include lib_pypy lib-python ...\n" +"$ ls -l\n" +"total 20\n" +"drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython\n" +"drwxr-xr-x 4 wena wena 4096 Feb 8 12:04 devguide\n" +"-rwxr-xr-x 1 wena wena 535 Feb 19 00:05 prog.py\n" +"drwxr-xr-x 14 wena wena 4096 Feb 7 00:59 pypy\n" +"-rw-r--r-- 1 wena wena 741 Feb 18 01:01 rm-unused-function.patch\n" +"$ ls --help\n" +"Usage: ls [OPTION]... [FILE]...\n" +"List information about the FILEs (the current directory by default).\n" +"Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.\n" +"..." +msgstr "" + #: howto/argparse.rst:48 msgid "A few concepts we can learn from the four commands:" msgstr "" @@ -96,10 +116,33 @@ msgstr "" msgid "Let us start with a very simple example which does (almost) nothing::" msgstr "" +#: howto/argparse.rst:76 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.parse_args()" +msgstr "" + #: howto/argparse.rst:188 howto/argparse.rst:209 msgid "Following is a result of running the code:" msgstr "" +#: howto/argparse.rst:82 +msgid "" +"$ python prog.py\n" +"$ python prog.py --help\n" +"usage: prog.py [-h]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"$ python prog.py --verbose\n" +"usage: prog.py [-h]\n" +"prog.py: error: unrecognized arguments: --verbose\n" +"$ python prog.py foo\n" +"usage: prog.py [-h]\n" +"prog.py: error: unrecognized arguments: foo" +msgstr "" + #: howto/argparse.rst:254 howto/argparse.rst:298 msgid "Here is what is happening:" msgstr "" @@ -132,10 +175,36 @@ msgstr "" msgid "An example::" msgstr "" +#: howto/argparse.rst:116 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"echo\")\n" +"args = parser.parse_args()\n" +"print(args.echo)" +msgstr "" + #: howto/argparse.rst:122 msgid "And running the code:" msgstr "" +#: howto/argparse.rst:124 +msgid "" +"$ python prog.py\n" +"usage: prog.py [-h] echo\n" +"prog.py: error: the following arguments are required: echo\n" +"$ python prog.py --help\n" +"usage: prog.py [-h] echo\n" +"\n" +"positional arguments:\n" +" echo\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"$ python prog.py foo\n" +"foo" +msgstr "" + #: howto/argparse.rst:140 msgid "Here is what's happening:" msgstr "" @@ -175,14 +244,54 @@ msgid "" "useful::" msgstr "" +#: howto/argparse.rst:161 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"echo\", help=\"echo the string you use here\")\n" +"args = parser.parse_args()\n" +"print(args.echo)" +msgstr "" + #: howto/argparse.rst:167 msgid "And we get:" msgstr "" +#: howto/argparse.rst:169 +msgid "" +"$ python prog.py -h\n" +"usage: prog.py [-h] echo\n" +"\n" +"positional arguments:\n" +" echo echo the string you use here\n" +"\n" +"options:\n" +" -h, --help show this help message and exit" +msgstr "" + #: howto/argparse.rst:180 msgid "Now, how about doing something even more useful::" msgstr "" +#: howto/argparse.rst:182 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", help=\"display a square of a given " +"number\")\n" +"args = parser.parse_args()\n" +"print(args.square**2)" +msgstr "" + +#: howto/argparse.rst:190 +msgid "" +"$ python prog.py 4\n" +"Traceback (most recent call last):\n" +" File \"prog.py\", line 5, in \n" +" print(args.square**2)\n" +"TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'" +msgstr "" + #: howto/argparse.rst:198 msgid "" "That didn't go so well. That's because :mod:`argparse` treats the options we " @@ -190,6 +299,26 @@ msgid "" "`argparse` to treat that input as an integer::" msgstr "" +#: howto/argparse.rst:202 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", help=\"display a square of a given " +"number\",\n" +" type=int)\n" +"args = parser.parse_args()\n" +"print(args.square**2)" +msgstr "" + +#: howto/argparse.rst:211 +msgid "" +"$ python prog.py 4\n" +"16\n" +"$ python prog.py four\n" +"usage: prog.py [-h] square\n" +"prog.py: error: argument square: invalid int value: 'four'" +msgstr "" + #: howto/argparse.rst:219 msgid "" "That went well. The program now even helpfully quits on bad illegal input " @@ -206,10 +335,37 @@ msgid "" "how to add optional ones::" msgstr "" +#: howto/argparse.rst:229 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"--verbosity\", help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"if args.verbosity:\n" +" print(\"verbosity turned on\")" +msgstr "" + #: howto/argparse.rst:282 howto/argparse.rst:432 msgid "And the output:" msgstr "" +#: howto/argparse.rst:238 +msgid "" +"$ python prog.py --verbosity 1\n" +"verbosity turned on\n" +"$ python prog.py\n" +"$ python prog.py --help\n" +"usage: prog.py [-h] [--verbosity VERBOSITY]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --verbosity VERBOSITY\n" +" increase output verbosity\n" +"$ python prog.py --verbosity\n" +"usage: prog.py [-h] [--verbosity VERBOSITY]\n" +"prog.py: error: argument --verbosity: expected one argument" +msgstr "" + #: howto/argparse.rst:256 msgid "" "The program is written so as to display something when ``--verbosity`` is " @@ -242,6 +398,32 @@ msgid "" "``False``. Let's modify the code accordingly::" msgstr "" +#: howto/argparse.rst:274 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"--verbose\", help=\"increase output verbosity\",\n" +" action=\"store_true\")\n" +"args = parser.parse_args()\n" +"if args.verbose:\n" +" print(\"verbosity turned on\")" +msgstr "" + +#: howto/argparse.rst:284 +msgid "" +"$ python prog.py --verbose\n" +"verbosity turned on\n" +"$ python prog.py --verbose 1\n" +"usage: prog.py [-h] [--verbose]\n" +"prog.py: error: unrecognized arguments: 1\n" +"$ python prog.py --help\n" +"usage: prog.py [-h] [--verbose]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --verbose increase output verbosity" +msgstr "" + #: howto/argparse.rst:300 msgid "" "The option is now more of a flag than something that requires a value. We " @@ -272,10 +454,34 @@ msgid "" "simple::" msgstr "" +#: howto/argparse.rst:320 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"-v\", \"--verbose\", help=\"increase output " +"verbosity\",\n" +" action=\"store_true\")\n" +"args = parser.parse_args()\n" +"if args.verbose:\n" +" print(\"verbosity turned on\")" +msgstr "" + #: howto/argparse.rst:328 msgid "And here goes:" msgstr "" +#: howto/argparse.rst:330 +msgid "" +"$ python prog.py -v\n" +"verbosity turned on\n" +"$ python prog.py --help\n" +"usage: prog.py [-h] [-v]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -v, --verbose increase output verbosity" +msgstr "" + #: howto/argparse.rst:341 msgid "Note that the new ability is also reflected in the help text." msgstr "" @@ -288,10 +494,39 @@ msgstr "" msgid "Our program keeps growing in complexity::" msgstr "" +#: howto/argparse.rst:349 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", type=int,\n" +" help=\"display a square of a given number\")\n" +"parser.add_argument(\"-v\", \"--verbose\", action=\"store_true\",\n" +" help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"answer = args.square**2\n" +"if args.verbose:\n" +" print(f\"the square of {args.square} equals {answer}\")\n" +"else:\n" +" print(answer)" +msgstr "" + #: howto/argparse.rst:362 msgid "And now the output:" msgstr "" +#: howto/argparse.rst:364 +msgid "" +"$ python prog.py\n" +"usage: prog.py [-h] [-v] square\n" +"prog.py: error: the following arguments are required: square\n" +"$ python prog.py 4\n" +"16\n" +"$ python prog.py 4 --verbose\n" +"the square of 4 equals 16\n" +"$ python prog.py --verbose 4\n" +"the square of 4 equals 16" +msgstr "" + #: howto/argparse.rst:376 msgid "We've brought back a positional argument, hence the complaint." msgstr "" @@ -306,6 +541,39 @@ msgid "" "verbosity values, and actually get to use them::" msgstr "" +#: howto/argparse.rst:383 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", type=int,\n" +" help=\"display a square of a given number\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", type=int,\n" +" help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"answer = args.square**2\n" +"if args.verbosity == 2:\n" +" print(f\"the square of {args.square} equals {answer}\")\n" +"elif args.verbosity == 1:\n" +" print(f\"{args.square}^2 == {answer}\")\n" +"else:\n" +" print(answer)" +msgstr "" + +#: howto/argparse.rst:400 +msgid "" +"$ python prog.py 4\n" +"16\n" +"$ python prog.py 4 -v\n" +"usage: prog.py [-h] [-v VERBOSITY] square\n" +"prog.py: error: argument -v/--verbosity: expected one argument\n" +"$ python prog.py 4 -v 1\n" +"4^2 == 16\n" +"$ python prog.py 4 -v 2\n" +"the square of 4 equals 16\n" +"$ python prog.py 4 -v 3\n" +"16" +msgstr "" + #: howto/argparse.rst:414 msgid "" "These all look good except the last one, which exposes a bug in our program. " @@ -313,6 +581,42 @@ msgid "" "accept::" msgstr "" +#: howto/argparse.rst:417 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", type=int,\n" +" help=\"display a square of a given number\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", type=int, choices=[0, 1, 2],\n" +" help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"answer = args.square**2\n" +"if args.verbosity == 2:\n" +" print(f\"the square of {args.square} equals {answer}\")\n" +"elif args.verbosity == 1:\n" +" print(f\"{args.square}^2 == {answer}\")\n" +"else:\n" +" print(answer)" +msgstr "" + +#: howto/argparse.rst:434 +msgid "" +"$ python prog.py 4 -v 3\n" +"usage: prog.py [-h] [-v {0,1,2}] square\n" +"prog.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, " +"1, 2)\n" +"$ python prog.py 4 -h\n" +"usage: prog.py [-h] [-v {0,1,2}] square\n" +"\n" +"positional arguments:\n" +" square display a square of a given number\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -v {0,1,2}, --verbosity {0,1,2}\n" +" increase output verbosity" +msgstr "" + #: howto/argparse.rst:450 msgid "" "Note that the change also reflects both in the error message as well as the " @@ -326,12 +630,56 @@ msgid "" "own verbosity argument (check the output of ``python --help``)::" msgstr "" +#: howto/argparse.rst:457 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", type=int,\n" +" help=\"display the square of a given number\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", action=\"count\",\n" +" help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"answer = args.square**2\n" +"if args.verbosity == 2:\n" +" print(f\"the square of {args.square} equals {answer}\")\n" +"elif args.verbosity == 1:\n" +" print(f\"{args.square}^2 == {answer}\")\n" +"else:\n" +" print(answer)" +msgstr "" + #: howto/argparse.rst:472 msgid "" "We have introduced another action, \"count\", to count the number of " "occurrences of specific options." msgstr "" +#: howto/argparse.rst:476 +msgid "" +"$ python prog.py 4\n" +"16\n" +"$ python prog.py 4 -v\n" +"4^2 == 16\n" +"$ python prog.py 4 -vv\n" +"the square of 4 equals 16\n" +"$ python prog.py 4 --verbosity --verbosity\n" +"the square of 4 equals 16\n" +"$ python prog.py 4 -v 1\n" +"usage: prog.py [-h] [-v] square\n" +"prog.py: error: unrecognized arguments: 1\n" +"$ python prog.py 4 -h\n" +"usage: prog.py [-h] [-v] square\n" +"\n" +"positional arguments:\n" +" square display a square of a given number\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -v, --verbosity increase output verbosity\n" +"$ python prog.py 4 -vvv\n" +"16" +msgstr "" + #: howto/argparse.rst:501 msgid "" "Yes, it's now more of a flag (similar to ``action=\"store_true\"``) in the " @@ -375,10 +723,43 @@ msgstr "" msgid "Let's fix::" msgstr "" +#: howto/argparse.rst:524 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", type=int,\n" +" help=\"display a square of a given number\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", action=\"count\",\n" +" help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"answer = args.square**2\n" +"\n" +"# bugfix: replace == with >=\n" +"if args.verbosity >= 2:\n" +" print(f\"the square of {args.square} equals {answer}\")\n" +"elif args.verbosity >= 1:\n" +" print(f\"{args.square}^2 == {answer}\")\n" +"else:\n" +" print(answer)" +msgstr "" + #: howto/argparse.rst:541 msgid "And this is what it gives:" msgstr "" +#: howto/argparse.rst:543 +msgid "" +"$ python prog.py 4 -vvv\n" +"the square of 4 equals 16\n" +"$ python prog.py 4 -vvvv\n" +"the square of 4 equals 16\n" +"$ python prog.py 4\n" +"Traceback (most recent call last):\n" +" File \"prog.py\", line 11, in \n" +" if args.verbosity >= 2:\n" +"TypeError: '>=' not supported between instances of 'NoneType' and 'int'" +msgstr "" + #: howto/argparse.rst:556 msgid "" "First output went well, and fixes the bug we had before. That is, we want " @@ -393,6 +774,24 @@ msgstr "" msgid "Let's fix that bug::" msgstr "" +#: howto/argparse.rst:563 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"square\", type=int,\n" +" help=\"display a square of a given number\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", action=\"count\", default=0,\n" +" help=\"increase output verbosity\")\n" +"args = parser.parse_args()\n" +"answer = args.square**2\n" +"if args.verbosity >= 2:\n" +" print(f\"the square of {args.square} equals {answer}\")\n" +"elif args.verbosity >= 1:\n" +" print(f\"{args.square}^2 == {answer}\")\n" +"else:\n" +" print(answer)" +msgstr "" + #: howto/argparse.rst:578 msgid "" "We've just introduced yet another keyword, ``default``. We've set it to " @@ -406,6 +805,12 @@ msgstr "" msgid "And:" msgstr "" +#: howto/argparse.rst:587 +msgid "" +"$ python prog.py 4\n" +"16" +msgstr "" + #: howto/argparse.rst:592 msgid "" "You can go quite far just with what we've learned so far, and we have only " @@ -423,10 +828,46 @@ msgid "" "just squares::" msgstr "" -#: howto/argparse.rst:656 +#: howto/argparse.rst:604 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"x\", type=int, help=\"the base\")\n" +"parser.add_argument(\"y\", type=int, help=\"the exponent\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", action=\"count\", default=0)\n" +"args = parser.parse_args()\n" +"answer = args.x**args.y\n" +"if args.verbosity >= 2:\n" +" print(f\"{args.x} to the power {args.y} equals {answer}\")\n" +"elif args.verbosity >= 1:\n" +" print(f\"{args.x}^{args.y} == {answer}\")\n" +"else:\n" +" print(answer)" +msgstr "" + +#: howto/argparse.rst:656 howto/argparse.rst:872 msgid "Output:" msgstr "" +#: howto/argparse.rst:620 +msgid "" +"$ python prog.py\n" +"usage: prog.py [-h] [-v] x y\n" +"prog.py: error: the following arguments are required: x, y\n" +"$ python prog.py -h\n" +"usage: prog.py [-h] [-v] x y\n" +"\n" +"positional arguments:\n" +" x the base\n" +" y the exponent\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -v, --verbosity\n" +"$ python prog.py 4 2 -v\n" +"4^2 == 16" +msgstr "" + #: howto/argparse.rst:639 msgid "" "Notice that so far we've been using verbosity level to *change* the text " @@ -434,6 +875,33 @@ msgid "" "display *more* text instead::" msgstr "" +#: howto/argparse.rst:643 +msgid "" +"import argparse\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument(\"x\", type=int, help=\"the base\")\n" +"parser.add_argument(\"y\", type=int, help=\"the exponent\")\n" +"parser.add_argument(\"-v\", \"--verbosity\", action=\"count\", default=0)\n" +"args = parser.parse_args()\n" +"answer = args.x**args.y\n" +"if args.verbosity >= 2:\n" +" print(f\"Running '{__file__}'\")\n" +"if args.verbosity >= 1:\n" +" print(f\"{args.x}^{args.y} == \", end=\"\")\n" +"print(answer)" +msgstr "" + +#: howto/argparse.rst:658 +msgid "" +"$ python prog.py 4 2\n" +"16\n" +"$ python prog.py 4 2 -v\n" +"4^2 == 16\n" +"$ python prog.py 4 2 -vv\n" +"Running 'prog.py'\n" +"4^2 == 16" +msgstr "" + #: howto/argparse.rst:672 msgid "Specifying ambiguous arguments" msgstr "" @@ -445,6 +913,28 @@ msgid "" "that everything after that is a positional argument::" msgstr "" +#: howto/argparse.rst:678 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-n', nargs='+')\n" +">>> parser.add_argument('args', nargs='*')\n" +"\n" +">>> # ambiguous, so parse_args assumes it's an option\n" +">>> parser.parse_args(['-f'])\n" +"usage: PROG [-h] [-n N [N ...]] [args ...]\n" +"PROG: error: unrecognized arguments: -f\n" +"\n" +">>> parser.parse_args(['--', '-f'])\n" +"Namespace(args=['-f'], n=None)\n" +"\n" +">>> # ambiguous, so the -n option greedily accepts arguments\n" +">>> parser.parse_args(['-n', '1', '2', '3'])\n" +"Namespace(args=[], n=['1', '2', '3'])\n" +"\n" +">>> parser.parse_args(['-n', '1', '--', '2', '3'])\n" +"Namespace(args=['2', '3'], n=['1'])" +msgstr "" + #: howto/argparse.rst:699 msgid "Conflicting options" msgstr "" @@ -459,12 +949,49 @@ msgid "" "``--quiet`` option, which will be the opposite of the ``--verbose`` one::" msgstr "" +#: howto/argparse.rst:709 +msgid "" +"import argparse\n" +"\n" +"parser = argparse.ArgumentParser()\n" +"group = parser.add_mutually_exclusive_group()\n" +"group.add_argument(\"-v\", \"--verbose\", action=\"store_true\")\n" +"group.add_argument(\"-q\", \"--quiet\", action=\"store_true\")\n" +"parser.add_argument(\"x\", type=int, help=\"the base\")\n" +"parser.add_argument(\"y\", type=int, help=\"the exponent\")\n" +"args = parser.parse_args()\n" +"answer = args.x**args.y\n" +"\n" +"if args.quiet:\n" +" print(answer)\n" +"elif args.verbose:\n" +" print(f\"{args.x} to the power {args.y} equals {answer}\")\n" +"else:\n" +" print(f\"{args.x}^{args.y} == {answer}\")" +msgstr "" + #: howto/argparse.rst:727 msgid "" "Our program is now simpler, and we've lost some functionality for the sake " "of demonstration. Anyways, here's the output:" msgstr "" +#: howto/argparse.rst:730 +msgid "" +"$ python prog.py 4 2\n" +"4^2 == 16\n" +"$ python prog.py 4 2 -q\n" +"16\n" +"$ python prog.py 4 2 -v\n" +"4 to the power 2 equals 16\n" +"$ python prog.py 4 2 -vq\n" +"usage: prog.py [-h] [-v | -q] x y\n" +"prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose\n" +"$ python prog.py 4 2 -v --quiet\n" +"usage: prog.py [-h] [-v | -q] x y\n" +"prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose" +msgstr "" + #: howto/argparse.rst:745 msgid "" "That should be easy to follow. I've added that last output so you can see " @@ -478,6 +1005,28 @@ msgid "" "your program, just in case they don't know::" msgstr "" +#: howto/argparse.rst:752 +msgid "" +"import argparse\n" +"\n" +"parser = argparse.ArgumentParser(description=\"calculate X to the power of " +"Y\")\n" +"group = parser.add_mutually_exclusive_group()\n" +"group.add_argument(\"-v\", \"--verbose\", action=\"store_true\")\n" +"group.add_argument(\"-q\", \"--quiet\", action=\"store_true\")\n" +"parser.add_argument(\"x\", type=int, help=\"the base\")\n" +"parser.add_argument(\"y\", type=int, help=\"the exponent\")\n" +"args = parser.parse_args()\n" +"answer = args.x**args.y\n" +"\n" +"if args.quiet:\n" +" print(answer)\n" +"elif args.verbose:\n" +" print(f\"{args.x} to the power {args.y} equals {answer}\")\n" +"else:\n" +" print(f\"{args.x}^{args.y} == {answer}\")" +msgstr "" + #: howto/argparse.rst:770 msgid "" "Note that slight difference in the usage text. Note the ``[-v | -q]``, which " @@ -485,6 +1034,23 @@ msgid "" "time:" msgstr "" +#: howto/argparse.rst:801 +msgid "" +"$ python prog.py --help\n" +"usage: prog.py [-h] [-v | -q] x y\n" +"\n" +"calculate X to the power of Y\n" +"\n" +"positional arguments:\n" +" x the base\n" +" y the exponent\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -v, --verbose\n" +" -q, --quiet" +msgstr "" + #: howto/argparse.rst:792 msgid "How to translate the argparse output" msgstr "" @@ -514,6 +1080,10 @@ msgid "" "command:" msgstr "" +#: howto/argparse.rst:824 +msgid "$ pybabel extract -o messages.po /usr/lib/python3.12/argparse.py" +msgstr "" + #: howto/argparse.rst:828 msgid "" "This command will extract all translatable strings from the :mod:`argparse` " @@ -527,6 +1097,12 @@ msgid "" "using this script::" msgstr "" +#: howto/argparse.rst:835 +msgid "" +"import argparse\n" +"print(argparse.__file__)" +msgstr "" + #: howto/argparse.rst:838 msgid "" "Once the messages in the ``.po`` file are translated and the translations " @@ -541,11 +1117,83 @@ msgid "" msgstr "" #: howto/argparse.rst:845 -msgid "Conclusion" +msgid "Custom type converters" msgstr "" #: howto/argparse.rst:847 msgid "" +"The :mod:`argparse` module allows you to specify custom type converters for " +"your command-line arguments. This allows you to modify user input before " +"it's stored in the :class:`argparse.Namespace`. This can be useful when you " +"need to pre-process the input before it is used in your program." +msgstr "" + +#: howto/argparse.rst:852 +msgid "" +"When using a custom type converter, you can use any callable that takes a " +"single string argument (the argument value) and returns the converted value. " +"However, if you need to handle more complex scenarios, you can use a custom " +"action class with the **action** parameter instead." +msgstr "" + +#: howto/argparse.rst:857 +msgid "" +"For example, let's say you want to handle arguments with different prefixes " +"and process them accordingly::" +msgstr "" + +#: howto/argparse.rst:860 +msgid "" +"import argparse\n" +"\n" +"parser = argparse.ArgumentParser(prefix_chars='-+')\n" +"\n" +"parser.add_argument('-a', metavar='', action='append',\n" +" type=lambda x: ('-', x))\n" +"parser.add_argument('+a', metavar='', action='append',\n" +" type=lambda x: ('+', x))\n" +"\n" +"args = parser.parse_args()\n" +"print(args)" +msgstr "" + +#: howto/argparse.rst:874 +msgid "" +"$ python prog.py -a value1 +a value2\n" +"Namespace(a=[('-', 'value1'), ('+', 'value2')])" +msgstr "" + +#: howto/argparse.rst:879 +msgid "In this example, we:" +msgstr "" + +#: howto/argparse.rst:881 +msgid "" +"Created a parser with custom prefix characters using the ``prefix_chars`` " +"parameter." +msgstr "" + +#: howto/argparse.rst:884 +msgid "" +"Defined two arguments, ``-a`` and ``+a``, which used the ``type`` parameter " +"to create custom type converters to store the value in a tuple with the " +"prefix." +msgstr "" + +#: howto/argparse.rst:887 +msgid "" +"Without the custom type converters, the arguments would have treated the ``-" +"a`` and ``+a`` as the same argument, which would have been undesirable. By " +"using custom type converters, we were able to differentiate between the two " +"arguments." +msgstr "" + +#: howto/argparse.rst:892 +msgid "Conclusion" +msgstr "" + +#: howto/argparse.rst:894 +msgid "" "The :mod:`argparse` module offers a lot more than shown here. Its docs are " "quite detailed and thorough, and full of examples. Having gone through this " "tutorial, you should easily digest them without feeling overwhelmed." diff --git a/howto/curses.po b/howto/curses.po index 1976e0f89..aa7b0178c 100644 --- a/howto/curses.po +++ b/howto/curses.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-01 21:53+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -139,6 +139,12 @@ msgid "" "after the name of the corresponding C variable. ::" msgstr "" +#: howto/curses.rst:90 +msgid "" +"import curses\n" +"stdscr = curses.initscr()" +msgstr "" + #: howto/curses.rst:93 msgid "" "Usually curses applications turn off automatic echoing of keys to the " @@ -146,6 +152,10 @@ msgid "" "circumstances. This requires calling the :func:`~curses.noecho` function. ::" msgstr "" +#: howto/curses.rst:98 +msgid "curses.noecho()" +msgstr "" + #: howto/curses.rst:100 msgid "" "Applications will also commonly need to react to keys instantly, without " @@ -153,6 +163,10 @@ msgid "" "opposed to the usual buffered input mode. ::" msgstr "" +#: howto/curses.rst:104 +msgid "curses.cbreak()" +msgstr "" + #: howto/curses.rst:106 msgid "" "Terminals usually return special keys, such as the cursor keys or navigation " @@ -163,12 +177,23 @@ msgid "" "keypad mode. ::" msgstr "" +#: howto/curses.rst:113 +msgid "stdscr.keypad(True)" +msgstr "" + #: howto/curses.rst:115 msgid "" "Terminating a curses application is much easier than starting one. You'll " "need to call::" msgstr "" +#: howto/curses.rst:118 +msgid "" +"curses.nocbreak()\n" +"stdscr.keypad(False)\n" +"curses.echo()" +msgstr "" + #: howto/curses.rst:122 msgid "" "to reverse the curses-friendly terminal settings. Then call the :func:" @@ -176,6 +201,10 @@ msgid "" "mode. ::" msgstr "" +#: howto/curses.rst:126 +msgid "curses.endwin()" +msgstr "" + #: howto/curses.rst:128 msgid "" "A common problem when debugging a curses application is to get your terminal " @@ -191,6 +220,25 @@ msgid "" "by importing the :func:`curses.wrapper` function and using it like this::" msgstr "" +#: howto/curses.rst:137 +msgid "" +"from curses import wrapper\n" +"\n" +"def main(stdscr):\n" +" # Clear screen\n" +" stdscr.clear()\n" +"\n" +" # This raises ZeroDivisionError when i == 10.\n" +" for i in range(0, 11):\n" +" v = i-10\n" +" stdscr.addstr(i, 0, '10 divided by {} is {}'.format(v, 10/v))\n" +"\n" +" stdscr.refresh()\n" +" stdscr.getkey()\n" +"\n" +"wrapper(main)" +msgstr "" + #: howto/curses.rst:153 msgid "" "The :func:`~curses.wrapper` function takes a callable object and does the " @@ -225,6 +273,13 @@ msgid "" "window object. ::" msgstr "" +#: howto/curses.rst:178 +msgid "" +"begin_x = 20; begin_y = 7\n" +"height = 5; width = 40\n" +"win = curses.newwin(height, width, begin_y, begin_x)" +msgstr "" + #: howto/curses.rst:182 msgid "" "Note that the coordinate system used in curses is unusual. Coordinates are " @@ -280,6 +335,24 @@ msgid "" "will be displayed. ::" msgstr "" +#: howto/curses.rst:223 +msgid "" +"pad = curses.newpad(100, 100)\n" +"# These loops fill the pad with letters; addch() is\n" +"# explained in the next section\n" +"for y in range(0, 99):\n" +" for x in range(0, 99):\n" +" pad.addch(y,x, ord('a') + (x*x+y*y) % 26)\n" +"\n" +"# Displays a section of the pad in the middle of the screen.\n" +"# (0,0) : coordinate of upper-left corner of pad area to display.\n" +"# (5,5) : coordinate of upper-left corner of window area to be filled\n" +"# with pad content.\n" +"# (20, 75) : coordinate of lower-right corner of window area to be\n" +"# : filled with pad content.\n" +"pad.refresh( 0,0, 5,5, 20,75)" +msgstr "" + #: howto/curses.rst:238 msgid "" "The :meth:`!refresh` call displays a section of the pad in the rectangle " @@ -513,6 +586,13 @@ msgid "" "you could code::" msgstr "" +#: howto/curses.rst:364 +msgid "" +"stdscr.addstr(0, 0, \"Current mode: Typing mode\",\n" +" curses.A_REVERSE)\n" +"stdscr.refresh()" +msgstr "" + #: howto/curses.rst:368 msgid "" "The curses library also supports color on those terminals that provide it. " @@ -546,6 +626,12 @@ msgstr "" msgid "An example, which displays a line of text using color pair 1::" msgstr "" +#: howto/curses.rst:391 +msgid "" +"stdscr.addstr(\"Pretty text\", curses.color_pair(1))\n" +"stdscr.refresh()" +msgstr "" + #: howto/curses.rst:394 msgid "" "As I said before, a color pair consists of a foreground and background " @@ -569,6 +655,10 @@ msgid "" "background, you would call::" msgstr "" +#: howto/curses.rst:408 +msgid "curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)" +msgstr "" + #: howto/curses.rst:410 msgid "" "When you change a color pair, any text already displayed using that color " @@ -576,6 +666,10 @@ msgid "" "color with::" msgstr "" +#: howto/curses.rst:414 +msgid "stdscr.addstr(0,0, \"RED ALERT!\", curses.color_pair(1))" +msgstr "" + #: howto/curses.rst:416 msgid "" "Very fancy terminals can change the definitions of the actual colors to a " @@ -641,6 +735,18 @@ msgid "" "program may look something like this::" msgstr "" +#: howto/curses.rst:462 +msgid "" +"while True:\n" +" c = stdscr.getch()\n" +" if c == ord('p'):\n" +" PrintDocument()\n" +" elif c == ord('q'):\n" +" break # Exit the while loop\n" +" elif c == curses.KEY_HOME:\n" +" x = y = 0" +msgstr "" + #: howto/curses.rst:471 msgid "" "The :mod:`curses.ascii` module supplies ASCII class membership functions " @@ -660,6 +766,14 @@ msgid "" "number of characters. ::" msgstr "" +#: howto/curses.rst:484 +msgid "" +"curses.echo() # Enable echoing of characters\n" +"\n" +"# Get a 15-character string, with the cursor on the top line\n" +"s = stdscr.getstr(0,0, 15)" +msgstr "" + #: howto/curses.rst:489 msgid "" "The :mod:`curses.textpad` module supplies a text box that supports an Emacs-" @@ -668,6 +782,27 @@ msgid "" "results either with or without trailing spaces. Here's an example::" msgstr "" +#: howto/curses.rst:495 +msgid "" +"import curses\n" +"from curses.textpad import Textbox, rectangle\n" +"\n" +"def main(stdscr):\n" +" stdscr.addstr(0, 0, \"Enter IM message: (hit Ctrl-G to send)\")\n" +"\n" +" editwin = curses.newwin(5,30, 2,1)\n" +" rectangle(stdscr, 1,0, 1+5+1, 1+30+1)\n" +" stdscr.refresh()\n" +"\n" +" box = Textbox(editwin)\n" +"\n" +" # Let the user edit until Ctrl-G is struck.\n" +" box.edit()\n" +"\n" +" # Get resulting contents\n" +" message = box.gather()" +msgstr "" + #: howto/curses.rst:513 msgid "" "See the library documentation on :mod:`curses.textpad` for more details." diff --git a/howto/descriptor.po b/howto/descriptor.po index 4d70c598b..15f76fd5c 100644 --- a/howto/descriptor.po +++ b/howto/descriptor.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -97,18 +97,41 @@ msgid "" "returns the constant ``10``:" msgstr "" +#: howto/descriptor.rst:48 +msgid "" +"class Ten:\n" +" def __get__(self, obj, objtype=None):\n" +" return 10" +msgstr "" + #: howto/descriptor.rst:54 msgid "" "To use the descriptor, it must be stored as a class variable in another " "class:" msgstr "" +#: howto/descriptor.rst:56 +msgid "" +"class A:\n" +" x = 5 # Regular class attribute\n" +" y = Ten() # Descriptor instance" +msgstr "" + #: howto/descriptor.rst:62 msgid "" "An interactive session shows the difference between normal attribute lookup " "and descriptor lookup:" msgstr "" +#: howto/descriptor.rst:65 +msgid "" +">>> a = A() # Make an instance of class A\n" +">>> a.x # Normal attribute lookup\n" +"5\n" +">>> a.y # Descriptor lookup\n" +"10" +msgstr "" + #: howto/descriptor.rst:73 msgid "" "In the ``a.x`` attribute lookup, the dot operator finds ``'x': 5`` in the " @@ -144,12 +167,45 @@ msgid "" "constants:" msgstr "" +#: howto/descriptor.rst:93 +msgid "" +"import os\n" +"\n" +"class DirectorySize:\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" return len(os.listdir(obj.dirname))\n" +"\n" +"class Directory:\n" +"\n" +" size = DirectorySize() # Descriptor instance\n" +"\n" +" def __init__(self, dirname):\n" +" self.dirname = dirname # Regular instance attribute" +msgstr "" + #: howto/descriptor.rst:109 msgid "" "An interactive session shows that the lookup is dynamic — it computes " "different, updated answers each time::" msgstr "" +#: howto/descriptor.rst:112 +msgid "" +">>> s = Directory('songs')\n" +">>> g = Directory('games')\n" +">>> s.size # The songs directory has twenty " +"files\n" +"20\n" +">>> g.size # The games directory has three " +"files\n" +"3\n" +">>> os.remove('games/chess') # Delete a game\n" +">>> g.size # File count is automatically " +"updated\n" +"2" +msgstr "" + #: howto/descriptor.rst:122 msgid "" "Besides showing how descriptors can run computations, this example also " @@ -180,12 +236,71 @@ msgid "" "logs the lookup or update:" msgstr "" +#: howto/descriptor.rst:143 +msgid "" +"import logging\n" +"\n" +"logging.basicConfig(level=logging.INFO)\n" +"\n" +"class LoggedAgeAccess:\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" value = obj._age\n" +" logging.info('Accessing %r giving %r', 'age', value)\n" +" return value\n" +"\n" +" def __set__(self, obj, value):\n" +" logging.info('Updating %r to %r', 'age', value)\n" +" obj._age = value\n" +"\n" +"class Person:\n" +"\n" +" age = LoggedAgeAccess() # Descriptor instance\n" +"\n" +" def __init__(self, name, age):\n" +" self.name = name # Regular instance attribute\n" +" self.age = age # Calls __set__()\n" +"\n" +" def birthday(self):\n" +" self.age += 1 # Calls both __get__() and __set__()" +msgstr "" + #: howto/descriptor.rst:172 msgid "" "An interactive session shows that all access to the managed attribute *age* " "is logged, but that the regular attribute *name* is not logged:" msgstr "" +#: howto/descriptor.rst:181 +msgid "" +">>> mary = Person('Mary M', 30) # The initial age update is logged\n" +"INFO:root:Updating 'age' to 30\n" +">>> dave = Person('David D', 40)\n" +"INFO:root:Updating 'age' to 40\n" +"\n" +">>> vars(mary) # The actual data is in a private " +"attribute\n" +"{'name': 'Mary M', '_age': 30}\n" +">>> vars(dave)\n" +"{'name': 'David D', '_age': 40}\n" +"\n" +">>> mary.age # Access the data and log the " +"lookup\n" +"INFO:root:Accessing 'age' giving 30\n" +"30\n" +">>> mary.birthday() # Updates are logged as well\n" +"INFO:root:Accessing 'age' giving 30\n" +"INFO:root:Updating 'age' to 31\n" +"\n" +">>> dave.name # Regular attribute lookup isn't " +"logged\n" +"'David D'\n" +">>> dave.age # Only the managed attribute is " +"logged\n" +"INFO:root:Accessing 'age' giving 40\n" +"40" +msgstr "" + #: howto/descriptor.rst:206 msgid "" "One major issue with this example is that the private name *_age* is " @@ -213,6 +328,40 @@ msgid "" "*private_name*:" msgstr "" +#: howto/descriptor.rst:223 +msgid "" +"import logging\n" +"\n" +"logging.basicConfig(level=logging.INFO)\n" +"\n" +"class LoggedAccess:\n" +"\n" +" def __set_name__(self, owner, name):\n" +" self.public_name = name\n" +" self.private_name = '_' + name\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" value = getattr(obj, self.private_name)\n" +" logging.info('Accessing %r giving %r', self.public_name, value)\n" +" return value\n" +"\n" +" def __set__(self, obj, value):\n" +" logging.info('Updating %r to %r', self.public_name, value)\n" +" setattr(obj, self.private_name, value)\n" +"\n" +"class Person:\n" +"\n" +" name = LoggedAccess() # First descriptor instance\n" +" age = LoggedAccess() # Second descriptor instance\n" +"\n" +" def __init__(self, name, age):\n" +" self.name = name # Calls the first descriptor\n" +" self.age = age # Calls the second descriptor\n" +"\n" +" def birthday(self):\n" +" self.age += 1" +msgstr "" + #: howto/descriptor.rst:256 msgid "" "An interactive session shows that the :class:`Person` class has called :meth:" @@ -220,14 +369,40 @@ msgid "" "func:`vars` to look up the descriptor without triggering it:" msgstr "" +#: howto/descriptor.rst:260 +msgid "" +">>> vars(vars(Person)['name'])\n" +"{'public_name': 'name', 'private_name': '_name'}\n" +">>> vars(vars(Person)['age'])\n" +"{'public_name': 'age', 'private_name': '_age'}" +msgstr "" + #: howto/descriptor.rst:267 msgid "The new class now logs access to both *name* and *age*:" msgstr "" +#: howto/descriptor.rst:275 +msgid "" +">>> pete = Person('Peter P', 10)\n" +"INFO:root:Updating 'name' to 'Peter P'\n" +"INFO:root:Updating 'age' to 10\n" +">>> kate = Person('Catherine C', 20)\n" +"INFO:root:Updating 'name' to 'Catherine C'\n" +"INFO:root:Updating 'age' to 20" +msgstr "" + #: howto/descriptor.rst:284 msgid "The two *Person* instances contain only the private names:" msgstr "" +#: howto/descriptor.rst:286 +msgid "" +">>> vars(pete)\n" +"{'_name': 'Peter P', '_age': 10}\n" +">>> vars(kate)\n" +"{'_name': 'Catherine C', '_age': 20}" +msgstr "" + #: howto/descriptor.rst:295 msgid "Closing thoughts" msgstr "" @@ -308,6 +483,27 @@ msgid "" "managed attribute descriptor:" msgstr "" +#: howto/descriptor.rst:343 +msgid "" +"from abc import ABC, abstractmethod\n" +"\n" +"class Validator(ABC):\n" +"\n" +" def __set_name__(self, owner, name):\n" +" self.private_name = '_' + name\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" return getattr(obj, self.private_name)\n" +"\n" +" def __set__(self, obj, value):\n" +" self.validate(value)\n" +" setattr(obj, self.private_name, value)\n" +"\n" +" @abstractmethod\n" +" def validate(self, value):\n" +" pass" +msgstr "" + #: howto/descriptor.rst:363 msgid "" "Custom validators need to inherit from :class:`Validator` and must supply a :" @@ -342,6 +538,61 @@ msgid "" "as well." msgstr "" +#: howto/descriptor.rst:383 +msgid "" +"class OneOf(Validator):\n" +"\n" +" def __init__(self, *options):\n" +" self.options = set(options)\n" +"\n" +" def validate(self, value):\n" +" if value not in self.options:\n" +" raise ValueError(f'Expected {value!r} to be one of {self.options!" +"r}')\n" +"\n" +"class Number(Validator):\n" +"\n" +" def __init__(self, minvalue=None, maxvalue=None):\n" +" self.minvalue = minvalue\n" +" self.maxvalue = maxvalue\n" +"\n" +" def validate(self, value):\n" +" if not isinstance(value, (int, float)):\n" +" raise TypeError(f'Expected {value!r} to be an int or float')\n" +" if self.minvalue is not None and value < self.minvalue:\n" +" raise ValueError(\n" +" f'Expected {value!r} to be at least {self.minvalue!r}'\n" +" )\n" +" if self.maxvalue is not None and value > self.maxvalue:\n" +" raise ValueError(\n" +" f'Expected {value!r} to be no more than {self.maxvalue!r}'\n" +" )\n" +"\n" +"class String(Validator):\n" +"\n" +" def __init__(self, minsize=None, maxsize=None, predicate=None):\n" +" self.minsize = minsize\n" +" self.maxsize = maxsize\n" +" self.predicate = predicate\n" +"\n" +" def validate(self, value):\n" +" if not isinstance(value, str):\n" +" raise TypeError(f'Expected {value!r} to be an str')\n" +" if self.minsize is not None and len(value) < self.minsize:\n" +" raise ValueError(\n" +" f'Expected {value!r} to be no smaller than {self.minsize!" +"r}'\n" +" )\n" +" if self.maxsize is not None and len(value) > self.maxsize:\n" +" raise ValueError(\n" +" f'Expected {value!r} to be no bigger than {self.maxsize!r}'\n" +" )\n" +" if self.predicate is not None and not self.predicate(value):\n" +" raise ValueError(\n" +" f'Expected {self.predicate} to be true for {value!r}'\n" +" )" +msgstr "" + #: howto/descriptor.rst:437 msgid "Practical application" msgstr "" @@ -350,10 +601,50 @@ msgstr "" msgid "Here's how the data validators can be used in a real class:" msgstr "" +#: howto/descriptor.rst:441 +msgid "" +"class Component:\n" +"\n" +" name = String(minsize=3, maxsize=10, predicate=str.isupper)\n" +" kind = OneOf('wood', 'metal', 'plastic')\n" +" quantity = Number(minvalue=0)\n" +"\n" +" def __init__(self, name, kind, quantity):\n" +" self.name = name\n" +" self.kind = kind\n" +" self.quantity = quantity" +msgstr "" + #: howto/descriptor.rst:454 msgid "The descriptors prevent invalid instances from being created:" msgstr "" +#: howto/descriptor.rst:456 +msgid "" +">>> Component('Widget', 'metal', 5) # Blocked: 'Widget' is not all " +"uppercase\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: Expected to be true for " +"'Widget'\n" +"\n" +">>> Component('WIDGET', 'metle', 5) # Blocked: 'metle' is misspelled\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: Expected 'metle' to be one of {'metal', 'plastic', 'wood'}\n" +"\n" +">>> Component('WIDGET', 'metal', -5) # Blocked: -5 is negative\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: Expected -5 to be at least 0\n" +">>> Component('WIDGET', 'metal', 'V') # Blocked: 'V' isn't a number\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: Expected 'V' to be an int or float\n" +"\n" +">>> c = Component('WIDGET', 'metal', 5) # Allowed: The inputs are valid" +msgstr "" + #: howto/descriptor.rst:481 msgid "Technical Tutorial" msgstr "" @@ -408,9 +699,9 @@ msgstr "" msgid "" "Descriptors are a powerful, general purpose protocol. They are the " "mechanism behind properties, methods, static methods, class methods, and :" -"func:`super()`. They are used throughout Python itself. Descriptors " -"simplify the underlying C code and offer a flexible set of new tools for " -"everyday Python programs." +"func:`super`. They are used throughout Python itself. Descriptors simplify " +"the underlying C code and offer a flexible set of new tools for everyday " +"Python programs." msgstr "" #: howto/descriptor.rst:522 @@ -481,8 +772,8 @@ msgstr "" msgid "" "The expression ``obj.x`` looks up the attribute ``x`` in the chain of " "namespaces for ``obj``. If the search finds a descriptor outside of the " -"instance ``__dict__``, its :meth:`__get__` method is invoked according to " -"the precedence rules listed below." +"instance :attr:`~object.__dict__`, its :meth:`~object.__get__` method is " +"invoked according to the precedence rules listed below." msgstr "" #: howto/descriptor.rst:565 @@ -515,6 +806,35 @@ msgid "" "is a pure Python equivalent:" msgstr "" +#: howto/descriptor.rst:583 +msgid "" +"def find_name_in_mro(cls, name, default):\n" +" \"Emulate _PyType_Lookup() in Objects/typeobject.c\"\n" +" for base in cls.__mro__:\n" +" if name in vars(base):\n" +" return vars(base)[name]\n" +" return default\n" +"\n" +"def object_getattribute(obj, name):\n" +" \"Emulate PyObject_GenericGetAttr() in Objects/object.c\"\n" +" null = object()\n" +" objtype = type(obj)\n" +" cls_var = find_name_in_mro(objtype, name, null)\n" +" descr_get = getattr(type(cls_var), '__get__', null)\n" +" if descr_get is not null:\n" +" if (hasattr(type(cls_var), '__set__')\n" +" or hasattr(type(cls_var), '__delete__')):\n" +" return descr_get(cls_var, obj, objtype) # data descriptor\n" +" if hasattr(obj, '__dict__') and name in vars(obj):\n" +" return vars(obj)[name] # instance variable\n" +" if descr_get is not null:\n" +" return descr_get(cls_var, obj, objtype) # non-data " +"descriptor\n" +" if cls_var is not null:\n" +" return cls_var # class variable\n" +" raise AttributeError(name)" +msgstr "" + #: howto/descriptor.rst:719 msgid "" "Note, there is no :meth:`__getattr__` hook in the :meth:`__getattribute__` " @@ -530,6 +850,18 @@ msgid "" "encapsulated in a helper function:" msgstr "" +#: howto/descriptor.rst:728 +msgid "" +"def getattr_hook(obj, name):\n" +" \"Emulate slot_tp_getattr_hook() in Objects/typeobject.c\"\n" +" try:\n" +" return obj.__getattribute__(name)\n" +" except AttributeError:\n" +" if not hasattr(type(obj), '__getattr__'):\n" +" raise\n" +" return type(obj).__getattr__(obj, name) # __getattr__" +msgstr "" + #: howto/descriptor.rst:773 msgid "Invocation from a class" msgstr "" @@ -584,7 +916,7 @@ msgstr "" #: howto/descriptor.rst:806 msgid "" -"The mechanism for descriptors is embedded in the :meth:`__getattribute__()` " +"The mechanism for descriptors is embedded in the :meth:`__getattribute__` " "methods for :class:`object`, :class:`type`, and :func:`super`." msgstr "" @@ -669,6 +1001,24 @@ msgid "" "care of lookups or updates:" msgstr "" +#: howto/descriptor.rst:858 +msgid "" +"class Field:\n" +"\n" +" def __set_name__(self, owner, name):\n" +" self.fetch = f'SELECT {name} FROM {owner.table} WHERE {owner.key}" +"=?;'\n" +" self.store = f'UPDATE {owner.table} SET {name}=? WHERE {owner.key}" +"=?;'\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" return conn.execute(self.fetch, [obj.key]).fetchone()[0]\n" +"\n" +" def __set__(self, obj, value):\n" +" conn.execute(self.store, [value, obj.key])\n" +" conn.commit()" +msgstr "" + #: howto/descriptor.rst:873 msgid "" "We can use the :class:`Field` class to define `models >> import sqlite3\n" +">>> conn = sqlite3.connect('entertainment.db')" +msgstr "" + #: howto/descriptor.rst:903 msgid "" "An interactive session shows how data is retrieved from the database and how " "it can be updated:" msgstr "" +#: howto/descriptor.rst:931 +msgid "" +">>> Movie('Star Wars').director\n" +"'George Lucas'\n" +">>> jaws = Movie('Jaws')\n" +">>> f'Released in {jaws.year} by {jaws.director}'\n" +"'Released in 1975 by Steven Spielberg'\n" +"\n" +">>> Song('Country Roads').artist\n" +"'John Denver'\n" +"\n" +">>> Movie('Star Wars').director = 'J.J. Abrams'\n" +">>> Movie('Star Wars').director\n" +"'J.J. Abrams'" +msgstr "" + #: howto/descriptor.rst:952 msgid "Pure Python Equivalents" msgstr "" @@ -709,17 +1103,89 @@ msgid "" "is::" msgstr "" +#: howto/descriptor.rst:966 +msgid "property(fget=None, fset=None, fdel=None, doc=None) -> property" +msgstr "" + #: howto/descriptor.rst:968 msgid "" "The documentation shows a typical use to define a managed attribute ``x``:" msgstr "" +#: howto/descriptor.rst:970 +msgid "" +"class C:\n" +" def getx(self): return self.__x\n" +" def setx(self, value): self.__x = value\n" +" def delx(self): del self.__x\n" +" x = property(getx, setx, delx, \"I'm the 'x' property.\")" +msgstr "" + #: howto/descriptor.rst:992 msgid "" "To see how :func:`property` is implemented in terms of the descriptor " "protocol, here is a pure Python equivalent:" msgstr "" +#: howto/descriptor.rst:995 +msgid "" +"class Property:\n" +" \"Emulate PyProperty_Type() in Objects/descrobject.c\"\n" +"\n" +" def __init__(self, fget=None, fset=None, fdel=None, doc=None):\n" +" self.fget = fget\n" +" self.fset = fset\n" +" self.fdel = fdel\n" +" if doc is None and fget is not None:\n" +" doc = fget.__doc__\n" +" self.__doc__ = doc\n" +" self._name = ''\n" +"\n" +" def __set_name__(self, owner, name):\n" +" self._name = name\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" if obj is None:\n" +" return self\n" +" if self.fget is None:\n" +" raise AttributeError(\n" +" f'property {self._name!r} of {type(obj).__name__!r} object " +"has no getter'\n" +" )\n" +" return self.fget(obj)\n" +"\n" +" def __set__(self, obj, value):\n" +" if self.fset is None:\n" +" raise AttributeError(\n" +" f'property {self._name!r} of {type(obj).__name__!r} object " +"has no setter'\n" +" )\n" +" self.fset(obj, value)\n" +"\n" +" def __delete__(self, obj):\n" +" if self.fdel is None:\n" +" raise AttributeError(\n" +" f'property {self._name!r} of {type(obj).__name__!r} object " +"has no deleter'\n" +" )\n" +" self.fdel(obj)\n" +"\n" +" def getter(self, fget):\n" +" prop = type(self)(fget, self.fset, self.fdel, self.__doc__)\n" +" prop._name = self._name\n" +" return prop\n" +"\n" +" def setter(self, fset):\n" +" prop = type(self)(self.fget, fset, self.fdel, self.__doc__)\n" +" prop._name = self._name\n" +" return prop\n" +"\n" +" def deleter(self, fdel):\n" +" prop = type(self)(self.fget, self.fset, fdel, self.__doc__)\n" +" prop._name = self._name\n" +" return prop" +msgstr "" + #: howto/descriptor.rst:1132 msgid "" "The :func:`property` builtin helps whenever a user interface has granted " @@ -737,6 +1203,18 @@ msgid "" "descriptor:" msgstr "" +#: howto/descriptor.rst:1142 +msgid "" +"class Cell:\n" +" ...\n" +"\n" +" @property\n" +" def value(self):\n" +" \"Recalculate the cell before returning value\"\n" +" self.recalc()\n" +" return self._value" +msgstr "" + #: howto/descriptor.rst:1153 msgid "" "Either the built-in :func:`property` or our :func:`Property` equivalent " @@ -767,6 +1245,21 @@ msgid "" "roughly equivalent to:" msgstr "" +#: howto/descriptor.rst:1171 +msgid "" +"class MethodType:\n" +" \"Emulate PyMethod_Type in Objects/classobject.c\"\n" +"\n" +" def __init__(self, func, obj):\n" +" self.__func__ = func\n" +" self.__self__ = obj\n" +"\n" +" def __call__(self, *args, **kwargs):\n" +" func = self.__func__\n" +" obj = self.__self__\n" +" return func(obj, *args, **kwargs)" +msgstr "" + #: howto/descriptor.rst:1185 msgid "" "To support automatic creation of methods, functions include the :meth:" @@ -775,41 +1268,94 @@ msgid "" "dotted lookup from an instance. Here's how it works:" msgstr "" +#: howto/descriptor.rst:1190 +msgid "" +"class Function:\n" +" ...\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" \"Simulate func_descr_get() in Objects/funcobject.c\"\n" +" if obj is None:\n" +" return self\n" +" return MethodType(self, obj)" +msgstr "" + #: howto/descriptor.rst:1201 msgid "" "Running the following class in the interpreter shows how the function " "descriptor works in practice:" msgstr "" +#: howto/descriptor.rst:1204 +msgid "" +"class D:\n" +" def f(self, x):\n" +" return x" +msgstr "" + #: howto/descriptor.rst:1210 msgid "" "The function has a :term:`qualified name` attribute to support introspection:" msgstr "" +#: howto/descriptor.rst:1212 +msgid "" +">>> D.f.__qualname__\n" +"'D.f'" +msgstr "" + #: howto/descriptor.rst:1217 msgid "" "Accessing the function through the class dictionary does not invoke :meth:" "`__get__`. Instead, it just returns the underlying function object::" msgstr "" +#: howto/descriptor.rst:1220 +msgid "" +">>> D.__dict__['f']\n" +"" +msgstr "" + #: howto/descriptor.rst:1223 msgid "" "Dotted access from a class calls :meth:`__get__` which just returns the " "underlying function unchanged::" msgstr "" +#: howto/descriptor.rst:1226 +msgid "" +">>> D.f\n" +"" +msgstr "" + #: howto/descriptor.rst:1229 msgid "" "The interesting behavior occurs during dotted access from an instance. The " "dotted lookup calls :meth:`__get__` which returns a bound method object::" msgstr "" +#: howto/descriptor.rst:1232 +msgid "" +">>> d = D()\n" +">>> d.f\n" +">" +msgstr "" + #: howto/descriptor.rst:1236 msgid "" "Internally, the bound method stores the underlying function and the bound " "instance::" msgstr "" +#: howto/descriptor.rst:1239 +msgid "" +">>> d.f.__func__\n" +"\n" +"\n" +">>> d.f.__self__\n" +"<__main__.D object at 0x00B18C90>" +msgstr "" + #: howto/descriptor.rst:1245 msgid "" "If you have ever wondered where *self* comes from in regular methods or " @@ -915,12 +1461,46 @@ msgid "" "example calls are unexciting:" msgstr "" +#: howto/descriptor.rst:1298 +msgid "" +"class E:\n" +" @staticmethod\n" +" def f(x):\n" +" return x * 10" +msgstr "" + +#: howto/descriptor.rst:1305 +msgid "" +">>> E.f(3)\n" +"30\n" +">>> E().f(3)\n" +"30" +msgstr "" + #: howto/descriptor.rst:1312 msgid "" "Using the non-data descriptor protocol, a pure Python version of :func:" "`staticmethod` would look like this:" msgstr "" +#: howto/descriptor.rst:1315 +msgid "" +"import functools\n" +"\n" +"class StaticMethod:\n" +" \"Emulate PyStaticMethod_Type() in Objects/funcobject.c\"\n" +"\n" +" def __init__(self, f):\n" +" self.f = f\n" +" functools.update_wrapper(self, f)\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" return self.f\n" +"\n" +" def __call__(self, *args, **kwds):\n" +" return self.f(*args, **kwds)" +msgstr "" + #: howto/descriptor.rst:1332 msgid "" "The :func:`functools.update_wrapper` call adds a ``__wrapped__`` attribute " @@ -941,6 +1521,22 @@ msgid "" "whether the caller is an object or a class:" msgstr "" +#: howto/descriptor.rst:1407 +msgid "" +"class F:\n" +" @classmethod\n" +" def f(cls, x):\n" +" return cls.__name__, x" +msgstr "" + +#: howto/descriptor.rst:1414 +msgid "" +">>> F.f(3)\n" +"('F', 3)\n" +">>> F().f(3)\n" +"('F', 3)" +msgstr "" + #: howto/descriptor.rst:1421 msgid "" "This behavior is useful whenever the method only needs to have a class " @@ -950,16 +1546,58 @@ msgid "" "of keys. The pure Python equivalent is:" msgstr "" +#: howto/descriptor.rst:1427 +msgid "" +"class Dict(dict):\n" +" @classmethod\n" +" def fromkeys(cls, iterable, value=None):\n" +" \"Emulate dict_fromkeys() in Objects/dictobject.c\"\n" +" d = cls()\n" +" for key in iterable:\n" +" d[key] = value\n" +" return d" +msgstr "" + #: howto/descriptor.rst:1438 msgid "Now a new dictionary of unique keys can be constructed like this:" msgstr "" +#: howto/descriptor.rst:1440 +msgid "" +">>> d = Dict.fromkeys('abracadabra')\n" +">>> type(d) is Dict\n" +"True\n" +">>> d\n" +"{'a': None, 'b': None, 'r': None, 'c': None, 'd': None}" +msgstr "" + #: howto/descriptor.rst:1448 msgid "" "Using the non-data descriptor protocol, a pure Python version of :func:" "`classmethod` would look like this:" msgstr "" +#: howto/descriptor.rst:1451 +msgid "" +"import functools\n" +"\n" +"class ClassMethod:\n" +" \"Emulate PyClassMethod_Type() in Objects/funcobject.c\"\n" +"\n" +" def __init__(self, f):\n" +" self.f = f\n" +" functools.update_wrapper(self, f)\n" +"\n" +" def __get__(self, obj, cls=None):\n" +" if cls is None:\n" +" cls = type(obj)\n" +" if hasattr(type(self.f), '__get__'):\n" +" # This code path was added in Python 3.9\n" +" # and was deprecated in Python 3.11.\n" +" return self.f.__get__(cls, cls)\n" +" return MethodType(self.f, cls)" +msgstr "" + #: howto/descriptor.rst:1526 msgid "" "The code path for ``hasattr(type(self.f), '__get__')`` was added in Python " @@ -968,6 +1606,21 @@ msgid "" "together. In Python 3.11, this functionality was deprecated." msgstr "" +#: howto/descriptor.rst:1531 +msgid "" +"class G:\n" +" @classmethod\n" +" @property\n" +" def __doc__(cls):\n" +" return f'A doc for {cls.__name__!r}'" +msgstr "" + +#: howto/descriptor.rst:1539 +msgid "" +">>> G.__doc__\n" +"\"A doc for 'G'\"" +msgstr "" + #: howto/descriptor.rst:1544 msgid "" "The :func:`functools.update_wrapper` call in ``ClassMethod`` adds a " @@ -995,12 +1648,62 @@ msgid "" "assignments. Only attribute names specified in ``__slots__`` are allowed:" msgstr "" +#: howto/descriptor.rst:1562 +msgid "" +"class Vehicle:\n" +" __slots__ = ('id_number', 'make', 'model')" +msgstr "" + +#: howto/descriptor.rst:1567 +msgid "" +">>> auto = Vehicle()\n" +">>> auto.id_nubmer = 'VYE483814LQEX'\n" +"Traceback (most recent call last):\n" +" ...\n" +"AttributeError: 'Vehicle' object has no attribute 'id_nubmer'" +msgstr "" + #: howto/descriptor.rst:1575 msgid "" "2. Helps create immutable objects where descriptors manage access to private " "attributes stored in ``__slots__``:" msgstr "" +#: howto/descriptor.rst:1578 +msgid "" +"class Immutable:\n" +"\n" +" __slots__ = ('_dept', '_name') # Replace the instance " +"dictionary\n" +"\n" +" def __init__(self, dept, name):\n" +" self._dept = dept # Store to private attribute\n" +" self._name = name # Store to private attribute\n" +"\n" +" @property # Read-only descriptor\n" +" def dept(self):\n" +" return self._dept\n" +"\n" +" @property\n" +" def name(self): # Read-only descriptor\n" +" return self._name" +msgstr "" + +#: howto/descriptor.rst:1596 +msgid "" +">>> mark = Immutable('Botany', 'Mark Watney')\n" +">>> mark.dept\n" +"'Botany'\n" +">>> mark.dept = 'Space Pirate'\n" +"Traceback (most recent call last):\n" +" ...\n" +"AttributeError: property 'dept' of 'Immutable' object has no setter\n" +">>> mark.location = 'Mars'\n" +"Traceback (most recent call last):\n" +" ...\n" +"AttributeError: 'Immutable' object has no attribute 'location'" +msgstr "" + #: howto/descriptor.rst:1610 msgid "" "3. Saves memory. On a 64-bit Linux build, an instance with two attributes " @@ -1021,6 +1724,27 @@ msgid "" "instance dictionary to function correctly:" msgstr "" +#: howto/descriptor.rst:1621 +msgid "" +"from functools import cached_property\n" +"\n" +"class CP:\n" +" __slots__ = () # Eliminates the instance dict\n" +"\n" +" @cached_property # Requires an instance dict\n" +" def pi(self):\n" +" return 4 * sum((-1.0)**n / (2.0*n + 1.0)\n" +" for n in reversed(range(100_000)))" +msgstr "" + +#: howto/descriptor.rst:1633 +msgid "" +">>> CP().pi\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: No '__dict__' attribute on 'CP' instance to cache 'pi' property." +msgstr "" + #: howto/descriptor.rst:1640 msgid "" "It is not possible to create an exact drop-in pure Python version of " @@ -1031,12 +1755,65 @@ msgid "" "managed by member descriptors:" msgstr "" +#: howto/descriptor.rst:1647 +msgid "" +"null = object()\n" +"\n" +"class Member:\n" +"\n" +" def __init__(self, name, clsname, offset):\n" +" 'Emulate PyMemberDef in Include/structmember.h'\n" +" # Also see descr_new() in Objects/descrobject.c\n" +" self.name = name\n" +" self.clsname = clsname\n" +" self.offset = offset\n" +"\n" +" def __get__(self, obj, objtype=None):\n" +" 'Emulate member_get() in Objects/descrobject.c'\n" +" # Also see PyMember_GetOne() in Python/structmember.c\n" +" if obj is None:\n" +" return self\n" +" value = obj._slotvalues[self.offset]\n" +" if value is null:\n" +" raise AttributeError(self.name)\n" +" return value\n" +"\n" +" def __set__(self, obj, value):\n" +" 'Emulate member_set() in Objects/descrobject.c'\n" +" obj._slotvalues[self.offset] = value\n" +"\n" +" def __delete__(self, obj):\n" +" 'Emulate member_delete() in Objects/descrobject.c'\n" +" value = obj._slotvalues[self.offset]\n" +" if value is null:\n" +" raise AttributeError(self.name)\n" +" obj._slotvalues[self.offset] = null\n" +"\n" +" def __repr__(self):\n" +" 'Emulate member_repr() in Objects/descrobject.c'\n" +" return f''" +msgstr "" + #: howto/descriptor.rst:1685 msgid "" "The :meth:`type.__new__` method takes care of adding member objects to class " "variables:" msgstr "" +#: howto/descriptor.rst:1688 +msgid "" +"class Type(type):\n" +" 'Simulate how the type metaclass adds member objects for slots'\n" +"\n" +" def __new__(mcls, clsname, bases, mapping, **kwargs):\n" +" 'Emulate type_new() in Objects/typeobject.c'\n" +" # type_new() calls PyTypeReady() which calls add_methods()\n" +" slot_names = mapping.get('slot_names', [])\n" +" for offset, name in enumerate(slot_names):\n" +" mapping[name] = Member(name, clsname, offset)\n" +" return type.__new__(mcls, clsname, bases, mapping, **kwargs)" +msgstr "" + #: howto/descriptor.rst:1701 msgid "" "The :meth:`object.__new__` method takes care of creating instances that have " @@ -1044,23 +1821,97 @@ msgid "" "Python:" msgstr "" +#: howto/descriptor.rst:1705 +msgid "" +"class Object:\n" +" 'Simulate how object.__new__() allocates memory for __slots__'\n" +"\n" +" def __new__(cls, *args, **kwargs):\n" +" 'Emulate object_new() in Objects/typeobject.c'\n" +" inst = super().__new__(cls)\n" +" if hasattr(cls, 'slot_names'):\n" +" empty_slots = [null] * len(cls.slot_names)\n" +" object.__setattr__(inst, '_slotvalues', empty_slots)\n" +" return inst\n" +"\n" +" def __setattr__(self, name, value):\n" +" 'Emulate _PyObject_GenericSetAttrWithDict() Objects/object.c'\n" +" cls = type(self)\n" +" if hasattr(cls, 'slot_names') and name not in cls.slot_names:\n" +" raise AttributeError(\n" +" f'{cls.__name__!r} object has no attribute {name!r}'\n" +" )\n" +" super().__setattr__(name, value)\n" +"\n" +" def __delattr__(self, name):\n" +" 'Emulate _PyObject_GenericSetAttrWithDict() Objects/object.c'\n" +" cls = type(self)\n" +" if hasattr(cls, 'slot_names') and name not in cls.slot_names:\n" +" raise AttributeError(\n" +" f'{cls.__name__!r} object has no attribute {name!r}'\n" +" )\n" +" super().__delattr__(name)" +msgstr "" + #: howto/descriptor.rst:1736 msgid "" "To use the simulation in a real class, just inherit from :class:`Object` and " "set the :term:`metaclass` to :class:`Type`:" msgstr "" +#: howto/descriptor.rst:1739 +msgid "" +"class H(Object, metaclass=Type):\n" +" 'Instance variables stored in slots'\n" +"\n" +" slot_names = ['x', 'y']\n" +"\n" +" def __init__(self, x, y):\n" +" self.x = x\n" +" self.y = y" +msgstr "" + #: howto/descriptor.rst:1750 msgid "" "At this point, the metaclass has loaded member objects for *x* and *y*::" msgstr "" +#: howto/descriptor.rst:1752 +msgid "" +">>> from pprint import pp\n" +">>> pp(dict(vars(H)))\n" +"{'__module__': '__main__',\n" +" '__doc__': 'Instance variables stored in slots',\n" +" 'slot_names': ['x', 'y'],\n" +" '__init__': ,\n" +" 'x': ,\n" +" 'y': }" +msgstr "" + #: howto/descriptor.rst:1771 msgid "" "When instances are created, they have a ``slot_values`` list where the " "attributes are stored:" msgstr "" +#: howto/descriptor.rst:1774 +msgid "" +">>> h = H(10, 20)\n" +">>> vars(h)\n" +"{'_slotvalues': [10, 20]}\n" +">>> h.x = 55\n" +">>> vars(h)\n" +"{'_slotvalues': [55, 20]}" +msgstr "" + #: howto/descriptor.rst:1783 msgid "Misspelled or unassigned attributes will raise an exception:" msgstr "" + +#: howto/descriptor.rst:1785 +msgid "" +">>> h.xz\n" +"Traceback (most recent call last):\n" +" ...\n" +"AttributeError: 'H' object has no attribute 'xz'" +msgstr "" diff --git a/howto/enum.po b/howto/enum.po index 4ad9fea78..f915168b2 100644 --- a/howto/enum.po +++ b/howto/enum.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -23,8 +23,8 @@ msgstr "" #: howto/enum.rst:9 msgid "" "An :class:`Enum` is a set of symbolic names bound to unique values. They " -"are similar to global variables, but they offer a more useful :func:" -"`repr()`, grouping, type-safety, and a few other features." +"are similar to global variables, but they offer a more useful :func:`repr`, " +"grouping, type-safety, and a few other features." msgstr "" #: howto/enum.rst:13 @@ -33,10 +33,32 @@ msgid "" "selection of values. For example, the days of the week::" msgstr "" +#: howto/enum.rst:16 +msgid "" +">>> from enum import Enum\n" +">>> class Weekday(Enum):\n" +"... MONDAY = 1\n" +"... TUESDAY = 2\n" +"... WEDNESDAY = 3\n" +"... THURSDAY = 4\n" +"... FRIDAY = 5\n" +"... SATURDAY = 6\n" +"... SUNDAY = 7" +msgstr "" + #: howto/enum.rst:26 msgid "Or perhaps the RGB primary colors::" msgstr "" +#: howto/enum.rst:28 +msgid "" +">>> from enum import Enum\n" +">>> class Color(Enum):\n" +"... RED = 1\n" +"... GREEN = 2\n" +"... BLUE = 3" +msgstr "" + #: howto/enum.rst:34 msgid "" "As you can see, creating an :class:`Enum` is as simple as writing a class " @@ -62,6 +84,12 @@ msgid "" "member::" msgstr "" +#: howto/enum.rst:48 +msgid "" +">>> Weekday(3)\n" +"" +msgstr "" + #: howto/enum.rst:51 msgid "" "As you can see, the ``repr()`` of a member shows the enum name, the member " @@ -69,18 +97,44 @@ msgid "" "member name::" msgstr "" +#: howto/enum.rst:55 +msgid "" +">>> print(Weekday.THURSDAY)\n" +"Weekday.THURSDAY" +msgstr "" + #: howto/enum.rst:58 msgid "The *type* of an enumeration member is the enum it belongs to::" msgstr "" +#: howto/enum.rst:60 +msgid "" +">>> type(Weekday.MONDAY)\n" +"\n" +">>> isinstance(Weekday.FRIDAY, Weekday)\n" +"True" +msgstr "" + #: howto/enum.rst:65 msgid "Enum members have an attribute that contains just their :attr:`name`::" msgstr "" +#: howto/enum.rst:67 +msgid "" +">>> print(Weekday.TUESDAY.name)\n" +"TUESDAY" +msgstr "" + #: howto/enum.rst:70 msgid "Likewise, they have an attribute for their :attr:`value`::" msgstr "" +#: howto/enum.rst:73 +msgid "" +">>> Weekday.WEDNESDAY.value\n" +"3" +msgstr "" + #: howto/enum.rst:76 msgid "" "Unlike many languages that treat enumerations solely as name/value pairs, " @@ -92,14 +146,44 @@ msgid "" "instance and return the matching enum member::" msgstr "" +#: howto/enum.rst:84 +msgid "" +"@classmethod\n" +"def from_date(cls, date):\n" +" return cls(date.isoweekday())" +msgstr "" + #: howto/enum.rst:88 msgid "The complete :class:`Weekday` enum now looks like this::" msgstr "" +#: howto/enum.rst:90 +msgid "" +">>> class Weekday(Enum):\n" +"... MONDAY = 1\n" +"... TUESDAY = 2\n" +"... WEDNESDAY = 3\n" +"... THURSDAY = 4\n" +"... FRIDAY = 5\n" +"... SATURDAY = 6\n" +"... SUNDAY = 7\n" +"... #\n" +"... @classmethod\n" +"... def from_date(cls, date):\n" +"... return cls(date.isoweekday())" +msgstr "" + #: howto/enum.rst:103 msgid "Now we can find out what today is! Observe::" msgstr "" +#: howto/enum.rst:105 +msgid "" +">>> from datetime import date\n" +">>> Weekday.from_date(date.today()) \n" +"" +msgstr "" + #: howto/enum.rst:109 msgid "" "Of course, if you're reading this on some other day, you'll see that day " @@ -114,6 +198,19 @@ msgid "" "different type of :class:`Enum`::" msgstr "" +#: howto/enum.rst:116 +msgid "" +">>> from enum import Flag\n" +">>> class Weekday(Flag):\n" +"... MONDAY = 1\n" +"... TUESDAY = 2\n" +"... WEDNESDAY = 4\n" +"... THURSDAY = 8\n" +"... FRIDAY = 16\n" +"... SATURDAY = 32\n" +"... SUNDAY = 64" +msgstr "" + #: howto/enum.rst:126 msgid "" "We've changed two things: we're inherited from :class:`Flag`, and the values " @@ -126,28 +223,85 @@ msgid "" "selection::" msgstr "" +#: howto/enum.rst:131 +msgid "" +">>> first_week_day = Weekday.MONDAY\n" +">>> first_week_day\n" +"" +msgstr "" + #: howto/enum.rst:135 msgid "" "But :class:`Flag` also allows us to combine several members into a single " "variable::" msgstr "" +#: howto/enum.rst:138 +msgid "" +">>> weekend = Weekday.SATURDAY | Weekday.SUNDAY\n" +">>> weekend\n" +"" +msgstr "" + #: howto/enum.rst:142 msgid "You can even iterate over a :class:`Flag` variable::" msgstr "" +#: howto/enum.rst:144 +msgid "" +">>> for day in weekend:\n" +"... print(day)\n" +"Weekday.SATURDAY\n" +"Weekday.SUNDAY" +msgstr "" + #: howto/enum.rst:149 msgid "Okay, let's get some chores set up::" msgstr "" +#: howto/enum.rst:151 +msgid "" +">>> chores_for_ethan = {\n" +"... 'feed the cat': Weekday.MONDAY | Weekday.WEDNESDAY | Weekday." +"FRIDAY,\n" +"... 'do the dishes': Weekday.TUESDAY | Weekday.THURSDAY,\n" +"... 'answer SO questions': Weekday.SATURDAY,\n" +"... }" +msgstr "" + #: howto/enum.rst:157 msgid "And a function to display the chores for a given day::" msgstr "" +#: howto/enum.rst:159 +msgid "" +">>> def show_chores(chores, day):\n" +"... for chore, days in chores.items():\n" +"... if day in days:\n" +"... print(chore)\n" +"...\n" +">>> show_chores(chores_for_ethan, Weekday.SATURDAY)\n" +"answer SO questions" +msgstr "" + #: howto/enum.rst:167 msgid "" "In cases where the actual values of the members do not matter, you can save " -"yourself some work and use :func:`auto()` for the values::" +"yourself some work and use :func:`auto` for the values::" +msgstr "" + +#: howto/enum.rst:170 +msgid "" +">>> from enum import auto\n" +">>> class Weekday(Flag):\n" +"... MONDAY = auto()\n" +"... TUESDAY = auto()\n" +"... WEDNESDAY = auto()\n" +"... THURSDAY = auto()\n" +"... FRIDAY = auto()\n" +"... SATURDAY = auto()\n" +"... SUNDAY = auto()\n" +"... WEEKEND = SATURDAY | SUNDAY" msgstr "" #: howto/enum.rst:186 @@ -161,14 +315,39 @@ msgid "" "known at program-writing time). ``Enum`` allows such access::" msgstr "" +#: howto/enum.rst:192 +msgid "" +">>> Color(1)\n" +"\n" +">>> Color(3)\n" +"" +msgstr "" + #: howto/enum.rst:197 msgid "If you want to access enum members by *name*, use item access::" msgstr "" +#: howto/enum.rst:199 +msgid "" +">>> Color['RED']\n" +"\n" +">>> Color['GREEN']\n" +"" +msgstr "" + #: howto/enum.rst:204 msgid "If you have an enum member and need its :attr:`name` or :attr:`value`::" msgstr "" +#: howto/enum.rst:206 +msgid "" +">>> member = Color.RED\n" +">>> member.name\n" +"'RED'\n" +">>> member.value\n" +"1" +msgstr "" + #: howto/enum.rst:214 msgid "Duplicating enum members and values" msgstr "" @@ -177,6 +356,17 @@ msgstr "" msgid "Having two enum members with the same name is invalid::" msgstr "" +#: howto/enum.rst:218 +msgid "" +">>> class Shape(Enum):\n" +"... SQUARE = 2\n" +"... SQUARE = 3\n" +"...\n" +"Traceback (most recent call last):\n" +"...\n" +"TypeError: 'SQUARE' already defined as 2" +msgstr "" + #: howto/enum.rst:226 msgid "" "However, an enum member can have other names associated with it. Given two " @@ -186,6 +376,22 @@ msgid "" "member ``A``. By-name lookup of ``B`` will also return the member ``A``::" msgstr "" +#: howto/enum.rst:232 +msgid "" +">>> class Shape(Enum):\n" +"... SQUARE = 2\n" +"... DIAMOND = 1\n" +"... CIRCLE = 3\n" +"... ALIAS_FOR_SQUARE = 2\n" +"...\n" +">>> Shape.SQUARE\n" +"\n" +">>> Shape.ALIAS_FOR_SQUARE\n" +"\n" +">>> Shape(2)\n" +"" +msgstr "" + #: howto/enum.rst:247 msgid "" "Attempting to create a member with the same name as an already defined " @@ -203,6 +409,21 @@ msgid "" "When this behavior isn't desired, you can use the :func:`unique` decorator::" msgstr "" +#: howto/enum.rst:258 +msgid "" +">>> from enum import Enum, unique\n" +">>> @unique\n" +"... class Mistake(Enum):\n" +"... ONE = 1\n" +"... TWO = 2\n" +"... THREE = 3\n" +"... FOUR = 3\n" +"...\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: duplicate values found in : FOUR -> THREE" +msgstr "" + #: howto/enum.rst:272 msgid "Using automatic values" msgstr "" @@ -211,12 +432,41 @@ msgstr "" msgid "If the exact value is unimportant you can use :class:`auto`::" msgstr "" +#: howto/enum.rst:276 +msgid "" +">>> from enum import Enum, auto\n" +">>> class Color(Enum):\n" +"... RED = auto()\n" +"... BLUE = auto()\n" +"... GREEN = auto()\n" +"...\n" +">>> [member.value for member in Color]\n" +"[1, 2, 3]" +msgstr "" + #: howto/enum.rst:285 msgid "" "The values are chosen by :func:`_generate_next_value_`, which can be " "overridden::" msgstr "" +#: howto/enum.rst:288 +msgid "" +">>> class AutoName(Enum):\n" +"... @staticmethod\n" +"... def _generate_next_value_(name, start, count, last_values):\n" +"... return name\n" +"...\n" +">>> class Ordinal(AutoName):\n" +"... NORTH = auto()\n" +"... SOUTH = auto()\n" +"... EAST = auto()\n" +"... WEST = auto()\n" +"...\n" +">>> [member.value for member in Ordinal]\n" +"['NORTH', 'SOUTH', 'EAST', 'WEST']" +msgstr "" + #: howto/enum.rst:304 msgid "" "The :meth:`_generate_next_value_` method must be defined before any members." @@ -230,6 +480,16 @@ msgstr "" msgid "Iterating over the members of an enum does not provide the aliases::" msgstr "" +#: howto/enum.rst:311 +msgid "" +">>> list(Shape)\n" +"[, , ]\n" +">>> list(Weekday)\n" +"[, , , , , , ]" +msgstr "" + #: howto/enum.rst:316 msgid "" "Note that the aliases ``Shape.ALIAS_FOR_SQUARE`` and ``Weekday.WEEKEND`` " @@ -243,12 +503,30 @@ msgid "" "including the aliases::" msgstr "" +#: howto/enum.rst:322 +msgid "" +">>> for name, member in Shape.__members__.items():\n" +"... name, member\n" +"...\n" +"('SQUARE', )\n" +"('DIAMOND', )\n" +"('CIRCLE', )\n" +"('ALIAS_FOR_SQUARE', )" +msgstr "" + #: howto/enum.rst:330 msgid "" "The ``__members__`` attribute can be used for detailed programmatic access " "to the enumeration members. For example, finding all the aliases::" msgstr "" +#: howto/enum.rst:333 +msgid "" +">>> [name for name, member in Shape.__members__.items() if member.name != " +"name]\n" +"['ALIAS_FOR_SQUARE']" +msgstr "" + #: howto/enum.rst:338 msgid "" "Aliases for flags include values with multiple flags set, such as ``3``, and " @@ -263,16 +541,44 @@ msgstr "" msgid "Enumeration members are compared by identity::" msgstr "" +#: howto/enum.rst:347 +msgid "" +">>> Color.RED is Color.RED\n" +"True\n" +">>> Color.RED is Color.BLUE\n" +"False\n" +">>> Color.RED is not Color.BLUE\n" +"True" +msgstr "" + #: howto/enum.rst:354 msgid "" "Ordered comparisons between enumeration values are *not* supported. Enum " "members are not integers (but see `IntEnum`_ below)::" msgstr "" +#: howto/enum.rst:357 +msgid "" +">>> Color.RED < Color.BLUE\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: '<' not supported between instances of 'Color' and 'Color'" +msgstr "" + #: howto/enum.rst:362 msgid "Equality comparisons are defined though::" msgstr "" +#: howto/enum.rst:364 +msgid "" +">>> Color.BLUE == Color.RED\n" +"False\n" +">>> Color.BLUE != Color.RED\n" +"True\n" +">>> Color.BLUE == Color.BLUE\n" +"True" +msgstr "" + #: howto/enum.rst:371 msgid "" "Comparisons against non-enumeration values will always compare not equal " @@ -280,6 +586,12 @@ msgid "" "below)::" msgstr "" +#: howto/enum.rst:375 +msgid "" +">>> Color.BLUE == 2\n" +"False" +msgstr "" + #: howto/enum.rst:380 msgid "" "It is possible to reload modules -- if a reloaded module contains enums, " @@ -306,10 +618,40 @@ msgid "" "usual. If we have this enumeration::" msgstr "" +#: howto/enum.rst:396 +msgid "" +">>> class Mood(Enum):\n" +"... FUNKY = 1\n" +"... HAPPY = 3\n" +"...\n" +"... def describe(self):\n" +"... # self is the member here\n" +"... return self.name, self.value\n" +"...\n" +"... def __str__(self):\n" +"... return 'my custom str! {0}'.format(self.value)\n" +"...\n" +"... @classmethod\n" +"... def favorite_mood(cls):\n" +"... # cls here is the enumeration\n" +"... return cls.HAPPY\n" +"..." +msgstr "" + #: howto/enum.rst:413 msgid "Then::" msgstr "" +#: howto/enum.rst:415 +msgid "" +">>> Mood.favorite_mood()\n" +"\n" +">>> Mood.HAPPY.describe()\n" +"('HAPPY', 3)\n" +">>> str(Mood.FUNKY)\n" +"'my custom str! 1'" +msgstr "" + #: howto/enum.rst:422 msgid "" "The rules for what is allowed are as follows: names that start and end with " @@ -346,16 +688,44 @@ msgid "" "order of these base classes is::" msgstr "" +#: howto/enum.rst:448 +msgid "" +"class EnumName([mix-in, ...,] [data-type,] base-enum):\n" +" pass" +msgstr "" + #: howto/enum.rst:451 msgid "" "Also, subclassing an enumeration is allowed only if the enumeration does not " "define any members. So this is forbidden::" msgstr "" +#: howto/enum.rst:454 +msgid "" +">>> class MoreColor(Color):\n" +"... PINK = 17\n" +"...\n" +"Traceback (most recent call last):\n" +"...\n" +"TypeError: cannot extend " +msgstr "" + #: howto/enum.rst:461 msgid "But this is allowed::" msgstr "" +#: howto/enum.rst:463 +msgid "" +">>> class Foo(Enum):\n" +"... def some_behavior(self):\n" +"... pass\n" +"...\n" +">>> class Bar(Foo):\n" +"... HAPPY = 1\n" +"... SAD = 2\n" +"..." +msgstr "" + #: howto/enum.rst:472 msgid "" "Allowing subclassing of enums that define members would lead to a violation " @@ -374,6 +744,23 @@ msgid "" "__repr__` omits the inherited class' name. For example::" msgstr "" +#: howto/enum.rst:486 +msgid "" +">>> from dataclasses import dataclass, field\n" +">>> @dataclass\n" +"... class CreatureDataMixin:\n" +"... size: str\n" +"... legs: int\n" +"... tail: bool = field(repr=False, default=True)\n" +"...\n" +">>> class Creature(CreatureDataMixin, Enum):\n" +"... BEETLE = 'small', 6\n" +"... DOG = 'medium', 4\n" +"...\n" +">>> Creature.DOG\n" +"" +msgstr "" + #: howto/enum.rst:500 msgid "" "Use the :func:`!dataclass` argument ``repr=False`` to use the standard :func:" @@ -394,6 +781,14 @@ msgstr "" msgid "Enumerations can be pickled and unpickled::" msgstr "" +#: howto/enum.rst:513 +msgid "" +">>> from test.test_enum import Fruit\n" +">>> from pickle import dumps, loads\n" +">>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO))\n" +"True" +msgstr "" + #: howto/enum.rst:518 msgid "" "The usual restrictions for pickling apply: picklable enums must be defined " @@ -414,6 +809,13 @@ msgid "" "value, but enums with complicated values may want to use by-name::" msgstr "" +#: howto/enum.rst:531 +msgid "" +">>> import enum\n" +">>> class MyEnum(enum.Enum):\n" +"... __reduce_ex__ = enum.pickle_by_enum_name" +msgstr "" + #: howto/enum.rst:537 msgid "" "Using by-name for flags is not recommended, as unnamed aliases will not " @@ -429,6 +831,17 @@ msgid "" "The :class:`Enum` class is callable, providing the following functional API::" msgstr "" +#: howto/enum.rst:546 +msgid "" +">>> Animal = Enum('Animal', 'ANT BEE CAT DOG')\n" +">>> Animal\n" +"\n" +">>> Animal.ANT\n" +"\n" +">>> list(Animal)\n" +"[, , , ]" +msgstr "" + #: howto/enum.rst:554 msgid "" "The semantics of this API resemble :class:`~collections.namedtuple`. The " @@ -447,6 +860,16 @@ msgid "" "assignment to :class:`Animal` is equivalent to::" msgstr "" +#: howto/enum.rst:566 +msgid "" +">>> class Animal(Enum):\n" +"... ANT = 1\n" +"... BEE = 2\n" +"... CAT = 3\n" +"... DOG = 4\n" +"..." +msgstr "" + #: howto/enum.rst:573 msgid "" "The reason for defaulting to ``1`` as the starting number and not ``0`` is " @@ -463,6 +886,10 @@ msgid "" "Jython). The solution is to specify the module name explicitly as follows::" msgstr "" +#: howto/enum.rst:583 +msgid ">>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__)" +msgstr "" + #: howto/enum.rst:587 msgid "" "If ``module`` is not supplied, and Enum cannot determine what it is, the new " @@ -473,15 +900,33 @@ msgstr "" #: howto/enum.rst:591 msgid "" "The new pickle protocol 4 also, in some circumstances, relies on :attr:" -"`~definition.__qualname__` being set to the location where pickle will be " -"able to find the class. For example, if the class was made available in " -"class SomeData in the global scope::" +"`~type.__qualname__` being set to the location where pickle will be able to " +"find the class. For example, if the class was made available in class " +"SomeData in the global scope::" +msgstr "" + +#: howto/enum.rst:596 +msgid "" +">>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal')" msgstr "" #: howto/enum.rst:598 msgid "The complete signature is::" msgstr "" +#: howto/enum.rst:600 +msgid "" +"Enum(\n" +" value='NewEnumName',\n" +" names=<...>,\n" +" *,\n" +" module='...',\n" +" qualname='...',\n" +" type=,\n" +" start=1,\n" +" )" +msgstr "" + #: howto/enum.rst:610 msgid "*value*: What the new enum class will record as its name." msgstr "" @@ -492,18 +937,34 @@ msgid "" "string (values will start at 1 unless otherwise specified)::" msgstr "" +#: howto/enum.rst:615 +msgid "'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE'" +msgstr "" + #: howto/enum.rst:617 msgid "or an iterator of names::" msgstr "" +#: howto/enum.rst:619 +msgid "['RED', 'GREEN', 'BLUE']" +msgstr "" + #: howto/enum.rst:621 msgid "or an iterator of (name, value) pairs::" msgstr "" +#: howto/enum.rst:623 +msgid "[('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)]" +msgstr "" + #: howto/enum.rst:625 msgid "or a mapping::" msgstr "" +#: howto/enum.rst:627 +msgid "{'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42}" +msgstr "" + #: howto/enum.rst:629 msgid "*module*: name of module where new enum class can be found." msgstr "" @@ -540,17 +1001,60 @@ msgid "" "each other::" msgstr "" +#: howto/enum.rst:652 +msgid "" +">>> from enum import IntEnum\n" +">>> class Shape(IntEnum):\n" +"... CIRCLE = 1\n" +"... SQUARE = 2\n" +"...\n" +">>> class Request(IntEnum):\n" +"... POST = 1\n" +"... GET = 2\n" +"...\n" +">>> Shape == 1\n" +"False\n" +">>> Shape.CIRCLE == 1\n" +"True\n" +">>> Shape.CIRCLE == Request.POST\n" +"True" +msgstr "" + #: howto/enum.rst:668 msgid "" "However, they still can't be compared to standard :class:`Enum` " "enumerations::" msgstr "" +#: howto/enum.rst:670 +msgid "" +">>> class Shape(IntEnum):\n" +"... CIRCLE = 1\n" +"... SQUARE = 2\n" +"...\n" +">>> class Color(Enum):\n" +"... RED = 1\n" +"... GREEN = 2\n" +"...\n" +">>> Shape.CIRCLE == Color.RED\n" +"False" +msgstr "" + #: howto/enum.rst:681 msgid "" ":class:`IntEnum` values behave like integers in other ways you'd expect::" msgstr "" +#: howto/enum.rst:683 +msgid "" +">>> int(Shape.CIRCLE)\n" +"1\n" +">>> ['a', 'b', 'c'][Shape.CIRCLE]\n" +"'b'\n" +">>> [i for i in range(Shape.SQUARE)]\n" +"[0, 1]" +msgstr "" + #: howto/enum.rst:692 msgid "StrEnum" msgstr "" @@ -593,10 +1097,43 @@ msgstr "" msgid "Sample :class:`IntFlag` class::" msgstr "" +#: howto/enum.rst:725 +msgid "" +">>> from enum import IntFlag\n" +">>> class Perm(IntFlag):\n" +"... R = 4\n" +"... W = 2\n" +"... X = 1\n" +"...\n" +">>> Perm.R | Perm.W\n" +"\n" +">>> Perm.R + Perm.W\n" +"6\n" +">>> RW = Perm.R | Perm.W\n" +">>> Perm.R in RW\n" +"True" +msgstr "" + #: howto/enum.rst:739 msgid "It is also possible to name the combinations::" msgstr "" +#: howto/enum.rst:741 +msgid "" +">>> class Perm(IntFlag):\n" +"... R = 4\n" +"... W = 2\n" +"... X = 1\n" +"... RWX = 7\n" +"...\n" +">>> Perm.RWX\n" +"\n" +">>> ~Perm.RWX\n" +"\n" +">>> Perm(7)\n" +"" +msgstr "" + #: howto/enum.rst:756 msgid "" "Named combinations are considered aliases. Aliases do not show up during " @@ -610,22 +1147,51 @@ msgid "" "`False`::" msgstr "" +#: howto/enum.rst:764 +msgid "" +">>> Perm.R & Perm.X\n" +"\n" +">>> bool(Perm.R & Perm.X)\n" +"False" +msgstr "" + #: howto/enum.rst:769 msgid "" "Because :class:`IntFlag` members are also subclasses of :class:`int` they " "can be combined with them (but may lose :class:`IntFlag` membership::" msgstr "" +#: howto/enum.rst:772 +msgid "" +">>> Perm.X | 4\n" +"\n" +"\n" +">>> Perm.X + 8\n" +"9" +msgstr "" + #: howto/enum.rst:780 msgid "" "The negation operator, ``~``, always returns an :class:`IntFlag` member with " "a positive value::" msgstr "" +#: howto/enum.rst:783 +msgid "" +">>> (~Perm.X).value == (Perm.R|Perm.W).value == 6\n" +"True" +msgstr "" + #: howto/enum.rst:786 msgid ":class:`IntFlag` members can also be iterated over::" msgstr "" +#: howto/enum.rst:788 +msgid "" +">>> list(RW)\n" +"[, ]" +msgstr "" + #: howto/enum.rst:795 msgid "Flag" msgstr "" @@ -646,22 +1212,69 @@ msgid "" "no flags being set, the boolean evaluation is :data:`False`::" msgstr "" +#: howto/enum.rst:809 +msgid "" +">>> from enum import Flag, auto\n" +">>> class Color(Flag):\n" +"... RED = auto()\n" +"... BLUE = auto()\n" +"... GREEN = auto()\n" +"...\n" +">>> Color.RED & Color.GREEN\n" +"\n" +">>> bool(Color.RED & Color.GREEN)\n" +"False" +msgstr "" + #: howto/enum.rst:820 msgid "" "Individual flags should have values that are powers of two (1, 2, 4, " "8, ...), while combinations of flags will not::" msgstr "" +#: howto/enum.rst:823 +msgid "" +">>> class Color(Flag):\n" +"... RED = auto()\n" +"... BLUE = auto()\n" +"... GREEN = auto()\n" +"... WHITE = RED | BLUE | GREEN\n" +"...\n" +">>> Color.WHITE\n" +"" +msgstr "" + #: howto/enum.rst:832 msgid "" "Giving a name to the \"no flags set\" condition does not change its boolean " "value::" msgstr "" +#: howto/enum.rst:835 +msgid "" +">>> class Color(Flag):\n" +"... BLACK = 0\n" +"... RED = auto()\n" +"... BLUE = auto()\n" +"... GREEN = auto()\n" +"...\n" +">>> Color.BLACK\n" +"\n" +">>> bool(Color.BLACK)\n" +"False" +msgstr "" + #: howto/enum.rst:846 msgid ":class:`Flag` members can also be iterated over::" msgstr "" +#: howto/enum.rst:848 +msgid "" +">>> purple = Color.RED | Color.BLUE\n" +">>> list(purple)\n" +"[, ]" +msgstr "" + #: howto/enum.rst:856 msgid "" "For the majority of new code, :class:`Enum` and :class:`Flag` are strongly " @@ -683,6 +1296,12 @@ msgid "" "simple to implement independently::" msgstr "" +#: howto/enum.rst:871 +msgid "" +"class IntEnum(int, Enum):\n" +" pass" +msgstr "" + #: howto/enum.rst:874 msgid "" "This demonstrates how similar derived enumerations can be defined; for " @@ -766,6 +1385,31 @@ msgid "" "want one of them to be the value::" msgstr "" +#: howto/enum.rst:919 +msgid "" +">>> class Coordinate(bytes, Enum):\n" +"... \"\"\"\n" +"... Coordinate with binary codes that can be indexed by the int code.\n" +"... \"\"\"\n" +"... def __new__(cls, value, label, unit):\n" +"... obj = bytes.__new__(cls, [value])\n" +"... obj._value_ = value\n" +"... obj.label = label\n" +"... obj.unit = unit\n" +"... return obj\n" +"... PX = (0, 'P.X', 'km')\n" +"... PY = (1, 'P.Y', 'km')\n" +"... VX = (2, 'V.X', 'km/s')\n" +"... VY = (3, 'V.Y', 'km/s')\n" +"...\n" +"\n" +">>> print(Coordinate['PY'])\n" +"Coordinate.PY\n" +"\n" +">>> print(Coordinate(3))\n" +"Coordinate.VY" +msgstr "" + #: howto/enum.rst:943 msgid "" "*Do not* call ``super().__new__()``, as the lookup-only ``__new__`` is the " @@ -858,6 +1502,21 @@ msgid "" "enumeration and raise an error if the two do not match::" msgstr "" +#: howto/enum.rst:993 +msgid "" +">>> class Color(Enum):\n" +"... _order_ = 'RED GREEN BLUE'\n" +"... RED = 1\n" +"... BLUE = 3\n" +"... GREEN = 2\n" +"...\n" +"Traceback (most recent call last):\n" +"...\n" +"TypeError: member order does not match _order_:\n" +" ['RED', 'BLUE', 'GREEN']\n" +" ['RED', 'GREEN', 'BLUE']" +msgstr "" + #: howto/enum.rst:1007 msgid "" "In Python 2 code the :attr:`_order_` attribute is necessary as definition " @@ -899,6 +1558,15 @@ msgid "" "type's constructor. For example::" msgstr "" +#: howto/enum.rst:1040 +msgid "" +">>> class MyEnum(IntEnum): # help(int) -> int(x, base=10) -> integer\n" +"... example = '11', 16 # so x='11' and base=16\n" +"...\n" +">>> MyEnum.example.value # and hex(11) is...\n" +"17" +msgstr "" + #: howto/enum.rst:1048 msgid "Boolean value of ``Enum`` classes and members" msgstr "" @@ -912,6 +1580,12 @@ msgid "" "your class::" msgstr "" +#: howto/enum.rst:1056 +msgid "" +"def __bool__(self):\n" +" return bool(self.value)" +msgstr "" + #: howto/enum.rst:1059 msgid "Plain :class:`Enum` classes always evaluate as :data:`True`." msgstr "" @@ -927,6 +1601,16 @@ msgid "" "the class::" msgstr "" +#: howto/enum.rst:1069 +msgid "" +">>> dir(Planet) \n" +"['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', " +"'VENUS', '__class__', '__doc__', '__members__', '__module__']\n" +">>> dir(Planet.EARTH) \n" +"['__class__', '__doc__', '__module__', 'mass', 'name', 'radius', " +"'surface_gravity', 'value']" +msgstr "" + #: howto/enum.rst:1076 msgid "Combining members of ``Flag``" msgstr "" @@ -937,6 +1621,22 @@ msgid "" "members that are comprised of a single bit::" msgstr "" +#: howto/enum.rst:1081 +msgid "" +">>> class Color(Flag):\n" +"... RED = auto()\n" +"... GREEN = auto()\n" +"... BLUE = auto()\n" +"... MAGENTA = RED | BLUE\n" +"... YELLOW = RED | GREEN\n" +"... CYAN = GREEN | BLUE\n" +"...\n" +">>> Color(3) # named combination\n" +"\n" +">>> Color(7) # not named combination\n" +"" +msgstr "" + #: howto/enum.rst:1096 msgid "``Flag`` and ``IntFlag`` minutia" msgstr "" @@ -945,6 +1645,18 @@ msgstr "" msgid "Using the following snippet for our examples::" msgstr "" +#: howto/enum.rst:1100 +msgid "" +">>> class Color(IntFlag):\n" +"... BLACK = 0\n" +"... RED = 1\n" +"... GREEN = 2\n" +"... BLUE = 4\n" +"... PURPLE = RED | BLUE\n" +"... WHITE = RED | GREEN | BLUE\n" +"..." +msgstr "" + #: howto/enum.rst:1109 msgid "the following are true:" msgstr "" @@ -961,32 +1673,88 @@ msgstr "" msgid "only canonical flags are returned during iteration::" msgstr "" +#: howto/enum.rst:1115 +msgid "" +">>> list(Color.WHITE)\n" +"[, , ]" +msgstr "" + #: howto/enum.rst:1118 msgid "" "negating a flag or flag set returns a new flag/flag set with the " "corresponding positive integer value::" msgstr "" +#: howto/enum.rst:1121 +msgid "" +">>> Color.BLUE\n" +"\n" +"\n" +">>> ~Color.BLUE\n" +"" +msgstr "" + #: howto/enum.rst:1127 msgid "names of pseudo-flags are constructed from their members' names::" msgstr "" +#: howto/enum.rst:1129 +msgid "" +">>> (Color.RED | Color.GREEN).name\n" +"'RED|GREEN'\n" +"\n" +">>> class Perm(IntFlag):\n" +"... R = 4\n" +"... W = 2\n" +"... X = 1\n" +"...\n" +">>> (Perm.R & Perm.W).name is None # effectively Perm(0)\n" +"True" +msgstr "" + #: howto/enum.rst:1140 msgid "multi-bit flags, aka aliases, can be returned from operations::" msgstr "" +#: howto/enum.rst:1142 +msgid "" +">>> Color.RED | Color.BLUE\n" +"\n" +"\n" +">>> Color(7) # or Color(-1)\n" +"\n" +"\n" +">>> Color(0)\n" +"" +msgstr "" + #: howto/enum.rst:1151 msgid "" "membership / containment checking: zero-valued flags are always considered " "to be contained::" msgstr "" +#: howto/enum.rst:1154 +msgid "" +">>> Color.BLACK in Color.WHITE\n" +"True" +msgstr "" + #: howto/enum.rst:1157 msgid "" "otherwise, only if all bits of one flag are in the other flag will True be " "returned::" msgstr "" +#: howto/enum.rst:1160 +msgid "" +">>> Color.PURPLE in Color.WHITE\n" +"True\n" +"\n" +">>> Color.GREEN in Color.PURPLE\n" +"False" +msgstr "" + #: howto/enum.rst:1166 msgid "" "There is a new boundary mechanism that controls how out-of-range / invalid " @@ -1089,6 +1857,12 @@ msgid "" "only the canonical members will be returned. For example::" msgstr "" +#: howto/enum.rst:1225 +msgid "" +">>> list(Color)\n" +"[, , ]" +msgstr "" + #: howto/enum.rst:1228 msgid "(Note that ``BLACK``, ``PURPLE``, and ``WHITE`` do not show up.)" msgstr "" @@ -1099,12 +1873,24 @@ msgid "" "than a negative value --- for example::" msgstr "" +#: howto/enum.rst:1233 +msgid "" +">>> ~Color.RED\n" +"" +msgstr "" + #: howto/enum.rst:1236 msgid "" "Flag members have a length corresponding to the number of power-of-two " "values they contain. For example::" msgstr "" +#: howto/enum.rst:1239 +msgid "" +">>> len(Color.PURPLE)\n" +"2" +msgstr "" + #: howto/enum.rst:1246 msgid "Enum Cookbook" msgstr "" @@ -1160,6 +1946,17 @@ msgstr "" msgid "Using :class:`auto` would look like::" msgstr "" +#: howto/enum.rst:1277 +msgid "" +">>> class Color(Enum):\n" +"... RED = auto()\n" +"... BLUE = auto()\n" +"... GREEN = auto()\n" +"...\n" +">>> Color.GREEN\n" +"" +msgstr "" + #: howto/enum.rst:1287 msgid "Using :class:`object`" msgstr "" @@ -1168,12 +1965,36 @@ msgstr "" msgid "Using :class:`object` would look like::" msgstr "" +#: howto/enum.rst:1291 +msgid "" +">>> class Color(Enum):\n" +"... RED = object()\n" +"... GREEN = object()\n" +"... BLUE = object()\n" +"...\n" +">>> Color.GREEN \n" +">" +msgstr "" + #: howto/enum.rst:1299 msgid "" "This is also a good example of why you might want to write your own :meth:" "`__repr__`::" msgstr "" +#: howto/enum.rst:1302 +msgid "" +">>> class Color(Enum):\n" +"... RED = object()\n" +"... GREEN = object()\n" +"... BLUE = object()\n" +"... def __repr__(self):\n" +"... return \"<%s.%s>\" % (self.__class__.__name__, self._name_)\n" +"...\n" +">>> Color.GREEN\n" +"" +msgstr "" + #: howto/enum.rst:1315 msgid "Using a descriptive string" msgstr "" @@ -1182,6 +2003,17 @@ msgstr "" msgid "Using a string as the value would look like::" msgstr "" +#: howto/enum.rst:1319 +msgid "" +">>> class Color(Enum):\n" +"... RED = 'stop'\n" +"... GREEN = 'go'\n" +"... BLUE = 'too fast!'\n" +"...\n" +">>> Color.GREEN\n" +"" +msgstr "" + #: howto/enum.rst:1329 msgid "Using a custom :meth:`__new__`" msgstr "" @@ -1190,18 +2022,64 @@ msgstr "" msgid "Using an auto-numbering :meth:`__new__` would look like::" msgstr "" +#: howto/enum.rst:1333 +msgid "" +">>> class AutoNumber(Enum):\n" +"... def __new__(cls):\n" +"... value = len(cls.__members__) + 1\n" +"... obj = object.__new__(cls)\n" +"... obj._value_ = value\n" +"... return obj\n" +"...\n" +">>> class Color(AutoNumber):\n" +"... RED = ()\n" +"... GREEN = ()\n" +"... BLUE = ()\n" +"...\n" +">>> Color.GREEN\n" +"" +msgstr "" + #: howto/enum.rst:1348 msgid "" "To make a more general purpose ``AutoNumber``, add ``*args`` to the " "signature::" msgstr "" +#: howto/enum.rst:1350 +msgid "" +">>> class AutoNumber(Enum):\n" +"... def __new__(cls, *args): # this is the only change from above\n" +"... value = len(cls.__members__) + 1\n" +"... obj = object.__new__(cls)\n" +"... obj._value_ = value\n" +"... return obj\n" +"..." +msgstr "" + #: howto/enum.rst:1358 msgid "" "Then when you inherit from ``AutoNumber`` you can write your own " "``__init__`` to handle any extra arguments::" msgstr "" +#: howto/enum.rst:1361 +msgid "" +">>> class Swatch(AutoNumber):\n" +"... def __init__(self, pantone='unknown'):\n" +"... self.pantone = pantone\n" +"... AUBURN = '3497'\n" +"... SEA_GREEN = '1246'\n" +"... BLEACHED_CORAL = () # New color, no Pantone code yet!\n" +"...\n" +">>> Swatch.SEA_GREEN\n" +"\n" +">>> Swatch.SEA_GREEN.pantone\n" +"'1246'\n" +">>> Swatch.BLEACHED_CORAL.pantone\n" +"'unknown'" +msgstr "" + #: howto/enum.rst:1377 msgid "" "The :meth:`__new__` method, if defined, is used during creation of the Enum " @@ -1215,6 +2093,10 @@ msgid "" "one that is found; instead, use the data type directly -- e.g.::" msgstr "" +#: howto/enum.rst:1386 +msgid "obj = int.__new__(cls, value)" +msgstr "" + #: howto/enum.rst:1390 msgid "OrderedEnum" msgstr "" @@ -1226,6 +2108,37 @@ msgid "" "to other enumerations)::" msgstr "" +#: howto/enum.rst:1396 +msgid "" +">>> class OrderedEnum(Enum):\n" +"... def __ge__(self, other):\n" +"... if self.__class__ is other.__class__:\n" +"... return self.value >= other.value\n" +"... return NotImplemented\n" +"... def __gt__(self, other):\n" +"... if self.__class__ is other.__class__:\n" +"... return self.value > other.value\n" +"... return NotImplemented\n" +"... def __le__(self, other):\n" +"... if self.__class__ is other.__class__:\n" +"... return self.value <= other.value\n" +"... return NotImplemented\n" +"... def __lt__(self, other):\n" +"... if self.__class__ is other.__class__:\n" +"... return self.value < other.value\n" +"... return NotImplemented\n" +"...\n" +">>> class Grade(OrderedEnum):\n" +"... A = 5\n" +"... B = 4\n" +"... C = 3\n" +"... D = 2\n" +"... F = 1\n" +"...\n" +">>> Grade.C < Grade.A\n" +"True" +msgstr "" + #: howto/enum.rst:1426 msgid "DuplicateFreeEnum" msgstr "" @@ -1236,6 +2149,30 @@ msgid "" "alias::" msgstr "" +#: howto/enum.rst:1431 +msgid "" +">>> class DuplicateFreeEnum(Enum):\n" +"... def __init__(self, *args):\n" +"... cls = self.__class__\n" +"... if any(self.value == e.value for e in cls):\n" +"... a = self.name\n" +"... e = cls(self.value).name\n" +"... raise ValueError(\n" +"... \"aliases not allowed in DuplicateFreeEnum: %r --> " +"%r\"\n" +"... % (a, e))\n" +"...\n" +">>> class Color(DuplicateFreeEnum):\n" +"... RED = 1\n" +"... GREEN = 2\n" +"... BLUE = 3\n" +"... GRENE = 2\n" +"...\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: aliases not allowed in DuplicateFreeEnum: 'GRENE' --> 'GREEN'" +msgstr "" + #: howto/enum.rst:1453 msgid "" "This is a useful example for subclassing Enum to add or change other " @@ -1253,6 +2190,32 @@ msgid "" "member will be passed to those methods::" msgstr "" +#: howto/enum.rst:1464 +msgid "" +">>> class Planet(Enum):\n" +"... MERCURY = (3.303e+23, 2.4397e6)\n" +"... VENUS = (4.869e+24, 6.0518e6)\n" +"... EARTH = (5.976e+24, 6.37814e6)\n" +"... MARS = (6.421e+23, 3.3972e6)\n" +"... JUPITER = (1.9e+27, 7.1492e7)\n" +"... SATURN = (5.688e+26, 6.0268e7)\n" +"... URANUS = (8.686e+25, 2.5559e7)\n" +"... NEPTUNE = (1.024e+26, 2.4746e7)\n" +"... def __init__(self, mass, radius):\n" +"... self.mass = mass # in kilograms\n" +"... self.radius = radius # in meters\n" +"... @property\n" +"... def surface_gravity(self):\n" +"... # universal gravitational constant (m3 kg-1 s-2)\n" +"... G = 6.67300E-11\n" +"... return G * self.mass / (self.radius * self.radius)\n" +"...\n" +">>> Planet.EARTH.value\n" +"(5.976e+24, 6378140.0)\n" +">>> Planet.EARTH.surface_gravity\n" +"9.802652743337129" +msgstr "" + #: howto/enum.rst:1490 msgid "TimePeriod" msgstr "" @@ -1261,6 +2224,24 @@ msgstr "" msgid "An example to show the :attr:`_ignore_` attribute in use::" msgstr "" +#: howto/enum.rst:1494 +msgid "" +">>> from datetime import timedelta\n" +">>> class Period(timedelta, Enum):\n" +"... \"different lengths of time\"\n" +"... _ignore_ = 'Period i'\n" +"... Period = vars()\n" +"... for i in range(367):\n" +"... Period['day_%d' % i] = i\n" +"...\n" +">>> list(Period)[:2]\n" +"[, ]\n" +">>> list(Period)[-2:]\n" +"[, ]" +msgstr "" + #: howto/enum.rst:1511 msgid "Subclassing EnumType" msgstr "" diff --git a/howto/functional.po b/howto/functional.po index d8a39ece8..99a128153 100644 --- a/howto/functional.po +++ b/howto/functional.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-01 21:53+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -330,6 +330,15 @@ msgid "" "an iterator. These two statements are equivalent::" msgstr "" +#: howto/functional.rst:222 +msgid "" +"for i in iter(obj):\n" +" print(i)\n" +"\n" +"for i in obj:\n" +" print(i)" +msgstr "" + #: howto/functional.rst:228 msgid "" "Iterators can be materialized as lists or tuples by using the :func:`list` " @@ -381,6 +390,26 @@ msgid "" "the dictionary's keys::" msgstr "" +#: howto/functional.rst:273 +msgid "" +">>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,\n" +"... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}\n" +">>> for key in m:\n" +"... print(key, m[key])\n" +"Jan 1\n" +"Feb 2\n" +"Mar 3\n" +"Apr 4\n" +"May 5\n" +"Jun 6\n" +"Jul 7\n" +"Aug 8\n" +"Sep 9\n" +"Oct 10\n" +"Nov 11\n" +"Dec 12" +msgstr "" + #: howto/functional.rst:290 msgid "" "Note that starting with Python 3.7, dictionary iteration order is guaranteed " @@ -409,12 +438,32 @@ msgid "" "each line of a file like this::" msgstr "" +#: howto/functional.rst:311 +msgid "" +"for line in file:\n" +" # do something for each line\n" +" ..." +msgstr "" + #: howto/functional.rst:315 msgid "" "Sets can take their contents from an iterable and let you iterate over the " "set's elements::" msgstr "" +#: howto/functional.rst:318 +msgid "" +">>> S = {2, 3, 5, 7, 11, 13}\n" +">>> for i in S:\n" +"... print(i)\n" +"2\n" +"3\n" +"5\n" +"7\n" +"11\n" +"13" +msgstr "" + #: howto/functional.rst:331 msgid "Generator expressions and list comprehensions" msgstr "" @@ -436,11 +485,28 @@ msgid "" "strip all the whitespace from a stream of strings with the following code::" msgstr "" +#: howto/functional.rst:344 +msgid "" +">>> line_list = [' line 1\\n', 'line 2 \\n', ' \\n', '']\n" +"\n" +">>> # Generator expression -- returns iterator\n" +">>> stripped_iter = (line.strip() for line in line_list)\n" +"\n" +">>> # List comprehension -- returns list\n" +">>> stripped_list = [line.strip() for line in line_list]" +msgstr "" + #: howto/functional.rst:352 msgid "" "You can select only certain elements by adding an ``\"if\"`` condition::" msgstr "" +#: howto/functional.rst:354 +msgid "" +">>> stripped_list = [line.strip() for line in line_list\n" +"... if line != \"\"]" +msgstr "" + #: howto/functional.rst:357 msgid "" "With a list comprehension, you get back a Python list; ``stripped_list`` is " @@ -459,6 +525,19 @@ msgid "" "expressions have the form::" msgstr "" +#: howto/functional.rst:368 +msgid "" +"( expression for expr in sequence1\n" +" if condition1\n" +" for expr2 in sequence2\n" +" if condition2\n" +" for expr3 in sequence3\n" +" ...\n" +" if condition3\n" +" for exprN in sequenceN\n" +" if conditionN )" +msgstr "" + #: howto/functional.rst:378 msgid "" "Again, for a list comprehension only the outside brackets are different " @@ -480,6 +559,10 @@ msgid "" "iterator that will be immediately passed to a function you can write::" msgstr "" +#: howto/functional.rst:389 +msgid "obj_total = sum(obj.count for obj in list_all_objects())" +msgstr "" + #: howto/functional.rst:391 msgid "" "The ``for...in`` clauses contain the sequences to be iterated over. The " @@ -496,6 +579,23 @@ msgid "" "equivalent to the following Python code::" msgstr "" +#: howto/functional.rst:400 +msgid "" +"for expr1 in sequence1:\n" +" if not (condition1):\n" +" continue # Skip this element\n" +" for expr2 in sequence2:\n" +" if not (condition2):\n" +" continue # Skip this element\n" +" ...\n" +" for exprN in sequenceN:\n" +" if not (conditionN):\n" +" continue # Skip this element\n" +"\n" +" # Output the value of\n" +" # the expression." +msgstr "" + #: howto/functional.rst:414 msgid "" "This means that when there are multiple ``for...in`` clauses but no ``if`` " @@ -511,6 +611,14 @@ msgid "" "comprehension below is a syntax error, while the second one is correct::" msgstr "" +#: howto/functional.rst:430 +msgid "" +"# Syntax error\n" +"[x, y for x in seq1 for y in seq2]\n" +"# Correct\n" +"[(x, y) for x in seq1 for y in seq2]" +msgstr "" + #: howto/functional.rst:437 msgid "Generators" msgstr "" @@ -594,6 +702,20 @@ msgid "" "generators recursively. ::" msgstr "" +#: howto/functional.rst:509 +msgid "" +"# A recursive generator that generates Tree leaves in in-order.\n" +"def inorder(t):\n" +" if t:\n" +" for x in inorder(t.left):\n" +" yield x\n" +"\n" +" yield t.label\n" +"\n" +" for x in inorder(t.right):\n" +" yield x" +msgstr "" + #: howto/functional.rst:520 msgid "" "Two other examples in ``test_generators.py`` produce solutions for the N-" @@ -624,6 +746,10 @@ msgid "" "variable or otherwise operated on::" msgstr "" +#: howto/functional.rst:541 +msgid "val = (yield i)" +msgstr "" + #: howto/functional.rst:543 msgid "" "I recommend that you **always** put parentheses around a ``yield`` " @@ -655,6 +781,19 @@ msgid "" "of the internal counter." msgstr "" +#: howto/functional.rst:562 +msgid "" +"def counter(maximum):\n" +" i = 0\n" +" while i < maximum:\n" +" val = (yield i)\n" +" # If value provided, change counter\n" +" if val is not None:\n" +" i = val\n" +" else:\n" +" i += 1" +msgstr "" + #: howto/functional.rst:574 msgid "And here's an example of changing the counter:" msgstr "" @@ -762,12 +901,29 @@ msgid "" "element. ::" msgstr "" +#: howto/functional.rst:667 +msgid "" +">>> for item in enumerate(['subject', 'verb', 'object']):\n" +"... print(item)\n" +"(0, 'subject')\n" +"(1, 'verb')\n" +"(2, 'object')" +msgstr "" + #: howto/functional.rst:673 msgid "" ":func:`enumerate` is often used when looping through a list and recording " "the indexes at which certain conditions are met::" msgstr "" +#: howto/functional.rst:676 +msgid "" +"f = open('data.txt', 'r')\n" +"for i, line in enumerate(f):\n" +" if line.strip() == '':\n" +" print('Blank line at line #%i' % i)" +msgstr "" + #: howto/functional.rst:681 msgid "" ":func:`sorted(iterable, key=None, reverse=False) ` collects all the " @@ -776,6 +932,19 @@ msgid "" "constructed list's :meth:`~list.sort` method. ::" msgstr "" +#: howto/functional.rst:686 +msgid "" +">>> import random\n" +">>> # Generate 8 random numbers between [0, 10000)\n" +">>> rand_list = random.sample(range(10000), 8)\n" +">>> rand_list \n" +"[769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]\n" +">>> sorted(rand_list) \n" +"[769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]\n" +">>> sorted(rand_list, reverse=True) \n" +"[9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]" +msgstr "" + #: howto/functional.rst:696 msgid "" "(For a more detailed discussion of sorting, see the :ref:`sortinghowto`.)" @@ -795,6 +964,12 @@ msgid "" "and returns them in a tuple::" msgstr "" +#: howto/functional.rst:721 +msgid "" +"zip(['a', 'b', 'c'], (1, 2, 3)) =>\n" +" ('a', 1), ('b', 2), ('c', 3)" +msgstr "" + #: howto/functional.rst:724 msgid "" "It doesn't construct an in-memory list and exhaust all the input iterators " @@ -810,6 +985,12 @@ msgid "" "will be the same length as the shortest iterable. ::" msgstr "" +#: howto/functional.rst:733 +msgid "" +"zip(['a', 'b'], (1, 2, 3)) =>\n" +" ('a', 1), ('b', 2)" +msgstr "" + #: howto/functional.rst:736 msgid "" "You should avoid doing this, though, because an element may be taken from " @@ -860,6 +1041,16 @@ msgid "" "defaults to 1::" msgstr "" +#: howto/functional.rst:762 +msgid "" +"itertools.count() =>\n" +" 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...\n" +"itertools.count(10) =>\n" +" 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...\n" +"itertools.count(10, 5) =>\n" +" 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, ..." +msgstr "" + #: howto/functional.rst:769 msgid "" ":func:`itertools.cycle(iter) ` saves a copy of the contents " @@ -868,6 +1059,12 @@ msgid "" "infinitely. ::" msgstr "" +#: howto/functional.rst:773 +msgid "" +"itertools.cycle([1, 2, 3, 4, 5]) =>\n" +" 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ..." +msgstr "" + #: howto/functional.rst:776 msgid "" ":func:`itertools.repeat(elem, [n]) ` returns the provided " @@ -875,6 +1072,14 @@ msgid "" "provided. ::" msgstr "" +#: howto/functional.rst:779 +msgid "" +"itertools.repeat('abc') =>\n" +" abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...\n" +"itertools.repeat('abc', 5) =>\n" +" abc, abc, abc, abc, abc" +msgstr "" + #: howto/functional.rst:784 msgid "" ":func:`itertools.chain(iterA, iterB, ...) ` takes an " @@ -883,6 +1088,12 @@ msgid "" "the iterables have been exhausted. ::" msgstr "" +#: howto/functional.rst:789 +msgid "" +"itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>\n" +" a, b, c, 1, 2, 3" +msgstr "" + #: howto/functional.rst:792 msgid "" ":func:`itertools.islice(iter, [start], stop, [step]) ` " @@ -894,6 +1105,16 @@ msgid "" "*step*. ::" msgstr "" +#: howto/functional.rst:799 +msgid "" +"itertools.islice(range(10), 8) =>\n" +" 0, 1, 2, 3, 4, 5, 6, 7\n" +"itertools.islice(range(10), 2, 8) =>\n" +" 2, 3, 4, 5, 6, 7\n" +"itertools.islice(range(10), 2, 8, 2) =>\n" +" 2, 4, 6" +msgstr "" + #: howto/functional.rst:806 msgid "" ":func:`itertools.tee(iter, [n]) ` replicates an iterator; it " @@ -904,6 +1125,18 @@ msgid "" "and one of the new iterators is consumed more than the others. ::" msgstr "" +#: howto/functional.rst:814 +msgid "" +"itertools.tee( itertools.count() ) =>\n" +" iterA, iterB\n" +"\n" +"where iterA ->\n" +" 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...\n" +"\n" +"and iterB ->\n" +" 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ..." +msgstr "" + #: howto/functional.rst:825 msgid "Calling functions on elements" msgstr "" @@ -924,6 +1157,15 @@ msgid "" "as the arguments::" msgstr "" +#: howto/functional.rst:837 +msgid "" +"itertools.starmap(os.path.join,\n" +" [('/bin', 'python'), ('/usr', 'bin', 'java'),\n" +" ('/usr', 'bin', 'perl'), ('/usr', 'bin', 'ruby')])\n" +"=>\n" +" /bin/python, /usr/bin/java, /usr/bin/perl, /usr/bin/ruby" +msgstr "" + #: howto/functional.rst:845 msgid "Selecting elements" msgstr "" @@ -941,6 +1183,12 @@ msgid "" "predicate returns false::" msgstr "" +#: howto/functional.rst:854 +msgid "" +"itertools.filterfalse(is_even, itertools.count()) =>\n" +" 1, 3, 5, 7, 9, 11, 13, 15, ..." +msgstr "" + #: howto/functional.rst:857 msgid "" ":func:`itertools.takewhile(predicate, iter) ` returns " @@ -948,6 +1196,18 @@ msgid "" "returns false, the iterator will signal the end of its results. ::" msgstr "" +#: howto/functional.rst:861 +msgid "" +"def less_than_10(x):\n" +" return x < 10\n" +"\n" +"itertools.takewhile(less_than_10, itertools.count()) =>\n" +" 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n" +"\n" +"itertools.takewhile(is_even, itertools.count()) =>\n" +" 0" +msgstr "" + #: howto/functional.rst:870 msgid "" ":func:`itertools.dropwhile(predicate, iter) ` discards " @@ -955,6 +1215,15 @@ msgid "" "iterable's results. ::" msgstr "" +#: howto/functional.rst:874 +msgid "" +"itertools.dropwhile(less_than_10, itertools.count()) =>\n" +" 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...\n" +"\n" +"itertools.dropwhile(is_even, itertools.count()) =>\n" +" 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..." +msgstr "" + #: howto/functional.rst:880 msgid "" ":func:`itertools.compress(data, selectors) ` takes two " @@ -963,6 +1232,12 @@ msgid "" "is exhausted::" msgstr "" +#: howto/functional.rst:884 +msgid "" +"itertools.compress([1, 2, 3, 4, 5], [True, True, False, False, True]) =>\n" +" 1, 2, 5" +msgstr "" + #: howto/functional.rst:889 msgid "Combinatoric functions" msgstr "" @@ -974,6 +1249,20 @@ msgid "" "elements contained in *iterable*. ::" msgstr "" +#: howto/functional.rst:895 +msgid "" +"itertools.combinations([1, 2, 3, 4, 5], 2) =>\n" +" (1, 2), (1, 3), (1, 4), (1, 5),\n" +" (2, 3), (2, 4), (2, 5),\n" +" (3, 4), (3, 5),\n" +" (4, 5)\n" +"\n" +"itertools.combinations([1, 2, 3, 4, 5], 3) =>\n" +" (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5),\n" +" (2, 3, 4), (2, 3, 5), (2, 4, 5),\n" +" (3, 4, 5)" +msgstr "" + #: howto/functional.rst:906 msgid "" "The elements within each tuple remain in the same order as *iterable* " @@ -983,6 +1272,21 @@ msgid "" "constraint on the order, returning all possible arrangements of length *r*::" msgstr "" +#: howto/functional.rst:913 +msgid "" +"itertools.permutations([1, 2, 3, 4, 5], 2) =>\n" +" (1, 2), (1, 3), (1, 4), (1, 5),\n" +" (2, 1), (2, 3), (2, 4), (2, 5),\n" +" (3, 1), (3, 2), (3, 4), (3, 5),\n" +" (4, 1), (4, 2), (4, 3), (4, 5),\n" +" (5, 1), (5, 2), (5, 3), (5, 4)\n" +"\n" +"itertools.permutations([1, 2, 3, 4, 5]) =>\n" +" (1, 2, 3, 4, 5), (1, 2, 3, 5, 4), (1, 2, 4, 3, 5),\n" +" ...\n" +" (5, 4, 3, 2, 1)" +msgstr "" + #: howto/functional.rst:925 msgid "" "If you don't supply a value for *r* the length of the iterable is used, " @@ -995,6 +1299,13 @@ msgid "" "position and don't require that the contents of *iterable* are unique::" msgstr "" +#: howto/functional.rst:931 +msgid "" +"itertools.permutations('aba', 3) =>\n" +" ('a', 'b', 'a'), ('a', 'a', 'b'), ('b', 'a', 'a'),\n" +" ('b', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'a')" +msgstr "" + #: howto/functional.rst:935 msgid "" "The identical tuple ``('a', 'a', 'b')`` occurs twice, but the two 'a' " @@ -1010,6 +1321,16 @@ msgid "" "the second element is selected. ::" msgstr "" +#: howto/functional.rst:944 +msgid "" +"itertools.combinations_with_replacement([1, 2, 3, 4, 5], 2) =>\n" +" (1, 1), (1, 2), (1, 3), (1, 4), (1, 5),\n" +" (2, 2), (2, 3), (2, 4), (2, 5),\n" +" (3, 3), (3, 4), (3, 5),\n" +" (4, 4), (4, 5),\n" +" (5, 5)" +msgstr "" + #: howto/functional.rst:953 msgid "Grouping elements" msgstr "" @@ -1030,6 +1351,31 @@ msgid "" "tuples containing a key value and an iterator for the elements with that key." msgstr "" +#: howto/functional.rst:966 +msgid "" +"city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'),\n" +" ('Anchorage', 'AK'), ('Nome', 'AK'),\n" +" ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'),\n" +" ...\n" +" ]\n" +"\n" +"def get_state(city_state):\n" +" return city_state[1]\n" +"\n" +"itertools.groupby(city_list, get_state) =>\n" +" ('AL', iterator-1),\n" +" ('AK', iterator-2),\n" +" ('AZ', iterator-3), ...\n" +"\n" +"where\n" +"iterator-1 =>\n" +" ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')\n" +"iterator-2 =>\n" +" ('Anchorage', 'AK'), ('Nome', 'AK')\n" +"iterator-3 =>\n" +" ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')" +msgstr "" + #: howto/functional.rst:988 msgid "" ":func:`~itertools.groupby` assumes that the underlying iterable's contents " @@ -1072,6 +1418,19 @@ msgstr "" msgid "Here's a small but realistic example::" msgstr "" +#: howto/functional.rst:1015 +msgid "" +"import functools\n" +"\n" +"def log(message, subsystem):\n" +" \"\"\"Write the contents of 'message' to the specified subsystem.\"\"\"\n" +" print('%s: %s' % (subsystem, message))\n" +" ...\n" +"\n" +"server_log = functools.partial(log, subsystem='server')\n" +"server_log('Unable to open socket')" +msgstr "" + #: howto/functional.rst:1025 msgid "" ":func:`functools.reduce(func, iter, [initial_value]) ` " @@ -1087,6 +1446,21 @@ msgid "" "``func(initial_value, A)`` is the first calculation. ::" msgstr "" +#: howto/functional.rst:1037 +msgid "" +">>> import operator, functools\n" +">>> functools.reduce(operator.concat, ['A', 'BB', 'C'])\n" +"'ABBC'\n" +">>> functools.reduce(operator.concat, [])\n" +"Traceback (most recent call last):\n" +" ...\n" +"TypeError: reduce() of empty sequence with no initial value\n" +">>> functools.reduce(operator.mul, [1, 2, 3], 1)\n" +"6\n" +">>> functools.reduce(operator.mul, [], 1)\n" +"1" +msgstr "" + #: howto/functional.rst:1049 msgid "" "If you use :func:`operator.add` with :func:`functools.reduce`, you'll add up " @@ -1100,6 +1474,18 @@ msgid "" "write the obvious :keyword:`for` loop::" msgstr "" +#: howto/functional.rst:1064 +msgid "" +"import functools\n" +"# Instead of:\n" +"product = functools.reduce(operator.mul, [1, 2, 3], 1)\n" +"\n" +"# You can write:\n" +"product = 1\n" +"for i in [1, 2, 3]:\n" +" product *= i" +msgstr "" + #: howto/functional.rst:1073 msgid "" "A related function is :func:`itertools.accumulate(iterable, func=operator." @@ -1108,6 +1494,15 @@ msgid "" "iterator that also yields each partial result::" msgstr "" +#: howto/functional.rst:1078 +msgid "" +"itertools.accumulate([1, 2, 3, 4, 5]) =>\n" +" 1, 3, 6, 10, 15\n" +"\n" +"itertools.accumulate([1, 2, 3, 4, 5], operator.mul) =>\n" +" 1, 2, 6, 24, 120" +msgstr "" + #: howto/functional.rst:1086 msgid "The operator module" msgstr "" @@ -1167,6 +1562,12 @@ msgid "" "need to define a new function at all::" msgstr "" +#: howto/functional.rst:1113 +msgid "" +"stripped_lines = [line.strip() for line in lines]\n" +"existing_files = filter(os.path.exists, file_list)" +msgstr "" + #: howto/functional.rst:1116 msgid "" "If the function you need doesn't exist, you need to write it. One way to " @@ -1176,12 +1577,28 @@ msgid "" "expression::" msgstr "" +#: howto/functional.rst:1121 +msgid "" +"adder = lambda x, y: x+y\n" +"\n" +"print_assign = lambda name, value: name + '=' + str(value)" +msgstr "" + #: howto/functional.rst:1125 msgid "" "An alternative is to just use the ``def`` statement and define a function in " "the usual way::" msgstr "" +#: howto/functional.rst:1128 +msgid "" +"def adder(x, y):\n" +" return x + y\n" +"\n" +"def print_assign(name, value):\n" +" return name + '=' + str(value)" +msgstr "" + #: howto/functional.rst:1134 msgid "" "Which alternative is preferable? That's a style question; my usual course " @@ -1198,6 +1615,12 @@ msgid "" "that's hard to read. Quick, what's the following code doing? ::" msgstr "" +#: howto/functional.rst:1144 +msgid "" +"import functools\n" +"total = functools.reduce(lambda a, b: (0, a[1] + b[1]), items)[1]" +msgstr "" + #: howto/functional.rst:1147 msgid "" "You can figure it out, but it takes time to disentangle the expression to " @@ -1205,14 +1628,34 @@ msgid "" "things a little bit better::" msgstr "" +#: howto/functional.rst:1151 +msgid "" +"import functools\n" +"def combine(a, b):\n" +" return 0, a[1] + b[1]\n" +"\n" +"total = functools.reduce(combine, items)[1]" +msgstr "" + #: howto/functional.rst:1157 msgid "But it would be best of all if I had simply used a ``for`` loop::" msgstr "" +#: howto/functional.rst:1159 +msgid "" +"total = 0\n" +"for a, b in items:\n" +" total += b" +msgstr "" + #: howto/functional.rst:1163 msgid "Or the :func:`sum` built-in and a generator expression::" msgstr "" +#: howto/functional.rst:1165 +msgid "total = sum(b for a, b in items)" +msgstr "" + #: howto/functional.rst:1167 msgid "" "Many uses of :func:`functools.reduce` are clearer when written as ``for`` " diff --git a/howto/gdb_helpers.po b/howto/gdb_helpers.po index 00cb49b09..1c89be337 100644 --- a/howto/gdb_helpers.po +++ b/howto/gdb_helpers.po @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-03-01 20:27+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: TURKISH \n" @@ -114,6 +114,10 @@ msgid "" "configuration file (``~/.gdbinit`` or ``~/.config/gdb/gdbinit``)::" msgstr "" +#: howto/gdb_helpers.rst:68 +msgid "add-auto-load-safe-path /path/to/cpython" +msgstr "" + #: howto/gdb_helpers.rst:70 msgid "You can also add multiple paths, separated by ``:``." msgstr "" @@ -132,10 +136,20 @@ msgstr "" msgid "Fedora:" msgstr "" +#: howto/gdb_helpers.rst:82 +msgid "" +"sudo dnf install gdb\n" +"sudo dnf debuginfo-install python3" +msgstr "" + #: howto/gdb_helpers.rst:87 msgid "Ubuntu:" msgstr "" +#: howto/gdb_helpers.rst:89 +msgid "sudo apt install gdb python3-dbg" +msgstr "" + #: howto/gdb_helpers.rst:93 msgid "" "On several recent Linux systems, GDB can download debugging symbols " @@ -190,6 +204,37 @@ msgid "" "enabled::" msgstr "" +#: howto/gdb_helpers.rst:126 +msgid "" +"#0 0x000000000041a6b1 in PyObject_Malloc (nbytes=Cannot access memory at " +"address 0x7fffff7fefe8\n" +") at Objects/obmalloc.c:748\n" +"#1 0x000000000041b7c0 in _PyObject_DebugMallocApi (id=111 'o', nbytes=24) " +"at Objects/obmalloc.c:1445\n" +"#2 0x000000000041b717 in _PyObject_DebugMalloc (nbytes=24) at Objects/" +"obmalloc.c:1412\n" +"#3 0x000000000044060a in _PyUnicode_New (length=11) at Objects/" +"unicodeobject.c:346\n" +"#4 0x00000000004466aa in PyUnicodeUCS2_DecodeUTF8Stateful (s=0x5c2b8d " +"\"__lltrace__\", size=11, errors=0x0, consumed=\n" +" 0x0) at Objects/unicodeobject.c:2531\n" +"#5 0x0000000000446647 in PyUnicodeUCS2_DecodeUTF8 (s=0x5c2b8d " +"\"__lltrace__\", size=11, errors=0x0)\n" +" at Objects/unicodeobject.c:2495\n" +"#6 0x0000000000440d1b in PyUnicodeUCS2_FromStringAndSize (u=0x5c2b8d " +"\"__lltrace__\", size=11)\n" +" at Objects/unicodeobject.c:551\n" +"#7 0x0000000000440d94 in PyUnicodeUCS2_FromString (u=0x5c2b8d " +"\"__lltrace__\") at Objects/unicodeobject.c:569\n" +"#8 0x0000000000584abd in PyDict_GetItemString (v=\n" +" {'Yuck': , '__builtins__': , '__file__': 'Lib/test/crashers/nasty_eq_vs_dict.py', " +"'__package__': None, 'y': , 'dict': {0: 0, 1: " +"1, 2: 2, 3: 3}, '__cached__': None, '__name__': '__main__', 'z': , '__doc__': None}, key=\n" +" 0x5c2b8d \"__lltrace__\") at Objects/dictobject.c:2171" +msgstr "" + #: howto/gdb_helpers.rst:142 msgid "" "Notice how the dictionary argument to ``PyDict_GetItemString`` is displayed " @@ -204,6 +249,28 @@ msgid "" "example::" msgstr "" +#: howto/gdb_helpers.rst:149 +msgid "" +"(gdb) p globals\n" +"$1 = {'__builtins__': , '__name__':\n" +"'__main__', 'ctypes': , '__doc__': None,\n" +"'__package__': None}\n" +"\n" +"(gdb) p *(PyDictObject*)globals\n" +"$2 = {ob_refcnt = 3, ob_type = 0x3dbdf85820, ma_fill = 5, ma_used = 5,\n" +"ma_mask = 7, ma_table = 0x63d0f8, ma_lookup = 0x3dbdc7ea70\n" +", ma_smalltable = {{me_hash = 7065186196740147912,\n" +"me_key = '__builtins__', me_value = },\n" +"{me_hash = -368181376027291943, me_key = '__name__',\n" +"me_value ='__main__'}, {me_hash = 0, me_key = 0x0, me_value = 0x0},\n" +"{me_hash = 0, me_key = 0x0, me_value = 0x0},\n" +"{me_hash = -9177857982131165996, me_key = 'ctypes',\n" +"me_value = },\n" +"{me_hash = -8518757509529533123, me_key = '__doc__', me_value = None},\n" +"{me_hash = 0, me_key = 0x0, me_value = 0x0}, {\n" +" me_hash = 6614918939584953775, me_key = '__package__', me_value = None}}}" +msgstr "" + #: howto/gdb_helpers.rst:168 msgid "" "Note that the pretty-printers do not actually call ``repr()``. For basic " @@ -219,6 +286,15 @@ msgid "" "level integer::" msgstr "" +#: howto/gdb_helpers.rst:177 +msgid "" +"(gdb) p some_machine_integer\n" +"$3 = 42\n" +"\n" +"(gdb) p some_python_integer\n" +"$4 = 42" +msgstr "" + #: howto/gdb_helpers.rst:183 msgid "" "The internal structure can be revealed with a cast to :c:expr:`PyLongObject " @@ -237,6 +313,12 @@ msgid "" "a lot like gdb's built-in printer for ``char *``::" msgstr "" +#: howto/gdb_helpers.rst:192 +msgid "" +"(gdb) p ptr_to_python_str\n" +"$6 = '__builtins__'" +msgstr "" + #: howto/gdb_helpers.rst:195 msgid "" "The pretty-printer for ``str`` instances defaults to using single-quotes (as " @@ -244,12 +326,25 @@ msgid "" "*`` values uses double-quotes and contains a hexadecimal address::" msgstr "" +#: howto/gdb_helpers.rst:199 +msgid "" +"(gdb) p ptr_to_char_star\n" +"$7 = 0x6d72c0 \"hello world\"" +msgstr "" + #: howto/gdb_helpers.rst:202 msgid "" "Again, the implementation details can be revealed with a cast to :c:expr:" "`PyUnicodeObject *`::" msgstr "" +#: howto/gdb_helpers.rst:205 +msgid "" +"(gdb) p *(PyUnicodeObject*)$6\n" +"$8 = {ob_base = {ob_refcnt = 33, ob_type = 0x3dad3a95a0}, length = 12,\n" +"str = 0x7ffff2128500, hash = 7065186196740147912, state = 1, defenc = 0x0}" +msgstr "" + #: howto/gdb_helpers.rst:210 msgid "``py-list``" msgstr "" @@ -261,6 +356,22 @@ msgid "" "marked with a \">\"::" msgstr "" +#: howto/gdb_helpers.rst:216 +msgid "" +"(gdb) py-list\n" +" 901 if options.profile:\n" +" 902 options.profile = False\n" +" 903 profile_me()\n" +" 904 return\n" +" 905\n" +">906 u = UI()\n" +" 907 if not u.quit:\n" +" 908 try:\n" +" 909 gtk.main()\n" +" 910 except KeyboardInterrupt:\n" +" 911 # properly quit on a keyboard interrupt..." +msgstr "" + #: howto/gdb_helpers.rst:229 msgid "" "Use ``py-list START`` to list at a different line number within the Python " @@ -296,6 +407,21 @@ msgstr "" msgid "For example::" msgstr "" +#: howto/gdb_helpers.rst:250 +msgid "" +"(gdb) py-up\n" +"#37 Frame 0x9420b04, for file /usr/lib/python2.6/site-packages/\n" +"gnome_sudoku/main.py, line 906, in start_game ()\n" +" u = UI()\n" +"(gdb) py-up\n" +"#40 Frame 0x948e82c, for file /usr/lib/python2.6/site-packages/\n" +"gnome_sudoku/gnome_sudoku.py, line 22, in start_game(main=)\n" +" main.start_game()\n" +"(gdb) py-up\n" +"Unable to find an older python frame" +msgstr "" + #: howto/gdb_helpers.rst:261 msgid "so we're at the top of the Python stack." msgstr "" @@ -311,6 +437,47 @@ msgstr "" msgid "Going back down::" msgstr "" +#: howto/gdb_helpers.rst:269 +msgid "" +"(gdb) py-down\n" +"#37 Frame 0x9420b04, for file /usr/lib/python2.6/site-packages/gnome_sudoku/" +"main.py, line 906, in start_game ()\n" +" u = UI()\n" +"(gdb) py-down\n" +"#34 (unable to read python frame information)\n" +"(gdb) py-down\n" +"#23 (unable to read python frame information)\n" +"(gdb) py-down\n" +"#19 (unable to read python frame information)\n" +"(gdb) py-down\n" +"#14 Frame 0x99262ac, for file /usr/lib/python2.6/site-packages/gnome_sudoku/" +"game_selector.py, line 201, in run_swallowed_dialog " +"(self=, puzzle=None, saved_games=[{'gsd.auto_fills': 0, 'tracking': {}, " +"'trackers': {}, 'notes': [], 'saved_at': 1270084485, 'game': '7 8 0 0 0 0 0 " +"5 6 0 0 9 0 8 0 1 0 0 0 4 6 0 0 0 0 7 0 6 5 0 0 0 4 7 9 2 0 0 0 9 0 1 0 0 0 " +"3 9 7 6 0 0 0 1 8 0 6 0 0 0 0 2 8 0 0 0 5 0 4 0 6 0 0 2 1 0 0 0 0 0 4 5\\n7 " +"8 0 0 0 0 0 5 6 0 0 9 0 8 0 1 0 0 0 4 6 0 0 0 0 7 0 6 5 1 8 3 4 7 9 2 0 0 0 " +"9 0 1 0 0 0 3 9 7 6 0 0 0 1 8 0 6 0 0 0 0 2 8 0 0 0 5 0 4 0 6 0 0 2 1 0 0 0 " +"0 0 4 5', 'gsd.impossible_hints': 0, 'timer.__absolute_start_time__': , 'gsd.hints': 0, 'timer.active_time': , 'timer.total_time': }], dialog=, saved_game_model=, sudoku_maker=, main_page=0) " +"at remote 0x98fa6e4>, d=)\n" +" gtk.main()\n" +"(gdb) py-down\n" +"#8 (unable to read python frame information)\n" +"(gdb) py-down\n" +"Unable to find a newer python frame" +msgstr "" + #: howto/gdb_helpers.rst:289 msgid "and we're at the bottom of the Python stack." msgstr "" @@ -322,6 +489,33 @@ msgid "" "move multiple Python frames at once. For example::" msgstr "" +#: howto/gdb_helpers.rst:295 +msgid "" +"(gdb) py-up\n" +"#6 Frame 0x7ffff7fb62b0, for file /tmp/rec.py, line 5, in recursive_function " +"(n=0)\n" +" time.sleep(5)\n" +"#6 Frame 0x7ffff7fb6240, for file /tmp/rec.py, line 7, in recursive_function " +"(n=1)\n" +" recursive_function(n-1)\n" +"#6 Frame 0x7ffff7fb61d0, for file /tmp/rec.py, line 7, in recursive_function " +"(n=2)\n" +" recursive_function(n-1)\n" +"#6 Frame 0x7ffff7fb6160, for file /tmp/rec.py, line 7, in recursive_function " +"(n=3)\n" +" recursive_function(n-1)\n" +"#6 Frame 0x7ffff7fb60f0, for file /tmp/rec.py, line 7, in recursive_function " +"(n=4)\n" +" recursive_function(n-1)\n" +"#6 Frame 0x7ffff7fb6080, for file /tmp/rec.py, line 7, in recursive_function " +"(n=5)\n" +" recursive_function(n-1)\n" +"#6 Frame 0x7ffff7fb6020, for file /tmp/rec.py, line 9, in ()\n" +" recursive_function(5)\n" +"(gdb) py-up\n" +"Unable to find an older python frame" +msgstr "" + #: howto/gdb_helpers.rst:315 msgid "``py-bt``" msgstr "" @@ -332,6 +526,43 @@ msgid "" "current thread." msgstr "" +#: howto/gdb_helpers.rst:322 +msgid "" +"(gdb) py-bt\n" +"#8 (unable to read python frame information)\n" +"#11 Frame 0x9aead74, for file /usr/lib/python2.6/site-packages/gnome_sudoku/" +"dialog_swallower.py, line 48, in run_dialog " +"(self=, main_page=0) " +"at remote 0x98fa6e4>, d=)\n" +" gtk.main()\n" +"#14 Frame 0x99262ac, for file /usr/lib/python2.6/site-packages/gnome_sudoku/" +"game_selector.py, line 201, in run_swallowed_dialog " +"(self=, puzzle=None, saved_games=[{'gsd.auto_fills': 0, 'tracking': {}, " +"'trackers': {}, 'notes': [], 'saved_at': 1270084485, 'game': '7 8 0 0 0 0 0 " +"5 6 0 0 9 0 8 0 1 0 0 0 4 6 0 0 0 0 7 0 6 5 0 0 0 4 7 9 2 0 0 0 9 0 1 0 0 0 " +"3 9 7 6 0 0 0 1 8 0 6 0 0 0 0 2 8 0 0 0 5 0 4 0 6 0 0 2 1 0 0 0 0 0 4 5\\n7 " +"8 0 0 0 0 0 5 6 0 0 9 0 8 0 1 0 0 0 4 6 0 0 0 0 7 0 6 5 1 8 3 4 7 9 2 0 0 0 " +"9 0 1 0 0 0 3 9 7 6 0 0 0 1 8 0 6 0 0 0 0 2 8 0 0 0 5 0 4 0 6 0 0 2 1 0 0 0 " +"0 0 4 5', 'gsd.impossible_hints': 0, 'timer.__absolute_start_time__': , 'gsd.hints': 0, 'timer.active_time': , 'timer.total_time': }], dialog=, saved_game_model=, sudoku_maker=)\n" +" main.start_game()" +msgstr "" + #: howto/gdb_helpers.rst:336 msgid "" "The frame numbers correspond to those displayed by GDB's standard " @@ -349,6 +580,19 @@ msgid "" "builtins::" msgstr "" +#: howto/gdb_helpers.rst:346 +msgid "" +"(gdb) py-print self\n" +"local 'self' = ,\n" +"main_page=0) at remote 0x98fa6e4>\n" +"(gdb) py-print __name__\n" +"global '__name__' = 'gnome_sudoku.dialog_swallower'\n" +"(gdb) py-print len\n" +"builtin 'len' = \n" +"(gdb) py-print scarlet_pimpernel\n" +"'scarlet_pimpernel' not found" +msgstr "" + #: howto/gdb_helpers.rst:356 msgid "" "If the current C frame corresponds to multiple Python frames, ``py-print`` " @@ -365,12 +609,38 @@ msgid "" "Python frame in the selected thread, and prints their representations::" msgstr "" +#: howto/gdb_helpers.rst:365 +msgid "" +"(gdb) py-locals\n" +"self = ,\n" +"main_page=0) at remote 0x98fa6e4>\n" +"d = " +msgstr "" + #: howto/gdb_helpers.rst:370 msgid "" "If the current C frame corresponds to multiple Python frames, locals from " "all of them will be shown::" msgstr "" +#: howto/gdb_helpers.rst:373 +msgid "" +"(gdb) py-locals\n" +"Locals for recursive_function\n" +"n = 0\n" +"Locals for recursive_function\n" +"n = 1\n" +"Locals for recursive_function\n" +"n = 2\n" +"Locals for recursive_function\n" +"n = 3\n" +"Locals for recursive_function\n" +"n = 4\n" +"Locals for recursive_function\n" +"n = 5\n" +"Locals for " +msgstr "" + #: howto/gdb_helpers.rst:390 msgid "Use with GDB commands" msgstr "" @@ -382,15 +652,131 @@ msgid "" "a specific frame within the selected thread, like this::" msgstr "" +#: howto/gdb_helpers.rst:396 +msgid "" +"(gdb) py-bt\n" +"(output snipped)\n" +"#68 Frame 0xaa4560, for file Lib/test/regrtest.py, line 1548, in " +"()\n" +" main()\n" +"(gdb) frame 68\n" +"#68 0x00000000004cd1e6 in PyEval_EvalFrameEx (f=Frame 0xaa4560, for file Lib/" +"test/regrtest.py, line 1548, in (), throwflag=0) at Python/ceval." +"c:2665\n" +"2665 x = call_function(&sp, oparg);\n" +"(gdb) py-list\n" +"1543 # Run the tests in a context manager that temporary changes the " +"CWD to a\n" +"1544 # temporary and writable directory. If it's not possible to " +"create or\n" +"1545 # change the CWD, the original CWD will be used. The original " +"CWD is\n" +"1546 # available from test_support.SAVEDCWD.\n" +"1547 with test_support.temp_cwd(TESTCWD, quiet=True):\n" +">1548 main()" +msgstr "" + #: howto/gdb_helpers.rst:411 msgid "" "The ``info threads`` command will give you a list of the threads within the " "process, and you can use the ``thread`` command to select a different one::" msgstr "" +#: howto/gdb_helpers.rst:414 +msgid "" +"(gdb) info threads\n" +" 105 Thread 0x7fffefa18710 (LWP 10260) sem_wait () at ../nptl/sysdeps/unix/" +"sysv/linux/x86_64/sem_wait.S:86\n" +" 104 Thread 0x7fffdf5fe710 (LWP 10259) sem_wait () at ../nptl/sysdeps/unix/" +"sysv/linux/x86_64/sem_wait.S:86\n" +"* 1 Thread 0x7ffff7fe2700 (LWP 10145) 0x00000038e46d73e3 in select () at ../" +"sysdeps/unix/syscall-template.S:82" +msgstr "" + #: howto/gdb_helpers.rst:419 msgid "" "You can use ``thread apply all COMMAND`` or (``t a a COMMAND`` for short) to " "run a command on all threads. With ``py-bt``, this lets you see what every " "thread is doing at the Python level::" msgstr "" + +#: howto/gdb_helpers.rst:423 +msgid "" +"(gdb) t a a py-bt\n" +"\n" +"Thread 105 (Thread 0x7fffefa18710 (LWP 10260)):\n" +"#5 Frame 0x7fffd00019d0, for file /home/david/coding/python-svn/Lib/" +"threading.py, line 155, in _acquire_restore " +"(self=<_RLock(_Verbose__verbose=False, _RLock__owner=140737354016512, " +"_RLock__block=, _RLock__count=1) at remote " +"0xd7ff40>, count_owner=(1, 140737213728528), count=1, " +"owner=140737213728528)\n" +" self.__block.acquire()\n" +"#8 Frame 0x7fffac001640, for file /home/david/coding/python-svn/Lib/" +"threading.py, line 269, in wait " +"(self=<_Condition(_Condition__lock=<_RLock(_Verbose__verbose=False, " +"_RLock__owner=140737354016512, _RLock__block=, _RLock__count=1) at remote 0xd7ff40>, acquire=, _is_owned=, " +"_release_save=, release=, _acquire_restore=, " +"_Verbose__verbose=False, _Condition__waiters=[]) at remote 0xd7fd10>, " +"timeout=None, waiter=, saved_state=(1, " +"140737213728528))\n" +" self._acquire_restore(saved_state)\n" +"#12 Frame 0x7fffb8001a10, for file /home/david/coding/python-svn/Lib/test/" +"lock_tests.py, line 348, in f ()\n" +" cond.wait()\n" +"#16 Frame 0x7fffb8001c40, for file /home/david/coding/python-svn/Lib/test/" +"lock_tests.py, line 37, in task (tid=140737213728528)\n" +" f()\n" +"\n" +"Thread 104 (Thread 0x7fffdf5fe710 (LWP 10259)):\n" +"#5 Frame 0x7fffe4001580, for file /home/david/coding/python-svn/Lib/" +"threading.py, line 155, in _acquire_restore " +"(self=<_RLock(_Verbose__verbose=False, _RLock__owner=140737354016512, " +"_RLock__block=, _RLock__count=1) at remote " +"0xd7ff40>, count_owner=(1, 140736940992272), count=1, " +"owner=140736940992272)\n" +" self.__block.acquire()\n" +"#8 Frame 0x7fffc8002090, for file /home/david/coding/python-svn/Lib/" +"threading.py, line 269, in wait " +"(self=<_Condition(_Condition__lock=<_RLock(_Verbose__verbose=False, " +"_RLock__owner=140737354016512, _RLock__block=, _RLock__count=1) at remote 0xd7ff40>, acquire=, _is_owned=, " +"_release_save=, release=, _acquire_restore=, " +"_Verbose__verbose=False, _Condition__waiters=[]) at remote 0xd7fd10>, " +"timeout=None, waiter=, saved_state=(1, " +"140736940992272))\n" +" self._acquire_restore(saved_state)\n" +"#12 Frame 0x7fffac001c90, for file /home/david/coding/python-svn/Lib/test/" +"lock_tests.py, line 348, in f ()\n" +" cond.wait()\n" +"#16 Frame 0x7fffac0011c0, for file /home/david/coding/python-svn/Lib/test/" +"lock_tests.py, line 37, in task (tid=140736940992272)\n" +" f()\n" +"\n" +"Thread 1 (Thread 0x7ffff7fe2700 (LWP 10145)):\n" +"#5 Frame 0xcb5380, for file /home/david/coding/python-svn/Lib/test/" +"lock_tests.py, line 16, in _wait ()\n" +" time.sleep(0.01)\n" +"#8 Frame 0x7fffd00024a0, for file /home/david/coding/python-svn/Lib/test/" +"lock_tests.py, line 378, in _check_notify " +"(self=, skipped=[], _mirrorOutput=False, testsRun=39, " +"buffer=False, _original_stderr=, " +"_stdout_buffer=, " +"_stderr_buffer=, " +"_moduleSetUpFailed=False, expectedFailures=[], errors=[], " +"_previousTestClass=, unexpectedSuccesses=[], " +"failures=[], shouldStop=False, failfast=False) at remote 0xc185a0>, " +"_threads=(0,), _cleanups=[], _type_equality_funcs={: , : " +", : " +", : " +", \n" @@ -81,16 +81,28 @@ msgstr "" msgid "On a Linux machine, this can be done via::" msgstr "" +#: howto/instrumentation.rst:42 +msgid "$ yum install systemtap-sdt-devel" +msgstr "" + #: howto/instrumentation.rst:44 msgid "or::" msgstr "" +#: howto/instrumentation.rst:46 +msgid "$ sudo apt-get install systemtap-sdt-dev" +msgstr "" + #: howto/instrumentation.rst:49 msgid "" "CPython must then be :option:`configured with the --with-dtrace option <--" "with-dtrace>`:" msgstr "" +#: howto/instrumentation.rst:52 +msgid "checking for --with-dtrace... yes" +msgstr "" + #: howto/instrumentation.rst:56 msgid "" "On macOS, you can list available DTrace probes by running a Python process " @@ -98,12 +110,40 @@ msgid "" "provider::" msgstr "" +#: howto/instrumentation.rst:60 +msgid "" +"$ python3.6 -q &\n" +"$ sudo dtrace -l -P python$! # or: dtrace -l -m python3.6\n" +"\n" +" ID PROVIDER MODULE FUNCTION NAME\n" +"29564 python18035 python3.6 _PyEval_EvalFrameDefault " +"function-entry\n" +"29565 python18035 python3.6 dtrace_function_entry " +"function-entry\n" +"29566 python18035 python3.6 _PyEval_EvalFrameDefault " +"function-return\n" +"29567 python18035 python3.6 dtrace_function_return " +"function-return\n" +"29568 python18035 python3.6 collect gc-" +"done\n" +"29569 python18035 python3.6 collect gc-" +"start\n" +"29570 python18035 python3.6 _PyEval_EvalFrameDefault line\n" +"29571 python18035 python3.6 maybe_dtrace_line line" +msgstr "" + #: howto/instrumentation.rst:73 msgid "" "On Linux, you can verify if the SystemTap static markers are present in the " "built binary by seeing if it contains a \".note.stapsdt\" section." msgstr "" +#: howto/instrumentation.rst:78 +msgid "" +"$ readelf -S ./python | grep .note.stapsdt\n" +"[30] .note.stapsdt NOTE 0000000000000000 00308d78" +msgstr "" + #: howto/instrumentation.rst:81 msgid "" "If you've built Python as a shared library (with the :option:`--enable-" @@ -111,10 +151,64 @@ msgid "" "library. For example::" msgstr "" +#: howto/instrumentation.rst:85 +msgid "" +"$ readelf -S libpython3.3dm.so.1.0 | grep .note.stapsdt\n" +"[29] .note.stapsdt NOTE 0000000000000000 00365b68" +msgstr "" + #: howto/instrumentation.rst:88 msgid "Sufficiently modern readelf can print the metadata::" msgstr "" +#: howto/instrumentation.rst:90 +msgid "" +"$ readelf -n ./python\n" +"\n" +"Displaying notes found at file offset 0x00000254 with length 0x00000020:\n" +" Owner Data size Description\n" +" GNU 0x00000010 NT_GNU_ABI_TAG (ABI version " +"tag)\n" +" OS: Linux, ABI: 2.6.32\n" +"\n" +"Displaying notes found at file offset 0x00000274 with length 0x00000024:\n" +" Owner Data size Description\n" +" GNU 0x00000014 NT_GNU_BUILD_ID (unique build " +"ID bitstring)\n" +" Build ID: df924a2b08a7e89f6e11251d4602022977af2670\n" +"\n" +"Displaying notes found at file offset 0x002d6c30 with length 0x00000144:\n" +" Owner Data size Description\n" +" stapsdt 0x00000031 NT_STAPSDT (SystemTap probe " +"descriptors)\n" +" Provider: python\n" +" Name: gc__start\n" +" Location: 0x00000000004371c3, Base: 0x0000000000630ce2, Semaphore: " +"0x00000000008d6bf6\n" +" Arguments: -4@%ebx\n" +" stapsdt 0x00000030 NT_STAPSDT (SystemTap probe " +"descriptors)\n" +" Provider: python\n" +" Name: gc__done\n" +" Location: 0x00000000004374e1, Base: 0x0000000000630ce2, Semaphore: " +"0x00000000008d6bf8\n" +" Arguments: -8@%rax\n" +" stapsdt 0x00000045 NT_STAPSDT (SystemTap probe " +"descriptors)\n" +" Provider: python\n" +" Name: function__entry\n" +" Location: 0x000000000053db6c, Base: 0x0000000000630ce2, Semaphore: " +"0x00000000008d6be8\n" +" Arguments: 8@%rbp 8@%r12 -4@%eax\n" +" stapsdt 0x00000046 NT_STAPSDT (SystemTap probe " +"descriptors)\n" +" Provider: python\n" +" Name: function__return\n" +" Location: 0x000000000053dba8, Base: 0x0000000000630ce2, Semaphore: " +"0x00000000008d6bea\n" +" Arguments: 8@%rbp 8@%r12 -4@%eax" +msgstr "" + #: howto/instrumentation.rst:125 msgid "" "The above metadata contains information for SystemTap describing how it can " @@ -134,14 +228,77 @@ msgid "" "are not going to be listed:" msgstr "" +#: howto/instrumentation.rst:138 +msgid "" +"self int indent;\n" +"\n" +"python$target:::function-entry\n" +"/copyinstr(arg1) == \"start\"/\n" +"{\n" +" self->trace = 1;\n" +"}\n" +"\n" +"python$target:::function-entry\n" +"/self->trace/\n" +"{\n" +" printf(\"%d\\t%*s:\", timestamp, 15, probename);\n" +" printf(\"%*s\", self->indent, \"\");\n" +" printf(\"%s:%s:%d\\n\", basename(copyinstr(arg0)), copyinstr(arg1), " +"arg2);\n" +" self->indent++;\n" +"}\n" +"\n" +"python$target:::function-return\n" +"/self->trace/\n" +"{\n" +" self->indent--;\n" +" printf(\"%d\\t%*s:\", timestamp, 15, probename);\n" +" printf(\"%*s\", self->indent, \"\");\n" +" printf(\"%s:%s:%d\\n\", basename(copyinstr(arg0)), copyinstr(arg1), " +"arg2);\n" +"}\n" +"\n" +"python$target:::function-return\n" +"/copyinstr(arg1) == \"start\"/\n" +"{\n" +" self->trace = 0;\n" +"}" +msgstr "" + #: howto/instrumentation.rst:230 msgid "It can be invoked like this::" msgstr "" +#: howto/instrumentation.rst:174 +msgid "$ sudo dtrace -q -s call_stack.d -c \"python3.6 script.py\"" +msgstr "" + #: howto/instrumentation.rst:236 msgid "The output looks like this:" msgstr "" +#: howto/instrumentation.rst:178 +msgid "" +"156641360502280 function-entry:call_stack.py:start:23\n" +"156641360518804 function-entry: call_stack.py:function_1:1\n" +"156641360532797 function-entry: call_stack.py:function_3:9\n" +"156641360546807 function-return: call_stack.py:function_3:10\n" +"156641360563367 function-return: call_stack.py:function_1:2\n" +"156641360578365 function-entry: call_stack.py:function_2:5\n" +"156641360591757 function-entry: call_stack.py:function_1:1\n" +"156641360605556 function-entry: call_stack.py:function_3:9\n" +"156641360617482 function-return: call_stack.py:function_3:10\n" +"156641360629814 function-return: call_stack.py:function_1:2\n" +"156641360642285 function-return: call_stack.py:function_2:6\n" +"156641360656770 function-entry: call_stack.py:function_3:9\n" +"156641360669707 function-return: call_stack.py:function_3:10\n" +"156641360687853 function-entry: call_stack.py:function_4:13\n" +"156641360700719 function-return: call_stack.py:function_4:14\n" +"156641360719640 function-entry: call_stack.py:function_5:18\n" +"156641360732567 function-return: call_stack.py:function_5:21\n" +"156641360747370 function-return:call_stack.py:start:28" +msgstr "" + #: howto/instrumentation.rst:201 msgid "Static SystemTap markers" msgstr "" @@ -159,6 +316,44 @@ msgid "" "hierarchy of a Python script:" msgstr "" +#: howto/instrumentation.rst:210 +msgid "" +"probe process(\"python\").mark(\"function__entry\") {\n" +" filename = user_string($arg1);\n" +" funcname = user_string($arg2);\n" +" lineno = $arg3;\n" +"\n" +" printf(\"%s => %s in %s:%d\\\\n\",\n" +" thread_indent(1), funcname, filename, lineno);\n" +"}\n" +"\n" +"probe process(\"python\").mark(\"function__return\") {\n" +" filename = user_string($arg1);\n" +" funcname = user_string($arg2);\n" +" lineno = $arg3;\n" +"\n" +" printf(\"%s <= %s in %s:%d\\\\n\",\n" +" thread_indent(-1), funcname, filename, lineno);\n" +"}" +msgstr "" + +#: howto/instrumentation.rst:232 +msgid "" +"$ stap \\\n" +" show-call-hierarchy.stp \\\n" +" -c \"./python test.py\"" +msgstr "" + +#: howto/instrumentation.rst:238 +msgid "" +"11408 python(8274): => __contains__ in Lib/_abcoll.py:362\n" +"11414 python(8274): => __getitem__ in Lib/os.py:425\n" +"11418 python(8274): => encode in Lib/os.py:490\n" +"11424 python(8274): <= encode in Lib/os.py:493\n" +"11428 python(8274): <= __getitem__ in Lib/os.py:426\n" +"11433 python(8274): <= __contains__ in Lib/_abcoll.py:366" +msgstr "" + #: howto/instrumentation.rst:247 msgid "where the columns are:" msgstr "" @@ -187,10 +382,20 @@ msgid "" "reflect this. For example, this line from the above example:" msgstr "" +#: howto/instrumentation.rst:259 +msgid "probe process(\"python\").mark(\"function__entry\") {" +msgstr "" + #: howto/instrumentation.rst:263 msgid "should instead read:" msgstr "" +#: howto/instrumentation.rst:265 +msgid "" +"probe process(\"python\").library(\"libpython3.6dm.so.1.0\")." +"mark(\"function__entry\") {" +msgstr "" + #: howto/instrumentation.rst:269 msgid "(assuming a :ref:`debug build ` of CPython 3.6)" msgstr "" @@ -253,7 +458,7 @@ msgstr "" #: howto/instrumentation.rst:309 msgid "" "Fires when the Python interpreter starts a garbage collection cycle. " -"``arg0`` is the generation to scan, like :func:`gc.collect()`." +"``arg0`` is the generation to scan, like :func:`gc.collect`." msgstr "" #: howto/instrumentation.rst:314 @@ -296,6 +501,29 @@ msgstr "" msgid "Here is a tapset file, based on a non-shared build of CPython:" msgstr "" +#: howto/instrumentation.rst:351 +msgid "" +"/*\n" +" Provide a higher-level wrapping around the function__entry and\n" +" function__return markers:\n" +" \\*/\n" +"probe python.function.entry = process(\"python\").mark(\"function__entry\")\n" +"{\n" +" filename = user_string($arg1);\n" +" funcname = user_string($arg2);\n" +" lineno = $arg3;\n" +" frameptr = $arg4\n" +"}\n" +"probe python.function.return = process(\"python\")." +"mark(\"function__return\")\n" +"{\n" +" filename = user_string($arg1);\n" +" funcname = user_string($arg2);\n" +" lineno = $arg3;\n" +" frameptr = $arg4\n" +"}" +msgstr "" + #: howto/instrumentation.rst:372 msgid "" "If this file is installed in SystemTap's tapset directory (e.g. ``/usr/share/" @@ -327,9 +555,46 @@ msgid "" "needing to directly name the static markers:" msgstr "" +#: howto/instrumentation.rst:395 +msgid "" +"probe python.function.entry\n" +"{\n" +" printf(\"%s => %s in %s:%d\\n\",\n" +" thread_indent(1), funcname, filename, lineno);\n" +"}\n" +"\n" +"probe python.function.return\n" +"{\n" +" printf(\"%s <= %s in %s:%d\\n\",\n" +" thread_indent(-1), funcname, filename, lineno);\n" +"}" +msgstr "" + #: howto/instrumentation.rst:410 msgid "" "The following script uses the tapset above to provide a top-like view of all " "running CPython code, showing the top 20 most frequently entered bytecode " "frames, each second, across the whole system:" msgstr "" + +#: howto/instrumentation.rst:414 +msgid "" +"global fn_calls;\n" +"\n" +"probe python.function.entry\n" +"{\n" +" fn_calls[pid(), filename, funcname, lineno] += 1;\n" +"}\n" +"\n" +"probe timer.ms(1000) {\n" +" printf(\"\\033[2J\\033[1;1H\") /* clear screen \\*/\n" +" printf(\"%6s %80s %6s %30s %6s\\n\",\n" +" \"PID\", \"FILENAME\", \"LINE\", \"FUNCTION\", \"CALLS\")\n" +" foreach ([pid, filename, funcname, lineno] in fn_calls- limit 20) {\n" +" printf(\"%6d %80s %6d %30s %6d\\n\",\n" +" pid, filename, lineno, funcname,\n" +" fn_calls[pid, filename, funcname, lineno]);\n" +" }\n" +" delete fn_calls;\n" +"}" +msgstr "" diff --git a/howto/ipaddress.po b/howto/ipaddress.po index 3814e1cb0..20a689d22 100644 --- a/howto/ipaddress.po +++ b/howto/ipaddress.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-02-24 17:22+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -98,6 +98,14 @@ msgid "" "within 32 bits are assumed to be IPv4 addresses::" msgstr "" +#: howto/ipaddress.rst:64 +msgid "" +">>> ipaddress.ip_address(3221225985)\n" +"IPv4Address('192.0.2.1')\n" +">>> ipaddress.ip_address(42540766411282592856903984951653826561)\n" +"IPv6Address('2001:db8::1')" +msgstr "" + #: howto/ipaddress.rst:69 msgid "" "To force the use of IPv4 or IPv6 addresses, the relevant classes can be " @@ -105,6 +113,16 @@ msgid "" "addresses for small integers::" msgstr "" +#: howto/ipaddress.rst:73 +msgid "" +">>> ipaddress.ip_address(1)\n" +"IPv4Address('0.0.0.1')\n" +">>> ipaddress.IPv4Address(1)\n" +"IPv4Address('0.0.0.1')\n" +">>> ipaddress.IPv6Address(1)\n" +"IPv6Address('::1')" +msgstr "" + #: howto/ipaddress.rst:82 msgid "Defining Networks" msgstr "" @@ -127,6 +145,14 @@ msgid "" "IP version automatically::" msgstr "" +#: howto/ipaddress.rst:96 +msgid "" +">>> ipaddress.ip_network('192.0.2.0/24')\n" +"IPv4Network('192.0.2.0/24')\n" +">>> ipaddress.ip_network('2001:db8::0/96')\n" +"IPv6Network('2001:db8::/96')" +msgstr "" + #: howto/ipaddress.rst:101 msgid "" "Network objects cannot have any host bits set. The practical effect of this " @@ -144,6 +170,16 @@ msgid "" "the constructor::" msgstr "" +#: howto/ipaddress.rst:112 +msgid "" +">>> ipaddress.ip_network('192.0.2.1/24')\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: 192.0.2.1/24 has host bits set\n" +">>> ipaddress.ip_network('192.0.2.1/24', strict=False)\n" +"IPv4Network('192.0.2.0/24')" +msgstr "" + #: howto/ipaddress.rst:119 msgid "" "While the string form offers significantly more flexibility, networks can " @@ -152,6 +188,14 @@ msgid "" "integer, so the network prefix includes the entire network address::" msgstr "" +#: howto/ipaddress.rst:124 +msgid "" +">>> ipaddress.ip_network(3221225984)\n" +"IPv4Network('192.0.2.0/32')\n" +">>> ipaddress.ip_network(42540766411282592856903984951653826560)\n" +"IPv6Network('2001:db8::/128')" +msgstr "" + #: howto/ipaddress.rst:129 msgid "" "As with addresses, creation of a particular kind of network can be forced by " @@ -196,18 +240,63 @@ msgstr "" msgid "Extracting the IP version::" msgstr "" +#: howto/ipaddress.rst:165 +msgid "" +">>> addr4 = ipaddress.ip_address('192.0.2.1')\n" +">>> addr6 = ipaddress.ip_address('2001:db8::1')\n" +">>> addr6.version\n" +"6\n" +">>> addr4.version\n" +"4" +msgstr "" + #: howto/ipaddress.rst:172 msgid "Obtaining the network from an interface::" msgstr "" +#: howto/ipaddress.rst:174 +msgid "" +">>> host4 = ipaddress.ip_interface('192.0.2.1/24')\n" +">>> host4.network\n" +"IPv4Network('192.0.2.0/24')\n" +">>> host6 = ipaddress.ip_interface('2001:db8::1/96')\n" +">>> host6.network\n" +"IPv6Network('2001:db8::/96')" +msgstr "" + #: howto/ipaddress.rst:181 msgid "Finding out how many individual addresses are in a network::" msgstr "" +#: howto/ipaddress.rst:183 +msgid "" +">>> net4 = ipaddress.ip_network('192.0.2.0/24')\n" +">>> net4.num_addresses\n" +"256\n" +">>> net6 = ipaddress.ip_network('2001:db8::0/96')\n" +">>> net6.num_addresses\n" +"4294967296" +msgstr "" + #: howto/ipaddress.rst:190 msgid "Iterating through the \"usable\" addresses on a network::" msgstr "" +#: howto/ipaddress.rst:192 +msgid "" +">>> net4 = ipaddress.ip_network('192.0.2.0/24')\n" +">>> for x in net4.hosts():\n" +"... print(x) \n" +"192.0.2.1\n" +"192.0.2.2\n" +"192.0.2.3\n" +"192.0.2.4\n" +"...\n" +"192.0.2.252\n" +"192.0.2.253\n" +"192.0.2.254" +msgstr "" + #: howto/ipaddress.rst:205 msgid "" "Obtaining the netmask (i.e. set bits corresponding to the network prefix) or " @@ -218,6 +307,18 @@ msgstr "" msgid "Exploding or compressing the address::" msgstr "" +#: howto/ipaddress.rst:222 +msgid "" +">>> addr6.exploded\n" +"'2001:0db8:0000:0000:0000:0000:0000:0001'\n" +">>> addr6.compressed\n" +"'2001:db8::1'\n" +">>> net6.exploded\n" +"'2001:0db8:0000:0000:0000:0000:0000:0000/96'\n" +">>> net6.compressed\n" +"'2001:db8::/96'" +msgstr "" + #: howto/ipaddress.rst:231 msgid "" "While IPv4 doesn't support explosion or compression, the associated objects " @@ -236,16 +337,43 @@ msgid "" "to index them like this::" msgstr "" +#: howto/ipaddress.rst:243 +msgid "" +">>> net4[1]\n" +"IPv4Address('192.0.2.1')\n" +">>> net4[-1]\n" +"IPv4Address('192.0.2.255')\n" +">>> net6[1]\n" +"IPv6Address('2001:db8::1')\n" +">>> net6[-1]\n" +"IPv6Address('2001:db8::ffff:ffff')" +msgstr "" + #: howto/ipaddress.rst:253 msgid "" "It also means that network objects lend themselves to using the list " "membership test syntax like this::" msgstr "" +#: howto/ipaddress.rst:256 +msgid "" +"if address in network:\n" +" # do something" +msgstr "" + #: howto/ipaddress.rst:259 msgid "Containment testing is done efficiently based on the network prefix::" msgstr "" +#: howto/ipaddress.rst:261 +msgid "" +">>> addr4 = ipaddress.ip_address('192.0.2.1')\n" +">>> addr4 in ipaddress.ip_network('192.0.2.0/24')\n" +"True\n" +">>> addr4 in ipaddress.ip_network('192.0.3.0/24')\n" +"False" +msgstr "" + #: howto/ipaddress.rst:269 msgid "Comparisons" msgstr "" @@ -256,6 +384,12 @@ msgid "" "objects, where it makes sense::" msgstr "" +#: howto/ipaddress.rst:274 +msgid "" +">>> ipaddress.ip_address('192.0.2.1') < ipaddress.ip_address('192.0.2.2')\n" +"True" +msgstr "" + #: howto/ipaddress.rst:277 msgid "" "A :exc:`TypeError` exception is raised if you try to compare objects of " @@ -273,6 +407,15 @@ msgid "" "an integer or string that the other module will accept::" msgstr "" +#: howto/ipaddress.rst:288 +msgid "" +">>> addr4 = ipaddress.ip_address('192.0.2.1')\n" +">>> str(addr4)\n" +"'192.0.2.1'\n" +">>> int(addr4)\n" +"3221225985" +msgstr "" + #: howto/ipaddress.rst:296 msgid "Getting more detail when instance creation fails" msgstr "" @@ -302,9 +445,39 @@ msgid "" "constructors directly. For example::" msgstr "" +#: howto/ipaddress.rst:314 +msgid "" +">>> ipaddress.ip_address(\"192.168.0.256\")\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: '192.168.0.256' does not appear to be an IPv4 or IPv6 address\n" +">>> ipaddress.IPv4Address(\"192.168.0.256\")\n" +"Traceback (most recent call last):\n" +" ...\n" +"ipaddress.AddressValueError: Octet 256 (> 255) not permitted in " +"'192.168.0.256'\n" +"\n" +">>> ipaddress.ip_network(\"192.168.0.1/64\")\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: '192.168.0.1/64' does not appear to be an IPv4 or IPv6 network\n" +">>> ipaddress.IPv4Network(\"192.168.0.1/64\")\n" +"Traceback (most recent call last):\n" +" ...\n" +"ipaddress.NetmaskValueError: '64' is not a valid netmask" +msgstr "" + #: howto/ipaddress.rst:332 msgid "" "However, both of the module specific exceptions have :exc:`ValueError` as " "their parent class, so if you're not concerned with the particular type of " "error, you can still write code like the following::" msgstr "" + +#: howto/ipaddress.rst:336 +msgid "" +"try:\n" +" network = ipaddress.IPv4Network(address)\n" +"except ValueError:\n" +" print('address/netmask is invalid for IPv4:', address)" +msgstr "" diff --git a/howto/isolating-extensions.po b/howto/isolating-extensions.po index a586729cb..dd427504a 100644 --- a/howto/isolating-extensions.po +++ b/howto/isolating-extensions.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-02-24 17:22+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -148,6 +148,17 @@ msgid "" "example:" msgstr "" +#: howto/isolating-extensions.rst:93 +msgid "" +">>> import sys\n" +">>> import binascii\n" +">>> old_binascii = binascii\n" +">>> del sys.modules['binascii']\n" +">>> import binascii # create a new module object\n" +">>> old_binascii == binascii\n" +"False" +msgstr "" + #: howto/isolating-extensions.rst:103 msgid "" "As a rule of thumb, the two modules should be completely independent. All " @@ -179,6 +190,20 @@ msgid "" "exception is *not* caught:" msgstr "" +#: howto/isolating-extensions.rst:126 +msgid "" +">>> old_binascii.Error == binascii.Error\n" +"False\n" +">>> try:\n" +"... old_binascii.unhexlify(b'qwertyuiop')\n" +"... except binascii.Error:\n" +"... print('boo')\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 2, in \n" +"binascii.Error: Non-hexadecimal digit found" +msgstr "" + #: howto/isolating-extensions.rst:139 msgid "" "This is expected. Notice that pure-Python modules behave the same way: it is " @@ -297,6 +322,23 @@ msgid "" "For example::" msgstr "" +#: howto/isolating-extensions.rst:218 +msgid "" +"static int loaded = 0;\n" +"\n" +"static int\n" +"exec_module(PyObject* module)\n" +"{\n" +" if (loaded) {\n" +" PyErr_SetString(PyExc_ImportError,\n" +" \"cannot load module more than once per process\");\n" +" return -1;\n" +" }\n" +" loaded = 1;\n" +" // ... rest of initialization\n" +"}" +msgstr "" + #: howto/isolating-extensions.rst:234 msgid "Module State Access from Functions" msgstr "" @@ -308,6 +350,19 @@ msgid "" "state, you can use ``PyModule_GetState``::" msgstr "" +#: howto/isolating-extensions.rst:240 +msgid "" +"static PyObject *\n" +"func(PyObject *module, PyObject *args)\n" +"{\n" +" my_struct *state = (my_struct*)PyModule_GetState(module);\n" +" if (state == NULL) {\n" +" return NULL;\n" +" }\n" +" // ... rest of logic\n" +"}" +msgstr "" + #: howto/isolating-extensions.rst:251 msgid "" "``PyModule_GetState`` may return ``NULL`` without setting an exception if " @@ -443,8 +498,8 @@ msgstr "" #: howto/isolating-extensions.rst:342 msgid "" -"Please refer to the the documentation of :c:macro:`Py_TPFLAGS_HAVE_GC` and :" -"c:member:`~PyTypeObject.tp_traverse` for additional considerations." +"Please refer to the documentation of :c:macro:`Py_TPFLAGS_HAVE_GC` and :c:" +"member:`~PyTypeObject.tp_traverse` for additional considerations." msgstr "" #: howto/isolating-extensions.rst:346 @@ -465,6 +520,17 @@ msgid "" "visit the type, so it must be more complicated::" msgstr "" +#: howto/isolating-extensions.rst:358 +msgid "" +"static int my_traverse(PyObject *self, visitproc visit, void *arg)\n" +"{\n" +" if (Py_Version >= 0x03090000) {\n" +" Py_VISIT(Py_TYPE(self));\n" +" }\n" +" return 0;\n" +"}" +msgstr "" + #: howto/isolating-extensions.rst:366 msgid "" "Unfortunately, :c:data:`Py_Version` was only added in Python 3.11. As a " @@ -497,10 +563,25 @@ msgstr "" msgid "For example, if your traverse function includes::" msgstr "" +#: howto/isolating-extensions.rst:384 +msgid "base->tp_traverse(self, visit, arg)" +msgstr "" + #: howto/isolating-extensions.rst:386 msgid "...and ``base`` may be a static type, then it should also include::" msgstr "" +#: howto/isolating-extensions.rst:388 +msgid "" +"if (base->tp_flags & Py_TPFLAGS_HEAPTYPE) {\n" +" // a heap type's tp_traverse already visited Py_TYPE(self)\n" +"} else {\n" +" if (Py_Version >= 0x03090000) {\n" +" Py_VISIT(Py_TYPE(self));\n" +" }\n" +"}" +msgstr "" + #: howto/isolating-extensions.rst:396 msgid "" "It is not necessary to handle the type's reference count in :c:member:" @@ -532,6 +613,18 @@ msgid "" "needs to be decremented *after* the instance is deallocated. For example::" msgstr "" +#: howto/isolating-extensions.rst:412 +msgid "" +"static void my_dealloc(PyObject *self)\n" +"{\n" +" PyObject_GC_UnTrack(self);\n" +" ...\n" +" PyTypeObject *type = Py_TYPE(self);\n" +" type->tp_free(self);\n" +" Py_DECREF(type);\n" +"}" +msgstr "" + #: howto/isolating-extensions.rst:421 msgid "" "The default ``tp_dealloc`` function does this, so if your type does *not* " @@ -566,6 +659,10 @@ msgid "" "That is, replace ``TYPE *o = PyObject_New(TYPE, typeobj)`` with::" msgstr "" +#: howto/isolating-extensions.rst:444 +msgid "TYPE *o = typeobj->tp_alloc(typeobj, 0);" +msgstr "" + #: howto/isolating-extensions.rst:446 msgid "" "Replace ``o = PyObject_NewVar(TYPE, typeobj, size)`` with the same, but use " @@ -578,6 +675,13 @@ msgid "" "func:`PyObject_GC_New` or :c:func:`PyObject_GC_NewVar`::" msgstr "" +#: howto/isolating-extensions.rst:452 +msgid "" +"TYPE *o = PyObject_GC_New(TYPE, typeobj);\n" +"\n" +"TYPE *o = PyObject_GC_NewVar(TYPE, typeobj, size);" +msgstr "" + #: howto/isolating-extensions.rst:458 msgid "Module State Access from Classes" msgstr "" @@ -595,6 +699,14 @@ msgid "" "these two steps with :c:func:`PyType_GetModuleState`, resulting in::" msgstr "" +#: howto/isolating-extensions.rst:467 +msgid "" +"my_struct *state = (my_struct*)PyType_GetModuleState(type);\n" +"if (state == NULL) {\n" +" return NULL;\n" +"}" +msgstr "" + #: howto/isolating-extensions.rst:474 msgid "Module State Access from Regular Methods" msgstr "" @@ -627,6 +739,19 @@ msgid "" "get_defining_class`` returns ``Base`` even if ``type(self) == Sub``:" msgstr "" +#: howto/isolating-extensions.rst:494 +msgid "" +"class Base:\n" +" def get_type_of_self(self):\n" +" return type(self)\n" +"\n" +" def get_defining_class(self):\n" +" return __class__\n" +"\n" +"class Sub(Base):\n" +" pass" +msgstr "" + #: howto/isolating-extensions.rst:506 msgid "" "For a method to get its \"defining class\", it must use the :ref:" @@ -635,6 +760,16 @@ msgid "" "corresponding :c:type:`PyCMethod` signature::" msgstr "" +#: howto/isolating-extensions.rst:511 +msgid "" +"PyObject *PyCMethod(\n" +" PyObject *self, // object the method was called on\n" +" PyTypeObject *defining_class, // defining class\n" +" PyObject *const *args, // C array of arguments\n" +" Py_ssize_t nargs, // length of \"args\"\n" +" PyObject *kwnames) // NULL, or dict of keyword arguments" +msgstr "" + #: howto/isolating-extensions.rst:518 msgid "" "Once you have the defining class, call :c:func:`PyType_GetModuleState` to " @@ -645,6 +780,33 @@ msgstr "" msgid "For example::" msgstr "" +#: howto/isolating-extensions.rst:523 +msgid "" +"static PyObject *\n" +"example_method(PyObject *self,\n" +" PyTypeObject *defining_class,\n" +" PyObject *const *args,\n" +" Py_ssize_t nargs,\n" +" PyObject *kwnames)\n" +"{\n" +" my_struct *state = (my_struct*)PyType_GetModuleState(defining_class);\n" +" if (state == NULL) {\n" +" return NULL;\n" +" }\n" +" ... // rest of logic\n" +"}\n" +"\n" +"PyDoc_STRVAR(example_method_doc, \"...\");\n" +"\n" +"static PyMethodDef my_methods[] = {\n" +" {\"example_method\",\n" +" (PyCFunction)(void(*)(void))example_method,\n" +" METH_METHOD|METH_FASTCALL|METH_KEYWORDS,\n" +" example_method_doc}\n" +" {NULL},\n" +"}" +msgstr "" + #: howto/isolating-extensions.rst:549 msgid "Module State Access from Slot Methods, Getters and Setters" msgstr "" @@ -670,6 +832,15 @@ msgid "" "you have the module, call :c:func:`PyModule_GetState` to get the state::" msgstr "" +#: howto/isolating-extensions.rst:573 +msgid "" +"PyObject *module = PyType_GetModuleByDef(Py_TYPE(self), &module_def);\n" +"my_struct *state = (my_struct*)PyModule_GetState(module);\n" +"if (state == NULL) {\n" +" return NULL;\n" +"}" +msgstr "" + #: howto/isolating-extensions.rst:579 msgid "" ":c:func:`!PyType_GetModuleByDef` works by searching the :term:`method " diff --git a/howto/logging-cookbook.po b/howto/logging-cookbook.po index 46279a1eb..2cebdd097 100644 --- a/howto/logging-cookbook.po +++ b/howto/logging-cookbook.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -51,14 +51,94 @@ msgid "" "module::" msgstr "" +#: howto/logging-cookbook.rst:26 +msgid "" +"import logging\n" +"import auxiliary_module\n" +"\n" +"# create logger with 'spam_application'\n" +"logger = logging.getLogger('spam_application')\n" +"logger.setLevel(logging.DEBUG)\n" +"# create file handler which logs even debug messages\n" +"fh = logging.FileHandler('spam.log')\n" +"fh.setLevel(logging.DEBUG)\n" +"# create console handler with a higher log level\n" +"ch = logging.StreamHandler()\n" +"ch.setLevel(logging.ERROR)\n" +"# create formatter and add it to the handlers\n" +"formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - " +"%(message)s')\n" +"fh.setFormatter(formatter)\n" +"ch.setFormatter(formatter)\n" +"# add the handlers to the logger\n" +"logger.addHandler(fh)\n" +"logger.addHandler(ch)\n" +"\n" +"logger.info('creating an instance of auxiliary_module.Auxiliary')\n" +"a = auxiliary_module.Auxiliary()\n" +"logger.info('created an instance of auxiliary_module.Auxiliary')\n" +"logger.info('calling auxiliary_module.Auxiliary.do_something')\n" +"a.do_something()\n" +"logger.info('finished auxiliary_module.Auxiliary.do_something')\n" +"logger.info('calling auxiliary_module.some_function()')\n" +"auxiliary_module.some_function()\n" +"logger.info('done with auxiliary_module.some_function()')" +msgstr "" + #: howto/logging-cookbook.rst:56 msgid "Here is the auxiliary module::" msgstr "" +#: howto/logging-cookbook.rst:58 +msgid "" +"import logging\n" +"\n" +"# create logger\n" +"module_logger = logging.getLogger('spam_application.auxiliary')\n" +"\n" +"class Auxiliary:\n" +" def __init__(self):\n" +" self.logger = logging.getLogger('spam_application.auxiliary." +"Auxiliary')\n" +" self.logger.info('creating an instance of Auxiliary')\n" +"\n" +" def do_something(self):\n" +" self.logger.info('doing something')\n" +" a = 1 + 1\n" +" self.logger.info('done doing something')\n" +"\n" +"def some_function():\n" +" module_logger.info('received a call to \"some_function\"')" +msgstr "" + #: howto/logging-cookbook.rst:76 msgid "The output looks like this:" msgstr "" +#: howto/logging-cookbook.rst:78 +msgid "" +"2005-03-23 23:47:11,663 - spam_application - INFO -\n" +" creating an instance of auxiliary_module.Auxiliary\n" +"2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -\n" +" creating an instance of Auxiliary\n" +"2005-03-23 23:47:11,665 - spam_application - INFO -\n" +" created an instance of auxiliary_module.Auxiliary\n" +"2005-03-23 23:47:11,668 - spam_application - INFO -\n" +" calling auxiliary_module.Auxiliary.do_something\n" +"2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -\n" +" doing something\n" +"2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -\n" +" done doing something\n" +"2005-03-23 23:47:11,670 - spam_application - INFO -\n" +" finished auxiliary_module.Auxiliary.do_something\n" +"2005-03-23 23:47:11,671 - spam_application - INFO -\n" +" calling auxiliary_module.some_function()\n" +"2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -\n" +" received a call to 'some_function'\n" +"2005-03-23 23:47:11,673 - spam_application - INFO -\n" +" done with auxiliary_module.some_function()" +msgstr "" + #: howto/logging-cookbook.rst:102 msgid "Logging from multiple threads" msgstr "" @@ -69,10 +149,61 @@ msgid "" "example shows logging from the main (initial) thread and another thread::" msgstr "" +#: howto/logging-cookbook.rst:107 +msgid "" +"import logging\n" +"import threading\n" +"import time\n" +"\n" +"def worker(arg):\n" +" while not arg['stop']:\n" +" logging.debug('Hi from myfunc')\n" +" time.sleep(0.5)\n" +"\n" +"def main():\n" +" logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d " +"%(threadName)s %(message)s')\n" +" info = {'stop': False}\n" +" thread = threading.Thread(target=worker, args=(info,))\n" +" thread.start()\n" +" while True:\n" +" try:\n" +" logging.debug('Hello from main')\n" +" time.sleep(0.75)\n" +" except KeyboardInterrupt:\n" +" info['stop'] = True\n" +" break\n" +" thread.join()\n" +"\n" +"if __name__ == '__main__':\n" +" main()" +msgstr "" + #: howto/logging-cookbook.rst:133 msgid "When run, the script should print something like the following:" msgstr "" +#: howto/logging-cookbook.rst:135 +msgid "" +" 0 Thread-1 Hi from myfunc\n" +" 3 MainThread Hello from main\n" +" 505 Thread-1 Hi from myfunc\n" +" 755 MainThread Hello from main\n" +"1007 Thread-1 Hi from myfunc\n" +"1507 MainThread Hello from main\n" +"1508 Thread-1 Hi from myfunc\n" +"2010 Thread-1 Hi from myfunc\n" +"2258 MainThread Hello from main\n" +"2512 Thread-1 Hi from myfunc\n" +"3009 MainThread Hello from main\n" +"3013 Thread-1 Hi from myfunc\n" +"3515 Thread-1 Hi from myfunc\n" +"3761 MainThread Hello from main\n" +"4017 Thread-1 Hi from myfunc\n" +"4513 MainThread Hello from main\n" +"4518 Thread-1 Hi from myfunc" +msgstr "" + #: howto/logging-cookbook.rst:155 msgid "" "This shows the logging output interspersed as one might expect. This " @@ -95,6 +226,35 @@ msgid "" "example::" msgstr "" +#: howto/logging-cookbook.rst:169 +msgid "" +"import logging\n" +"\n" +"logger = logging.getLogger('simple_example')\n" +"logger.setLevel(logging.DEBUG)\n" +"# create file handler which logs even debug messages\n" +"fh = logging.FileHandler('spam.log')\n" +"fh.setLevel(logging.DEBUG)\n" +"# create console handler with a higher log level\n" +"ch = logging.StreamHandler()\n" +"ch.setLevel(logging.ERROR)\n" +"# create formatter and add it to the handlers\n" +"formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - " +"%(message)s')\n" +"ch.setFormatter(formatter)\n" +"fh.setFormatter(formatter)\n" +"# add the handlers to logger\n" +"logger.addHandler(ch)\n" +"logger.addHandler(fh)\n" +"\n" +"# 'application' code\n" +"logger.debug('debug message')\n" +"logger.info('info message')\n" +"logger.warning('warn message')\n" +"logger.error('error message')\n" +"logger.critical('critical message')" +msgstr "" + #: howto/logging-cookbook.rst:194 msgid "" "Notice that the 'application' code does not care about multiple handlers. " @@ -127,14 +287,69 @@ msgid "" "console messages should not. Here's how you can achieve this::" msgstr "" +#: howto/logging-cookbook.rst:216 +msgid "" +"import logging\n" +"\n" +"# set up logging to file - see previous section for more details\n" +"logging.basicConfig(level=logging.DEBUG,\n" +" format='%(asctime)s %(name)-12s %(levelname)-8s " +"%(message)s',\n" +" datefmt='%m-%d %H:%M',\n" +" filename='/tmp/myapp.log',\n" +" filemode='w')\n" +"# define a Handler which writes INFO messages or higher to the sys.stderr\n" +"console = logging.StreamHandler()\n" +"console.setLevel(logging.INFO)\n" +"# set a format which is simpler for console use\n" +"formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')\n" +"# tell the handler to use this format\n" +"console.setFormatter(formatter)\n" +"# add the handler to the root logger\n" +"logging.getLogger('').addHandler(console)\n" +"\n" +"# Now, we can log to the root logger, or any other logger. First the " +"root...\n" +"logging.info('Jackdaws love my big sphinx of quartz.')\n" +"\n" +"# Now, define a couple of other loggers which might represent areas in your\n" +"# application:\n" +"\n" +"logger1 = logging.getLogger('myapp.area1')\n" +"logger2 = logging.getLogger('myapp.area2')\n" +"\n" +"logger1.debug('Quick zephyrs blow, vexing daft Jim.')\n" +"logger1.info('How quickly daft jumping zebras vex.')\n" +"logger2.warning('Jail zesty vixen who grabbed pay from quack.')\n" +"logger2.error('The five boxing wizards jump quickly.')" +msgstr "" + #: howto/logging-cookbook.rst:248 msgid "When you run this, on the console you will see" msgstr "" +#: howto/logging-cookbook.rst:250 +msgid "" +"root : INFO Jackdaws love my big sphinx of quartz.\n" +"myapp.area1 : INFO How quickly daft jumping zebras vex.\n" +"myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.\n" +"myapp.area2 : ERROR The five boxing wizards jump quickly." +msgstr "" + #: howto/logging-cookbook.rst:257 msgid "and in the file you will see something like" msgstr "" +#: howto/logging-cookbook.rst:259 +msgid "" +"10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.\n" +"10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.\n" +"10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.\n" +"10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from " +"quack.\n" +"10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly." +msgstr "" + #: howto/logging-cookbook.rst:267 msgid "" "As you can see, the DEBUG message only shows up in the file. The other " @@ -184,6 +399,47 @@ msgstr "" msgid "Suppose you configure logging with the following JSON:" msgstr "" +#: howto/logging-cookbook.rst:295 +msgid "" +"{\n" +" \"version\": 1,\n" +" \"disable_existing_loggers\": false,\n" +" \"formatters\": {\n" +" \"simple\": {\n" +" \"format\": \"%(levelname)-8s - %(message)s\"\n" +" }\n" +" },\n" +" \"handlers\": {\n" +" \"stdout\": {\n" +" \"class\": \"logging.StreamHandler\",\n" +" \"level\": \"INFO\",\n" +" \"formatter\": \"simple\",\n" +" \"stream\": \"ext://sys.stdout\"\n" +" },\n" +" \"stderr\": {\n" +" \"class\": \"logging.StreamHandler\",\n" +" \"level\": \"ERROR\",\n" +" \"formatter\": \"simple\",\n" +" \"stream\": \"ext://sys.stderr\"\n" +" },\n" +" \"file\": {\n" +" \"class\": \"logging.FileHandler\",\n" +" \"formatter\": \"simple\",\n" +" \"filename\": \"app.log\",\n" +" \"mode\": \"w\"\n" +" }\n" +" },\n" +" \"root\": {\n" +" \"level\": \"DEBUG\",\n" +" \"handlers\": [\n" +" \"stderr\",\n" +" \"stdout\",\n" +" \"file\"\n" +" ]\n" +" }\n" +"}" +msgstr "" + #: howto/logging-cookbook.rst:335 msgid "" "This configuration does *almost* what we want, except that ``sys.stdout`` " @@ -193,16 +449,52 @@ msgid "" "adding a ``filters`` section parallel to ``formatters`` and ``handlers``:" msgstr "" +#: howto/logging-cookbook.rst:341 +msgid "" +"{\n" +" \"filters\": {\n" +" \"warnings_and_below\": {\n" +" \"()\" : \"__main__.filter_maker\",\n" +" \"level\": \"WARNING\"\n" +" }\n" +" }\n" +"}" +msgstr "" + #: howto/logging-cookbook.rst:352 msgid "and changing the section on the ``stdout`` handler to add it:" msgstr "" +#: howto/logging-cookbook.rst:354 +msgid "" +"{\n" +" \"stdout\": {\n" +" \"class\": \"logging.StreamHandler\",\n" +" \"level\": \"INFO\",\n" +" \"formatter\": \"simple\",\n" +" \"stream\": \"ext://sys.stdout\",\n" +" \"filters\": [\"warnings_and_below\"]\n" +" }\n" +"}" +msgstr "" + #: howto/logging-cookbook.rst:366 msgid "" "A filter is just a function, so we can define the ``filter_maker`` (a " "factory function) as follows:" msgstr "" +#: howto/logging-cookbook.rst:369 +msgid "" +"def filter_maker(level):\n" +" level = getattr(logging, level)\n" +"\n" +" def filter(record):\n" +" return record.levelno <= level\n" +"\n" +" return filter" +msgstr "" + #: howto/logging-cookbook.rst:379 msgid "" "This converts the string argument passed in to a numeric level, and returns " @@ -218,14 +510,110 @@ msgstr "" msgid "With the filter added, we can run ``main.py``, which in full is:" msgstr "" +#: howto/logging-cookbook.rst:389 +msgid "" +"import json\n" +"import logging\n" +"import logging.config\n" +"\n" +"CONFIG = '''\n" +"{\n" +" \"version\": 1,\n" +" \"disable_existing_loggers\": false,\n" +" \"formatters\": {\n" +" \"simple\": {\n" +" \"format\": \"%(levelname)-8s - %(message)s\"\n" +" }\n" +" },\n" +" \"filters\": {\n" +" \"warnings_and_below\": {\n" +" \"()\" : \"__main__.filter_maker\",\n" +" \"level\": \"WARNING\"\n" +" }\n" +" },\n" +" \"handlers\": {\n" +" \"stdout\": {\n" +" \"class\": \"logging.StreamHandler\",\n" +" \"level\": \"INFO\",\n" +" \"formatter\": \"simple\",\n" +" \"stream\": \"ext://sys.stdout\",\n" +" \"filters\": [\"warnings_and_below\"]\n" +" },\n" +" \"stderr\": {\n" +" \"class\": \"logging.StreamHandler\",\n" +" \"level\": \"ERROR\",\n" +" \"formatter\": \"simple\",\n" +" \"stream\": \"ext://sys.stderr\"\n" +" },\n" +" \"file\": {\n" +" \"class\": \"logging.FileHandler\",\n" +" \"formatter\": \"simple\",\n" +" \"filename\": \"app.log\",\n" +" \"mode\": \"w\"\n" +" }\n" +" },\n" +" \"root\": {\n" +" \"level\": \"DEBUG\",\n" +" \"handlers\": [\n" +" \"stderr\",\n" +" \"stdout\",\n" +" \"file\"\n" +" ]\n" +" }\n" +"}\n" +"'''\n" +"\n" +"def filter_maker(level):\n" +" level = getattr(logging, level)\n" +"\n" +" def filter(record):\n" +" return record.levelno <= level\n" +"\n" +" return filter\n" +"\n" +"logging.config.dictConfig(json.loads(CONFIG))\n" +"logging.debug('A DEBUG message')\n" +"logging.info('An INFO message')\n" +"logging.warning('A WARNING message')\n" +"logging.error('An ERROR message')\n" +"logging.critical('A CRITICAL message')" +msgstr "" + #: howto/logging-cookbook.rst:457 msgid "And after running it like this:" msgstr "" +#: howto/logging-cookbook.rst:459 +msgid "python main.py 2>stderr.log >stdout.log" +msgstr "" + #: howto/logging-cookbook.rst:463 msgid "We can see the results are as expected:" msgstr "" +#: howto/logging-cookbook.rst:465 +msgid "" +"$ more *.log\n" +"::::::::::::::\n" +"app.log\n" +"::::::::::::::\n" +"DEBUG - A DEBUG message\n" +"INFO - An INFO message\n" +"WARNING - A WARNING message\n" +"ERROR - An ERROR message\n" +"CRITICAL - A CRITICAL message\n" +"::::::::::::::\n" +"stderr.log\n" +"::::::::::::::\n" +"ERROR - An ERROR message\n" +"CRITICAL - A CRITICAL message\n" +"::::::::::::::\n" +"stdout.log\n" +"::::::::::::::\n" +"INFO - An INFO message\n" +"WARNING - A WARNING message" +msgstr "" + #: howto/logging-cookbook.rst:489 msgid "Configuration server example" msgstr "" @@ -234,6 +622,38 @@ msgstr "" msgid "Here is an example of a module using the logging configuration server::" msgstr "" +#: howto/logging-cookbook.rst:493 +msgid "" +"import logging\n" +"import logging.config\n" +"import time\n" +"import os\n" +"\n" +"# read initial config file\n" +"logging.config.fileConfig('logging.conf')\n" +"\n" +"# create and start listener on port 9999\n" +"t = logging.config.listen(9999)\n" +"t.start()\n" +"\n" +"logger = logging.getLogger('simpleExample')\n" +"\n" +"try:\n" +" # loop through logging calls to see the difference\n" +" # new configurations make, until Ctrl+C is pressed\n" +" while True:\n" +" logger.debug('debug message')\n" +" logger.info('info message')\n" +" logger.warning('warn message')\n" +" logger.error('error message')\n" +" logger.critical('critical message')\n" +" time.sleep(5)\n" +"except KeyboardInterrupt:\n" +" # cleanup\n" +" logging.config.stopListening()\n" +" t.join()" +msgstr "" + #: howto/logging-cookbook.rst:522 msgid "" "And here is a script that takes a filename and sends that file to the " @@ -241,6 +661,26 @@ msgid "" "configuration::" msgstr "" +#: howto/logging-cookbook.rst:526 +msgid "" +"#!/usr/bin/env python\n" +"import socket, sys, struct\n" +"\n" +"with open(sys.argv[1], 'rb') as f:\n" +" data_to_send = f.read()\n" +"\n" +"HOST = 'localhost'\n" +"PORT = 9999\n" +"s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n" +"print('connecting...')\n" +"s.connect((HOST, PORT))\n" +"print('sending config...')\n" +"s.send(struct.pack('>L', len(data_to_send)))\n" +"s.send(data_to_send)\n" +"s.close()\n" +"print('complete')" +msgstr "" + #: howto/logging-cookbook.rst:547 msgid "Dealing with handlers that block" msgstr "" @@ -301,10 +741,33 @@ msgstr "" msgid "An example of using these two classes follows (imports omitted)::" msgstr "" +#: howto/logging-cookbook.rst:589 +msgid "" +"que = queue.Queue(-1) # no limit on size\n" +"queue_handler = QueueHandler(que)\n" +"handler = logging.StreamHandler()\n" +"listener = QueueListener(que, handler)\n" +"root = logging.getLogger()\n" +"root.addHandler(queue_handler)\n" +"formatter = logging.Formatter('%(threadName)s: %(message)s')\n" +"handler.setFormatter(formatter)\n" +"listener.start()\n" +"# The log output will display the thread which generated\n" +"# the event (the main thread) rather than the internal\n" +"# thread which monitors the internal queue. This is what\n" +"# you want to happen.\n" +"root.warning('Look out!')\n" +"listener.stop()" +msgstr "" + #: howto/logging-cookbook.rst:605 msgid "which, when run, will produce:" msgstr "" +#: howto/logging-cookbook.rst:607 +msgid "MainThread: Look out!" +msgstr "" + #: howto/logging-cookbook.rst:611 msgid "" "Although the earlier discussion wasn't specifically talking about async " @@ -339,18 +802,147 @@ msgid "" "`SocketHandler` instance to the root logger at the sending end::" msgstr "" +#: howto/logging-cookbook.rst:638 +msgid "" +"import logging, logging.handlers\n" +"\n" +"rootLogger = logging.getLogger('')\n" +"rootLogger.setLevel(logging.DEBUG)\n" +"socketHandler = logging.handlers.SocketHandler('localhost',\n" +" logging.handlers.DEFAULT_TCP_LOGGING_PORT)\n" +"# don't bother with a formatter, since a socket handler sends the event as\n" +"# an unformatted pickle\n" +"rootLogger.addHandler(socketHandler)\n" +"\n" +"# Now, we can log to the root logger, or any other logger. First the " +"root...\n" +"logging.info('Jackdaws love my big sphinx of quartz.')\n" +"\n" +"# Now, define a couple of other loggers which might represent areas in your\n" +"# application:\n" +"\n" +"logger1 = logging.getLogger('myapp.area1')\n" +"logger2 = logging.getLogger('myapp.area2')\n" +"\n" +"logger1.debug('Quick zephyrs blow, vexing daft Jim.')\n" +"logger1.info('How quickly daft jumping zebras vex.')\n" +"logger2.warning('Jail zesty vixen who grabbed pay from quack.')\n" +"logger2.error('The five boxing wizards jump quickly.')" +msgstr "" + #: howto/logging-cookbook.rst:662 msgid "" "At the receiving end, you can set up a receiver using the :mod:" "`socketserver` module. Here is a basic working example::" msgstr "" +#: howto/logging-cookbook.rst:665 +msgid "" +"import pickle\n" +"import logging\n" +"import logging.handlers\n" +"import socketserver\n" +"import struct\n" +"\n" +"\n" +"class LogRecordStreamHandler(socketserver.StreamRequestHandler):\n" +" \"\"\"Handler for a streaming logging request.\n" +"\n" +" This basically logs the record using whatever logging policy is\n" +" configured locally.\n" +" \"\"\"\n" +"\n" +" def handle(self):\n" +" \"\"\"\n" +" Handle multiple requests - each expected to be a 4-byte length,\n" +" followed by the LogRecord in pickle format. Logs the record\n" +" according to whatever policy is configured locally.\n" +" \"\"\"\n" +" while True:\n" +" chunk = self.connection.recv(4)\n" +" if len(chunk) < 4:\n" +" break\n" +" slen = struct.unpack('>L', chunk)[0]\n" +" chunk = self.connection.recv(slen)\n" +" while len(chunk) < slen:\n" +" chunk = chunk + self.connection.recv(slen - len(chunk))\n" +" obj = self.unPickle(chunk)\n" +" record = logging.makeLogRecord(obj)\n" +" self.handleLogRecord(record)\n" +"\n" +" def unPickle(self, data):\n" +" return pickle.loads(data)\n" +"\n" +" def handleLogRecord(self, record):\n" +" # if a name is specified, we use the named logger rather than the " +"one\n" +" # implied by the record.\n" +" if self.server.logname is not None:\n" +" name = self.server.logname\n" +" else:\n" +" name = record.name\n" +" logger = logging.getLogger(name)\n" +" # N.B. EVERY record gets logged. This is because Logger.handle\n" +" # is normally called AFTER logger-level filtering. If you want\n" +" # to do filtering, do it at the client end to save wasting\n" +" # cycles and network bandwidth!\n" +" logger.handle(record)\n" +"\n" +"class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):\n" +" \"\"\"\n" +" Simple TCP socket-based logging receiver suitable for testing.\n" +" \"\"\"\n" +"\n" +" allow_reuse_address = True\n" +"\n" +" def __init__(self, host='localhost',\n" +" port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,\n" +" handler=LogRecordStreamHandler):\n" +" socketserver.ThreadingTCPServer.__init__(self, (host, port), " +"handler)\n" +" self.abort = 0\n" +" self.timeout = 1\n" +" self.logname = None\n" +"\n" +" def serve_until_stopped(self):\n" +" import select\n" +" abort = 0\n" +" while not abort:\n" +" rd, wr, ex = select.select([self.socket.fileno()],\n" +" [], [],\n" +" self.timeout)\n" +" if rd:\n" +" self.handle_request()\n" +" abort = self.abort\n" +"\n" +"def main():\n" +" logging.basicConfig(\n" +" format='%(relativeCreated)5d %(name)-15s %(levelname)-8s " +"%(message)s')\n" +" tcpserver = LogRecordSocketReceiver()\n" +" print('About to start TCP server...')\n" +" tcpserver.serve_until_stopped()\n" +"\n" +"if __name__ == '__main__':\n" +" main()" +msgstr "" + #: howto/logging-cookbook.rst:750 msgid "" "First run the server, and then the client. On the client side, nothing is " "printed on the console; on the server side, you should see something like:" msgstr "" +#: howto/logging-cookbook.rst:753 +msgid "" +"About to start TCP server...\n" +" 59 root INFO Jackdaws love my big sphinx of quartz.\n" +" 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.\n" +" 69 myapp.area1 INFO How quickly daft jumping zebras vex.\n" +" 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.\n" +" 69 myapp.area2 ERROR The five boxing wizards jump quickly." +msgstr "" + #: howto/logging-cookbook.rst:762 msgid "" "Note that there are some security issues with pickle in some scenarios. If " @@ -553,6 +1145,17 @@ msgid "" "of :class:`LoggerAdapter`::" msgstr "" +#: howto/logging-cookbook.rst:878 +msgid "" +"def debug(self, msg, /, *args, **kwargs):\n" +" \"\"\"\n" +" Delegate a debug call to the underlying logger, after adding\n" +" contextual information from this adapter instance.\n" +" \"\"\"\n" +" msg, kwargs = self.process(msg, kwargs)\n" +" self.logger.debug(msg, *args, **kwargs)" +msgstr "" + #: howto/logging-cookbook.rst:886 msgid "" "The :meth:`~LoggerAdapter.process` method of :class:`LoggerAdapter` is where " @@ -577,10 +1180,27 @@ msgid "" "`~LoggerAdapter.process` to do what you need. Here is a simple example::" msgstr "" +#: howto/logging-cookbook.rst:903 +msgid "" +"class CustomAdapter(logging.LoggerAdapter):\n" +" \"\"\"\n" +" This example adapter expects the passed in dict-like object to have a\n" +" 'connid' key, whose value in brackets is prepended to the log message.\n" +" \"\"\"\n" +" def process(self, msg, kwargs):\n" +" return '[%s] %s' % (self.extra['connid'], msg), kwargs" +msgstr "" + #: howto/logging-cookbook.rst:911 msgid "which you can use like this::" msgstr "" +#: howto/logging-cookbook.rst:913 +msgid "" +"logger = logging.getLogger(__name__)\n" +"adapter = CustomAdapter(logger, {'connid': some_conn_id})" +msgstr "" + #: howto/logging-cookbook.rst:916 msgid "" "Then any events that you log to the adapter will have the value of " @@ -625,10 +1245,81 @@ msgid "" "an example script::" msgstr "" +#: howto/logging-cookbook.rst:947 +msgid "" +"import logging\n" +"from random import choice\n" +"\n" +"class ContextFilter(logging.Filter):\n" +" \"\"\"\n" +" This is a filter which injects contextual information into the log.\n" +"\n" +" Rather than use actual contextual information, we just use random\n" +" data in this demo.\n" +" \"\"\"\n" +"\n" +" USERS = ['jim', 'fred', 'sheila']\n" +" IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']\n" +"\n" +" def filter(self, record):\n" +"\n" +" record.ip = choice(ContextFilter.IPS)\n" +" record.user = choice(ContextFilter.USERS)\n" +" return True\n" +"\n" +"if __name__ == '__main__':\n" +" levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, " +"logging.CRITICAL)\n" +" logging.basicConfig(level=logging.DEBUG,\n" +" format='%(asctime)-15s %(name)-5s %(levelname)-8s " +"IP: %(ip)-15s User: %(user)-8s %(message)s')\n" +" a1 = logging.getLogger('a.b.c')\n" +" a2 = logging.getLogger('d.e.f')\n" +"\n" +" f = ContextFilter()\n" +" a1.addFilter(f)\n" +" a2.addFilter(f)\n" +" a1.debug('A debug message')\n" +" a1.info('An info message with %s', 'some parameters')\n" +" for x in range(10):\n" +" lvl = choice(levels)\n" +" lvlname = logging.getLevelName(lvl)\n" +" a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, " +"'parameters')" +msgstr "" + #: howto/logging-cookbook.rst:984 msgid "which, when run, produces something like:" msgstr "" +#: howto/logging-cookbook.rst:986 +msgid "" +"2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A " +"debug message\n" +"2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An " +"info message with some parameters\n" +"2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A " +"message at CRITICAL level with 2 parameters\n" +"2010-09-06 22:38:15,300 d.e.f ERROR IP: 127.0.0.1 User: jim A " +"message at ERROR level with 2 parameters\n" +"2010-09-06 22:38:15,300 d.e.f DEBUG IP: 127.0.0.1 User: sheila A " +"message at DEBUG level with 2 parameters\n" +"2010-09-06 22:38:15,300 d.e.f ERROR IP: 123.231.231.123 User: fred A " +"message at ERROR level with 2 parameters\n" +"2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1 User: jim A " +"message at CRITICAL level with 2 parameters\n" +"2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A " +"message at CRITICAL level with 2 parameters\n" +"2010-09-06 22:38:15,300 d.e.f DEBUG IP: 192.168.0.1 User: jim A " +"message at DEBUG level with 2 parameters\n" +"2010-09-06 22:38:15,301 d.e.f ERROR IP: 127.0.0.1 User: sheila A " +"message at ERROR level with 2 parameters\n" +"2010-09-06 22:38:15,301 d.e.f DEBUG IP: 123.231.231.123 User: fred A " +"message at DEBUG level with 2 parameters\n" +"2010-09-06 22:38:15,301 d.e.f INFO IP: 123.231.231.123 User: fred A " +"message at INFO level with 2 parameters" +msgstr "" + #: howto/logging-cookbook.rst:1002 msgid "Use of ``contextvars``" msgstr "" @@ -658,6 +1349,21 @@ msgstr "" msgid "Let's assume that the library can be simulated by the following code:" msgstr "" +#: howto/logging-cookbook.rst:1019 +msgid "" +"# webapplib.py\n" +"import logging\n" +"import time\n" +"\n" +"logger = logging.getLogger(__name__)\n" +"\n" +"def useful():\n" +" # Just a representative event logged from the library\n" +" logger.debug('Hello from webapplib!')\n" +" # Just sleep for a bit so other threads get to run\n" +" time.sleep(0.01)" +msgstr "" + #: howto/logging-cookbook.rst:1033 msgid "" "We can simulate the multiple web applications by means of two simple " @@ -665,6 +1371,161 @@ msgid "" "applications work - each request is handled by a thread:" msgstr "" +#: howto/logging-cookbook.rst:1037 +msgid "" +"# main.py\n" +"import argparse\n" +"from contextvars import ContextVar\n" +"import logging\n" +"import os\n" +"from random import choice\n" +"import threading\n" +"import webapplib\n" +"\n" +"logger = logging.getLogger(__name__)\n" +"root = logging.getLogger()\n" +"root.setLevel(logging.DEBUG)\n" +"\n" +"class Request:\n" +" \"\"\"\n" +" A simple dummy request class which just holds dummy HTTP request " +"method,\n" +" client IP address and client username\n" +" \"\"\"\n" +" def __init__(self, method, ip, user):\n" +" self.method = method\n" +" self.ip = ip\n" +" self.user = user\n" +"\n" +"# A dummy set of requests which will be used in the simulation - we'll just " +"pick\n" +"# from this list randomly. Note that all GET requests are from 192.168.2." +"XXX\n" +"# addresses, whereas POST requests are from 192.16.3.XXX addresses. Three " +"users\n" +"# are represented in the sample requests.\n" +"\n" +"REQUESTS = [\n" +" Request('GET', '192.168.2.20', 'jim'),\n" +" Request('POST', '192.168.3.20', 'fred'),\n" +" Request('GET', '192.168.2.21', 'sheila'),\n" +" Request('POST', '192.168.3.21', 'jim'),\n" +" Request('GET', '192.168.2.22', 'fred'),\n" +" Request('POST', '192.168.3.22', 'sheila'),\n" +"]\n" +"\n" +"# Note that the format string includes references to request context " +"information\n" +"# such as HTTP method, client IP and username\n" +"\n" +"formatter = logging.Formatter('%(threadName)-11s %(appName)s %(name)-9s " +"%(user)-6s %(ip)s %(method)-4s %(message)s')\n" +"\n" +"# Create our context variables. These will be filled at the start of " +"request\n" +"# processing, and used in the logging that happens during that processing\n" +"\n" +"ctx_request = ContextVar('request')\n" +"ctx_appname = ContextVar('appname')\n" +"\n" +"class InjectingFilter(logging.Filter):\n" +" \"\"\"\n" +" A filter which injects context-specific information into logs and " +"ensures\n" +" that only information for a specific webapp is included in its log\n" +" \"\"\"\n" +" def __init__(self, app):\n" +" self.app = app\n" +"\n" +" def filter(self, record):\n" +" request = ctx_request.get()\n" +" record.method = request.method\n" +" record.ip = request.ip\n" +" record.user = request.user\n" +" record.appName = appName = ctx_appname.get()\n" +" return appName == self.app.name\n" +"\n" +"class WebApp:\n" +" \"\"\"\n" +" A dummy web application class which has its own handler and filter for " +"a\n" +" webapp-specific log.\n" +" \"\"\"\n" +" def __init__(self, name):\n" +" self.name = name\n" +" handler = logging.FileHandler(name + '.log', 'w')\n" +" f = InjectingFilter(self)\n" +" handler.setFormatter(formatter)\n" +" handler.addFilter(f)\n" +" root.addHandler(handler)\n" +" self.num_requests = 0\n" +"\n" +" def process_request(self, request):\n" +" \"\"\"\n" +" This is the dummy method for processing a request. It's called on a\n" +" different thread for every request. We store the context information " +"into\n" +" the context vars before doing anything else.\n" +" \"\"\"\n" +" ctx_request.set(request)\n" +" ctx_appname.set(self.name)\n" +" self.num_requests += 1\n" +" logger.debug('Request processing started')\n" +" webapplib.useful()\n" +" logger.debug('Request processing finished')\n" +"\n" +"def main():\n" +" fn = os.path.splitext(os.path.basename(__file__))[0]\n" +" adhf = argparse.ArgumentDefaultsHelpFormatter\n" +" ap = argparse.ArgumentParser(formatter_class=adhf, prog=fn,\n" +" description='Simulate a couple of web '\n" +" 'applications handling some '\n" +" 'requests, showing how request " +"'\n" +" 'context can be used to '\n" +" 'populate logs')\n" +" aa = ap.add_argument\n" +" aa('--count', '-c', type=int, default=100, help='How many requests to " +"simulate')\n" +" options = ap.parse_args()\n" +"\n" +" # Create the dummy webapps and put them in a list which we can use to " +"select\n" +" # from randomly\n" +" app1 = WebApp('app1')\n" +" app2 = WebApp('app2')\n" +" apps = [app1, app2]\n" +" threads = []\n" +" # Add a common handler which will capture all events\n" +" handler = logging.FileHandler('app.log', 'w')\n" +" handler.setFormatter(formatter)\n" +" root.addHandler(handler)\n" +"\n" +" # Generate calls to process requests\n" +" for i in range(options.count):\n" +" try:\n" +" # Pick an app at random and a request for it to process\n" +" app = choice(apps)\n" +" request = choice(REQUESTS)\n" +" # Process the request in its own thread\n" +" t = threading.Thread(target=app.process_request, " +"args=(request,))\n" +" threads.append(t)\n" +" t.start()\n" +" except KeyboardInterrupt:\n" +" break\n" +"\n" +" # Wait for the threads to terminate\n" +" for t in threads:\n" +" t.join()\n" +"\n" +" for app in apps:\n" +" print('%s processed %s requests' % (app.name, app.num_requests))\n" +"\n" +"if __name__ == '__main__':\n" +" main()" +msgstr "" + #: howto/logging-cookbook.rst:1177 msgid "" "If you run the above, you should find that roughly half the requests go " @@ -676,6 +1537,61 @@ msgid "" "illustrated by the following shell output:" msgstr "" +#: howto/logging-cookbook.rst:1184 +msgid "" +"~/logging-contextual-webapp$ python main.py\n" +"app1 processed 51 requests\n" +"app2 processed 49 requests\n" +"~/logging-contextual-webapp$ wc -l *.log\n" +" 153 app1.log\n" +" 147 app2.log\n" +" 300 app.log\n" +" 600 total\n" +"~/logging-contextual-webapp$ head -3 app1.log\n" +"Thread-3 (process_request) app1 __main__ jim 192.168.3.21 POST Request " +"processing started\n" +"Thread-3 (process_request) app1 webapplib jim 192.168.3.21 POST Hello " +"from webapplib!\n" +"Thread-5 (process_request) app1 __main__ jim 192.168.3.21 POST Request " +"processing started\n" +"~/logging-contextual-webapp$ head -3 app2.log\n" +"Thread-1 (process_request) app2 __main__ sheila 192.168.2.21 GET Request " +"processing started\n" +"Thread-1 (process_request) app2 webapplib sheila 192.168.2.21 GET Hello " +"from webapplib!\n" +"Thread-2 (process_request) app2 __main__ jim 192.168.2.20 GET Request " +"processing started\n" +"~/logging-contextual-webapp$ head app.log\n" +"Thread-1 (process_request) app2 __main__ sheila 192.168.2.21 GET Request " +"processing started\n" +"Thread-1 (process_request) app2 webapplib sheila 192.168.2.21 GET Hello " +"from webapplib!\n" +"Thread-2 (process_request) app2 __main__ jim 192.168.2.20 GET Request " +"processing started\n" +"Thread-3 (process_request) app1 __main__ jim 192.168.3.21 POST Request " +"processing started\n" +"Thread-2 (process_request) app2 webapplib jim 192.168.2.20 GET Hello " +"from webapplib!\n" +"Thread-3 (process_request) app1 webapplib jim 192.168.3.21 POST Hello " +"from webapplib!\n" +"Thread-4 (process_request) app2 __main__ fred 192.168.2.22 GET Request " +"processing started\n" +"Thread-5 (process_request) app1 __main__ jim 192.168.3.21 POST Request " +"processing started\n" +"Thread-4 (process_request) app2 webapplib fred 192.168.2.22 GET Hello " +"from webapplib!\n" +"Thread-6 (process_request) app1 __main__ jim 192.168.3.21 POST Request " +"processing started\n" +"~/logging-contextual-webapp$ grep app1 app1.log | wc -l\n" +"153\n" +"~/logging-contextual-webapp$ grep app2 app2.log | wc -l\n" +"147\n" +"~/logging-contextual-webapp$ grep app1 app.log | wc -l\n" +"153\n" +"~/logging-contextual-webapp$ grep app2 app.log | wc -l\n" +"147" +msgstr "" + #: howto/logging-cookbook.rst:1224 msgid "Imparting contextual information in handlers" msgstr "" @@ -688,6 +1604,28 @@ msgid "" "instead of modifying it in-place, as shown in the following script::" msgstr "" +#: howto/logging-cookbook.rst:1231 +msgid "" +"import copy\n" +"import logging\n" +"\n" +"def filter(record: logging.LogRecord):\n" +" record = copy.copy(record)\n" +" record.user = 'jim'\n" +" return record\n" +"\n" +"if __name__ == '__main__':\n" +" logger = logging.getLogger()\n" +" logger.setLevel(logging.INFO)\n" +" handler = logging.StreamHandler()\n" +" formatter = logging.Formatter('%(message)s from %(user)-8s')\n" +" handler.setFormatter(formatter)\n" +" handler.addFilter(filter)\n" +" logger.addHandler(handler)\n" +"\n" +" logger.info('A log message')" +msgstr "" + #: howto/logging-cookbook.rst:1253 msgid "Logging to a single file from multiple processes" msgstr "" @@ -734,12 +1672,229 @@ msgid "" "requirements::" msgstr "" +#: howto/logging-cookbook.rst:1289 +msgid "" +"# You'll need these imports in your own code\n" +"import logging\n" +"import logging.handlers\n" +"import multiprocessing\n" +"\n" +"# Next two import lines for this demo only\n" +"from random import choice, random\n" +"import time\n" +"\n" +"#\n" +"# Because you'll want to define the logging configurations for listener and " +"workers, the\n" +"# listener and worker process functions take a configurer parameter which is " +"a callable\n" +"# for configuring logging for that process. These functions are also passed " +"the queue,\n" +"# which they use for communication.\n" +"#\n" +"# In practice, you can configure the listener however you want, but note " +"that in this\n" +"# simple example, the listener does not apply level or filter logic to " +"received records.\n" +"# In practice, you would probably want to do this logic in the worker " +"processes, to avoid\n" +"# sending events which would be filtered out between processes.\n" +"#\n" +"# The size of the rotated files is made small so you can see the results " +"easily.\n" +"def listener_configurer():\n" +" root = logging.getLogger()\n" +" h = logging.handlers.RotatingFileHandler('mptest.log', 'a', 300, 10)\n" +" f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s " +"%(levelname)-8s %(message)s')\n" +" h.setFormatter(f)\n" +" root.addHandler(h)\n" +"\n" +"# This is the listener process top-level loop: wait for logging events\n" +"# (LogRecords)on the queue and handle them, quit when you get a None for a\n" +"# LogRecord.\n" +"def listener_process(queue, configurer):\n" +" configurer()\n" +" while True:\n" +" try:\n" +" record = queue.get()\n" +" if record is None: # We send this as a sentinel to tell the " +"listener to quit.\n" +" break\n" +" logger = logging.getLogger(record.name)\n" +" logger.handle(record) # No level or filter logic applied - just " +"do it!\n" +" except Exception:\n" +" import sys, traceback\n" +" print('Whoops! Problem:', file=sys.stderr)\n" +" traceback.print_exc(file=sys.stderr)\n" +"\n" +"# Arrays used for random selections in this demo\n" +"\n" +"LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,\n" +" logging.ERROR, logging.CRITICAL]\n" +"\n" +"LOGGERS = ['a.b.c', 'd.e.f']\n" +"\n" +"MESSAGES = [\n" +" 'Random message #1',\n" +" 'Random message #2',\n" +" 'Random message #3',\n" +"]\n" +"\n" +"# The worker configuration is done at the start of the worker process run.\n" +"# Note that on Windows you can't rely on fork semantics, so each process\n" +"# will run the logging configuration code when it starts.\n" +"def worker_configurer(queue):\n" +" h = logging.handlers.QueueHandler(queue) # Just the one handler needed\n" +" root = logging.getLogger()\n" +" root.addHandler(h)\n" +" # send all messages, for demo; no other level or filter logic applied.\n" +" root.setLevel(logging.DEBUG)\n" +"\n" +"# This is the worker process top-level loop, which just logs ten events " +"with\n" +"# random intervening delays before terminating.\n" +"# The print messages are just so you know it's doing something!\n" +"def worker_process(queue, configurer):\n" +" configurer(queue)\n" +" name = multiprocessing.current_process().name\n" +" print('Worker started: %s' % name)\n" +" for i in range(10):\n" +" time.sleep(random())\n" +" logger = logging.getLogger(choice(LOGGERS))\n" +" level = choice(LEVELS)\n" +" message = choice(MESSAGES)\n" +" logger.log(level, message)\n" +" print('Worker finished: %s' % name)\n" +"\n" +"# Here's where the demo gets orchestrated. Create the queue, create and " +"start\n" +"# the listener, create ten workers and start them, wait for them to finish,\n" +"# then send a None to the queue to tell the listener to finish.\n" +"def main():\n" +" queue = multiprocessing.Queue(-1)\n" +" listener = multiprocessing.Process(target=listener_process,\n" +" args=(queue, listener_configurer))\n" +" listener.start()\n" +" workers = []\n" +" for i in range(10):\n" +" worker = multiprocessing.Process(target=worker_process,\n" +" args=(queue, worker_configurer))\n" +" workers.append(worker)\n" +" worker.start()\n" +" for w in workers:\n" +" w.join()\n" +" queue.put_nowait(None)\n" +" listener.join()\n" +"\n" +"if __name__ == '__main__':\n" +" main()" +msgstr "" + #: howto/logging-cookbook.rst:1394 msgid "" "A variant of the above script keeps the logging in the main process, in a " "separate thread::" msgstr "" +#: howto/logging-cookbook.rst:1397 +msgid "" +"import logging\n" +"import logging.config\n" +"import logging.handlers\n" +"from multiprocessing import Process, Queue\n" +"import random\n" +"import threading\n" +"import time\n" +"\n" +"def logger_thread(q):\n" +" while True:\n" +" record = q.get()\n" +" if record is None:\n" +" break\n" +" logger = logging.getLogger(record.name)\n" +" logger.handle(record)\n" +"\n" +"\n" +"def worker_process(q):\n" +" qh = logging.handlers.QueueHandler(q)\n" +" root = logging.getLogger()\n" +" root.setLevel(logging.DEBUG)\n" +" root.addHandler(qh)\n" +" levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,\n" +" logging.CRITICAL]\n" +" loggers = ['foo', 'foo.bar', 'foo.bar.baz',\n" +" 'spam', 'spam.ham', 'spam.ham.eggs']\n" +" for i in range(100):\n" +" lvl = random.choice(levels)\n" +" logger = logging.getLogger(random.choice(loggers))\n" +" logger.log(lvl, 'Message no. %d', i)\n" +"\n" +"if __name__ == '__main__':\n" +" q = Queue()\n" +" d = {\n" +" 'version': 1,\n" +" 'formatters': {\n" +" 'detailed': {\n" +" 'class': 'logging.Formatter',\n" +" 'format': '%(asctime)s %(name)-15s %(levelname)-8s " +"%(processName)-10s %(message)s'\n" +" }\n" +" },\n" +" 'handlers': {\n" +" 'console': {\n" +" 'class': 'logging.StreamHandler',\n" +" 'level': 'INFO',\n" +" },\n" +" 'file': {\n" +" 'class': 'logging.FileHandler',\n" +" 'filename': 'mplog.log',\n" +" 'mode': 'w',\n" +" 'formatter': 'detailed',\n" +" },\n" +" 'foofile': {\n" +" 'class': 'logging.FileHandler',\n" +" 'filename': 'mplog-foo.log',\n" +" 'mode': 'w',\n" +" 'formatter': 'detailed',\n" +" },\n" +" 'errors': {\n" +" 'class': 'logging.FileHandler',\n" +" 'filename': 'mplog-errors.log',\n" +" 'mode': 'w',\n" +" 'level': 'ERROR',\n" +" 'formatter': 'detailed',\n" +" },\n" +" },\n" +" 'loggers': {\n" +" 'foo': {\n" +" 'handlers': ['foofile']\n" +" }\n" +" },\n" +" 'root': {\n" +" 'level': 'DEBUG',\n" +" 'handlers': ['console', 'file', 'errors']\n" +" },\n" +" }\n" +" workers = []\n" +" for i in range(5):\n" +" wp = Process(target=worker_process, name='worker %d' % (i + 1), " +"args=(q,))\n" +" workers.append(wp)\n" +" wp.start()\n" +" logging.config.dictConfig(d)\n" +" lp = threading.Thread(target=logger_thread, args=(q,))\n" +" lp.start()\n" +" # At this point, the main process could do some useful work of its own\n" +" # Once it's done that, it can wait for the workers to terminate...\n" +" for wp in workers:\n" +" wp.join()\n" +" # And now tell the logging thread to finish up, too\n" +" q.put(None)\n" +" lp.join()" +msgstr "" + #: howto/logging-cookbook.rst:1489 msgid "" "This variant shows how you can e.g. apply configuration for particular " @@ -761,18 +1916,47 @@ msgid "" "Instead of" msgstr "" +#: howto/logging-cookbook.rst:1502 +msgid "queue = multiprocessing.Queue(-1)" +msgstr "" + #: howto/logging-cookbook.rst:1506 msgid "you should use" msgstr "" +#: howto/logging-cookbook.rst:1508 +msgid "" +"queue = multiprocessing.Manager().Queue(-1) # also works with the examples " +"above" +msgstr "" + #: howto/logging-cookbook.rst:1512 msgid "and you can then replace the worker creation from this::" msgstr "" +#: howto/logging-cookbook.rst:1514 +msgid "" +"workers = []\n" +"for i in range(10):\n" +" worker = multiprocessing.Process(target=worker_process,\n" +" args=(queue, worker_configurer))\n" +" workers.append(worker)\n" +" worker.start()\n" +"for w in workers:\n" +" w.join()" +msgstr "" + #: howto/logging-cookbook.rst:1523 msgid "to this (remembering to first import :mod:`concurrent.futures`)::" msgstr "" +#: howto/logging-cookbook.rst:1525 +msgid "" +"with concurrent.futures.ProcessPoolExecutor(max_workers=10) as executor:\n" +" for i in range(10):\n" +" executor.submit(worker_process, queue, worker_configurer)" +msgstr "" + #: howto/logging-cookbook.rst:1530 msgid "Deploying Web applications using Gunicorn and uWSGI" msgstr "" @@ -802,12 +1986,51 @@ msgid "" "usage pattern, the logging package provides a :class:`RotatingFileHandler`::" msgstr "" +#: howto/logging-cookbook.rst:1553 +msgid "" +"import glob\n" +"import logging\n" +"import logging.handlers\n" +"\n" +"LOG_FILENAME = 'logging_rotatingfile_example.out'\n" +"\n" +"# Set up a specific logger with our desired output level\n" +"my_logger = logging.getLogger('MyLogger')\n" +"my_logger.setLevel(logging.DEBUG)\n" +"\n" +"# Add the log message handler to the logger\n" +"handler = logging.handlers.RotatingFileHandler(\n" +" LOG_FILENAME, maxBytes=20, backupCount=5)\n" +"\n" +"my_logger.addHandler(handler)\n" +"\n" +"# Log some messages\n" +"for i in range(20):\n" +" my_logger.debug('i = %d' % i)\n" +"\n" +"# See what files are created\n" +"logfiles = glob.glob('%s*' % LOG_FILENAME)\n" +"\n" +"for filename in logfiles:\n" +" print(filename)" +msgstr "" + #: howto/logging-cookbook.rst:1579 msgid "" "The result should be 6 separate files, each with part of the log history for " "the application:" msgstr "" +#: howto/logging-cookbook.rst:1582 +msgid "" +"logging_rotatingfile_example.out\n" +"logging_rotatingfile_example.out.1\n" +"logging_rotatingfile_example.out.2\n" +"logging_rotatingfile_example.out.3\n" +"logging_rotatingfile_example.out.4\n" +"logging_rotatingfile_example.out.5" +msgstr "" + #: howto/logging-cookbook.rst:1591 msgid "" "The most current file is always :file:`logging_rotatingfile_example.out`, " @@ -848,6 +2071,31 @@ msgid "" "session to show the possibilities:" msgstr "" +#: howto/logging-cookbook.rst:1622 +msgid "" +">>> import logging\n" +">>> root = logging.getLogger()\n" +">>> root.setLevel(logging.DEBUG)\n" +">>> handler = logging.StreamHandler()\n" +">>> bf = logging.Formatter('{asctime} {name} {levelname:8s} {message}',\n" +"... style='{')\n" +">>> handler.setFormatter(bf)\n" +">>> root.addHandler(handler)\n" +">>> logger = logging.getLogger('foo.bar')\n" +">>> logger.debug('This is a DEBUG message')\n" +"2010-10-28 15:11:55,341 foo.bar DEBUG This is a DEBUG message\n" +">>> logger.critical('This is a CRITICAL message')\n" +"2010-10-28 15:12:11,526 foo.bar CRITICAL This is a CRITICAL message\n" +">>> df = logging.Formatter('$asctime $name ${levelname} $message',\n" +"... style='$')\n" +">>> handler.setFormatter(df)\n" +">>> logger.debug('This is a DEBUG message')\n" +"2010-10-28 15:13:06,924 foo.bar DEBUG This is a DEBUG message\n" +">>> logger.critical('This is a CRITICAL message')\n" +"2010-10-28 15:13:11,494 foo.bar CRITICAL This is a CRITICAL message\n" +">>>" +msgstr "" + #: howto/logging-cookbook.rst:1646 msgid "" "Note that the formatting of logging messages for final output to logs is " @@ -855,6 +2103,13 @@ msgid "" "That can still use %-formatting, as shown here::" msgstr "" +#: howto/logging-cookbook.rst:1650 +msgid "" +">>> logger.error('This is an%s %s %s', 'other,', 'ERROR,', 'message')\n" +"2010-10-28 15:19:29,833 foo.bar ERROR This is another, ERROR, message\n" +">>>" +msgstr "" + #: howto/logging-cookbook.rst:1654 msgid "" "Logging calls (``logger.debug()``, ``logger.info()`` etc.) only take " @@ -880,6 +2135,27 @@ msgid "" "the following two classes::" msgstr "" +#: howto/logging-cookbook.rst:1673 howto/logging-cookbook.rst:2761 +msgid "" +"class BraceMessage:\n" +" def __init__(self, fmt, /, *args, **kwargs):\n" +" self.fmt = fmt\n" +" self.args = args\n" +" self.kwargs = kwargs\n" +"\n" +" def __str__(self):\n" +" return self.fmt.format(*self.args, **self.kwargs)\n" +"\n" +"class DollarMessage:\n" +" def __init__(self, fmt, /, **kwargs):\n" +" self.fmt = fmt\n" +" self.kwargs = kwargs\n" +"\n" +" def __str__(self):\n" +" from string import Template\n" +" return Template(self.fmt).substitute(**self.kwargs)" +msgstr "" + #: howto/logging-cookbook.rst:1691 msgid "" "Either of these can be used in place of a format string, to allow {}- or $-" @@ -898,6 +2174,25 @@ msgid "" "that they're declared in a module called ``wherever``):" msgstr "" +#: howto/logging-cookbook.rst:1703 +msgid "" +">>> from wherever import BraceMessage as __\n" +">>> print(__('Message with {0} {name}', 2, name='placeholders'))\n" +"Message with 2 placeholders\n" +">>> class Point: pass\n" +"...\n" +">>> p = Point()\n" +">>> p.x = 0.5\n" +">>> p.y = 0.5\n" +">>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})',\n" +"... point=p))\n" +"Message with coordinates: (0.50, 0.50)\n" +">>> from wherever import DollarMessage as __\n" +">>> print(__('Message with $num $what', num=2, what='placeholders'))\n" +"Message with 2 placeholders\n" +">>>" +msgstr "" + #: howto/logging-cookbook.rst:1721 msgid "" "While the above examples use ``print()`` to show how the formatting works, " @@ -922,6 +2217,35 @@ msgid "" "effect to the above, as in the following example::" msgstr "" +#: howto/logging-cookbook.rst:1736 +msgid "" +"import logging\n" +"\n" +"class Message:\n" +" def __init__(self, fmt, args):\n" +" self.fmt = fmt\n" +" self.args = args\n" +"\n" +" def __str__(self):\n" +" return self.fmt.format(*self.args)\n" +"\n" +"class StyleAdapter(logging.LoggerAdapter):\n" +" def log(self, level, msg, /, *args, stacklevel=1, **kwargs):\n" +" if self.isEnabledFor(level):\n" +" msg, kwargs = self.process(msg, kwargs)\n" +" self.logger.log(level, Message(msg, args), **kwargs,\n" +" stacklevel=stacklevel+1)\n" +"\n" +"logger = StyleAdapter(logging.getLogger(__name__))\n" +"\n" +"def main():\n" +" logger.debug('Hello, {}', 'world!')\n" +"\n" +"if __name__ == '__main__':\n" +" logging.basicConfig(level=logging.DEBUG)\n" +" main()" +msgstr "" + #: howto/logging-cookbook.rst:1762 msgid "" "The above script should log the message ``Hello, world!`` when run with " @@ -995,6 +2319,10 @@ msgid "" "would do simply by adding new packages or modules and doing ::" msgstr "" +#: howto/logging-cookbook.rst:1810 +msgid "logger = logging.getLogger(__name__)" +msgstr "" + #: howto/logging-cookbook.rst:1812 msgid "" "at module level). It's probably one too many things to think about. " @@ -1023,6 +2351,18 @@ msgid "" "this::" msgstr "" +#: howto/logging-cookbook.rst:1829 +msgid "" +"old_factory = logging.getLogRecordFactory()\n" +"\n" +"def record_factory(*args, **kwargs):\n" +" record = old_factory(*args, **kwargs)\n" +" record.custom_attribute = 0xdecafbad\n" +" return record\n" +"\n" +"logging.setLogRecordFactory(record_factory)" +msgstr "" + #: howto/logging-cookbook.rst:1838 msgid "" "This pattern allows different libraries to chain factories together, and as " @@ -1048,12 +2388,45 @@ msgid "" "socket is created separately and passed to the handler (as its 'queue')::" msgstr "" +#: howto/logging-cookbook.rst:1859 +msgid "" +"import zmq # using pyzmq, the Python binding for ZeroMQ\n" +"import json # for serializing records portably\n" +"\n" +"ctx = zmq.Context()\n" +"sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value\n" +"sock.bind('tcp://*:5556') # or wherever\n" +"\n" +"class ZeroMQSocketHandler(QueueHandler):\n" +" def enqueue(self, record):\n" +" self.queue.send_json(record.__dict__)\n" +"\n" +"\n" +"handler = ZeroMQSocketHandler(sock)" +msgstr "" + #: howto/logging-cookbook.rst:1874 msgid "" "Of course there are other ways of organizing this, for example passing in " "the data needed by the handler to create the socket::" msgstr "" +#: howto/logging-cookbook.rst:1877 +msgid "" +"class ZeroMQSocketHandler(QueueHandler):\n" +" def __init__(self, uri, socktype=zmq.PUB, ctx=None):\n" +" self.ctx = ctx or zmq.Context()\n" +" socket = zmq.Socket(self.ctx, socktype)\n" +" socket.bind(uri)\n" +" super().__init__(socket)\n" +"\n" +" def enqueue(self, record):\n" +" self.queue.send_json(record.__dict__)\n" +"\n" +" def close(self):\n" +" self.queue.close()" +msgstr "" + #: howto/logging-cookbook.rst:1892 howto/logging-cookbook.rst:1922 msgid "Subclass ``QueueListener``" msgstr "" @@ -1064,6 +2437,22 @@ msgid "" "kinds of queues, for example a ZeroMQ 'subscribe' socket. Here's an example::" msgstr "" +#: howto/logging-cookbook.rst:1897 +msgid "" +"class ZeroMQSocketListener(QueueListener):\n" +" def __init__(self, uri, /, *handlers, **kwargs):\n" +" self.ctx = kwargs.get('ctx') or zmq.Context()\n" +" socket = zmq.Socket(self.ctx, zmq.SUB)\n" +" socket.setsockopt_string(zmq.SUBSCRIBE, '') # subscribe to " +"everything\n" +" socket.connect(uri)\n" +" super().__init__(socket, *handlers, **kwargs)\n" +"\n" +" def dequeue(self):\n" +" msg = self.queue.recv_json()\n" +" return logging.makeLogRecord(msg)" +msgstr "" + #: howto/logging-cookbook.rst:1912 msgid "Subclassing QueueHandler and QueueListener- a ``pynng`` example" msgstr "" @@ -1077,6 +2466,117 @@ msgid "" "``pynng`` installed. Just for variety, we present the listener first." msgstr "" +#: howto/logging-cookbook.rst:1924 +msgid "" +"# listener.py\n" +"import json\n" +"import logging\n" +"import logging.handlers\n" +"\n" +"import pynng\n" +"\n" +"DEFAULT_ADDR = \"tcp://localhost:13232\"\n" +"\n" +"interrupted = False\n" +"\n" +"class NNGSocketListener(logging.handlers.QueueListener):\n" +"\n" +" def __init__(self, uri, /, *handlers, **kwargs):\n" +" # Have a timeout for interruptability, and open a\n" +" # subscriber socket\n" +" socket = pynng.Sub0(listen=uri, recv_timeout=500)\n" +" # The b'' subscription matches all topics\n" +" topics = kwargs.pop('topics', None) or b''\n" +" socket.subscribe(topics)\n" +" # We treat the socket as a queue\n" +" super().__init__(socket, *handlers, **kwargs)\n" +"\n" +" def dequeue(self, block):\n" +" data = None\n" +" # Keep looping while not interrupted and no data received over the\n" +" # socket\n" +" while not interrupted:\n" +" try:\n" +" data = self.queue.recv(block=block)\n" +" break\n" +" except pynng.Timeout:\n" +" pass\n" +" except pynng.Closed: # sometimes happens when you hit Ctrl-C\n" +" break\n" +" if data is None:\n" +" return None\n" +" # Get the logging event sent from a publisher\n" +" event = json.loads(data.decode('utf-8'))\n" +" return logging.makeLogRecord(event)\n" +"\n" +" def enqueue_sentinel(self):\n" +" # Not used in this implementation, as the socket isn't really a\n" +" # queue\n" +" pass\n" +"\n" +"logging.getLogger('pynng').propagate = False\n" +"listener = NNGSocketListener(DEFAULT_ADDR, logging.StreamHandler(), " +"topics=b'')\n" +"listener.start()\n" +"print('Press Ctrl-C to stop.')\n" +"try:\n" +" while True:\n" +" pass\n" +"except KeyboardInterrupt:\n" +" interrupted = True\n" +"finally:\n" +" listener.stop()" +msgstr "" + +#: howto/logging-cookbook.rst:1990 +msgid "" +"# sender.py\n" +"import json\n" +"import logging\n" +"import logging.handlers\n" +"import time\n" +"import random\n" +"\n" +"import pynng\n" +"\n" +"DEFAULT_ADDR = \"tcp://localhost:13232\"\n" +"\n" +"class NNGSocketHandler(logging.handlers.QueueHandler):\n" +"\n" +" def __init__(self, uri):\n" +" socket = pynng.Pub0(dial=uri, send_timeout=500)\n" +" super().__init__(socket)\n" +"\n" +" def enqueue(self, record):\n" +" # Send the record as UTF-8 encoded JSON\n" +" d = dict(record.__dict__)\n" +" data = json.dumps(d)\n" +" self.queue.send(data.encode('utf-8'))\n" +"\n" +" def close(self):\n" +" self.queue.close()\n" +"\n" +"logging.getLogger('pynng').propagate = False\n" +"handler = NNGSocketHandler(DEFAULT_ADDR)\n" +"# Make sure the process ID is in the output\n" +"logging.basicConfig(level=logging.DEBUG,\n" +" handlers=[logging.StreamHandler(), handler],\n" +" format='%(levelname)-8s %(name)10s %(process)6s " +"%(message)s')\n" +"levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,\n" +" logging.CRITICAL)\n" +"logger_names = ('myapp', 'myapp.lib1', 'myapp.lib2')\n" +"msgno = 1\n" +"while True:\n" +" # Just randomly select some loggers and levels and log away\n" +" level = random.choice(levels)\n" +" logger = logging.getLogger(random.choice(logger_names))\n" +" logger.log(level, 'Message no. %5d' % msgno)\n" +" msgno += 1\n" +" delay = random.random() * 2 + 0.5\n" +" time.sleep(delay)" +msgstr "" + #: howto/logging-cookbook.rst:2037 msgid "" "You can run the above two snippets in separate command shells. If we run the " @@ -1084,14 +2584,65 @@ msgid "" "see something like the following. In the first sender shell:" msgstr "" +#: howto/logging-cookbook.rst:2041 +msgid "" +"$ python sender.py\n" +"DEBUG myapp 613 Message no. 1\n" +"WARNING myapp.lib2 613 Message no. 2\n" +"CRITICAL myapp.lib2 613 Message no. 3\n" +"WARNING myapp.lib2 613 Message no. 4\n" +"CRITICAL myapp.lib1 613 Message no. 5\n" +"DEBUG myapp 613 Message no. 6\n" +"CRITICAL myapp.lib1 613 Message no. 7\n" +"INFO myapp.lib1 613 Message no. 8\n" +"(and so on)" +msgstr "" + #: howto/logging-cookbook.rst:2054 msgid "In the second sender shell:" msgstr "" +#: howto/logging-cookbook.rst:2056 +msgid "" +"$ python sender.py\n" +"INFO myapp.lib2 657 Message no. 1\n" +"CRITICAL myapp.lib2 657 Message no. 2\n" +"CRITICAL myapp 657 Message no. 3\n" +"CRITICAL myapp.lib1 657 Message no. 4\n" +"INFO myapp.lib1 657 Message no. 5\n" +"WARNING myapp.lib2 657 Message no. 6\n" +"CRITICAL myapp 657 Message no. 7\n" +"DEBUG myapp.lib1 657 Message no. 8\n" +"(and so on)" +msgstr "" + #: howto/logging-cookbook.rst:2069 msgid "In the listener shell:" msgstr "" +#: howto/logging-cookbook.rst:2071 +msgid "" +"$ python listener.py\n" +"Press Ctrl-C to stop.\n" +"DEBUG myapp 613 Message no. 1\n" +"WARNING myapp.lib2 613 Message no. 2\n" +"INFO myapp.lib2 657 Message no. 1\n" +"CRITICAL myapp.lib2 613 Message no. 3\n" +"CRITICAL myapp.lib2 657 Message no. 2\n" +"CRITICAL myapp 657 Message no. 3\n" +"WARNING myapp.lib2 613 Message no. 4\n" +"CRITICAL myapp.lib1 613 Message no. 5\n" +"CRITICAL myapp.lib1 657 Message no. 4\n" +"INFO myapp.lib1 657 Message no. 5\n" +"DEBUG myapp 613 Message no. 6\n" +"WARNING myapp.lib2 657 Message no. 6\n" +"CRITICAL myapp 657 Message no. 7\n" +"CRITICAL myapp.lib1 613 Message no. 7\n" +"INFO myapp.lib1 613 Message no. 8\n" +"DEBUG myapp.lib1 657 Message no. 8\n" +"(and so on)" +msgstr "" + #: howto/logging-cookbook.rst:2093 msgid "" "As you can see, the logging from the two sender processes is interleaved in " @@ -1110,6 +2661,59 @@ msgid "" "func:`~config.dictConfig` to put the configuration into effect::" msgstr "" +#: howto/logging-cookbook.rst:2104 +msgid "" +"LOGGING = {\n" +" 'version': 1,\n" +" 'disable_existing_loggers': False,\n" +" 'formatters': {\n" +" 'verbose': {\n" +" 'format': '{levelname} {asctime} {module} {process:d} {thread:d} " +"{message}',\n" +" 'style': '{',\n" +" },\n" +" 'simple': {\n" +" 'format': '{levelname} {message}',\n" +" 'style': '{',\n" +" },\n" +" },\n" +" 'filters': {\n" +" 'special': {\n" +" '()': 'project.logging.SpecialFilter',\n" +" 'foo': 'bar',\n" +" },\n" +" },\n" +" 'handlers': {\n" +" 'console': {\n" +" 'level': 'INFO',\n" +" 'class': 'logging.StreamHandler',\n" +" 'formatter': 'simple',\n" +" },\n" +" 'mail_admins': {\n" +" 'level': 'ERROR',\n" +" 'class': 'django.utils.log.AdminEmailHandler',\n" +" 'filters': ['special']\n" +" }\n" +" },\n" +" 'loggers': {\n" +" 'django': {\n" +" 'handlers': ['console'],\n" +" 'propagate': True,\n" +" },\n" +" 'django.request': {\n" +" 'handlers': ['mail_admins'],\n" +" 'level': 'ERROR',\n" +" 'propagate': False,\n" +" },\n" +" 'myproject.custom': {\n" +" 'handlers': ['console', 'mail_admins'],\n" +" 'level': 'INFO',\n" +" 'filters': ['special']\n" +" }\n" +" }\n" +"}" +msgstr "" + #: howto/logging-cookbook.rst:2153 msgid "" "For more information about this configuration, you can see the `relevant " @@ -1127,11 +2731,54 @@ msgid "" "following runnable script, which shows gzip compression of the log file::" msgstr "" +#: howto/logging-cookbook.rst:2165 +msgid "" +"import gzip\n" +"import logging\n" +"import logging.handlers\n" +"import os\n" +"import shutil\n" +"\n" +"def namer(name):\n" +" return name + \".gz\"\n" +"\n" +"def rotator(source, dest):\n" +" with open(source, 'rb') as f_in:\n" +" with gzip.open(dest, 'wb') as f_out:\n" +" shutil.copyfileobj(f_in, f_out)\n" +" os.remove(source)\n" +"\n" +"\n" +"rh = logging.handlers.RotatingFileHandler('rotated.log', maxBytes=128, " +"backupCount=5)\n" +"rh.rotator = rotator\n" +"rh.namer = namer\n" +"\n" +"root = logging.getLogger()\n" +"root.setLevel(logging.INFO)\n" +"root.addHandler(rh)\n" +"f = logging.Formatter('%(asctime)s %(message)s')\n" +"rh.setFormatter(f)\n" +"for i in range(1000):\n" +" root.info(f'Message no. {i + 1}')" +msgstr "" + #: howto/logging-cookbook.rst:2193 msgid "" "After running this, you will see six new files, five of which are compressed:" msgstr "" +#: howto/logging-cookbook.rst:2195 +msgid "" +"$ ls rotated.log*\n" +"rotated.log rotated.log.2.gz rotated.log.4.gz\n" +"rotated.log.1.gz rotated.log.3.gz rotated.log.5.gz\n" +"$ zcat rotated.log.1.gz\n" +"2023-01-20 02:28:17,767 Message no. 996\n" +"2023-01-20 02:28:17,767 Message no. 997\n" +"2023-01-20 02:28:17,767 Message no. 998" +msgstr "" + #: howto/logging-cookbook.rst:2206 msgid "A more elaborate multiprocessing example" msgstr "" @@ -1163,6 +2810,229 @@ msgid "" "works::" msgstr "" +#: howto/logging-cookbook.rst:2226 +msgid "" +"import logging\n" +"import logging.config\n" +"import logging.handlers\n" +"from multiprocessing import Process, Queue, Event, current_process\n" +"import os\n" +"import random\n" +"import time\n" +"\n" +"class MyHandler:\n" +" \"\"\"\n" +" A simple handler for logging events. It runs in the listener process " +"and\n" +" dispatches events to loggers based on the name in the received record,\n" +" which then get dispatched, by the logging system, to the handlers\n" +" configured for those loggers.\n" +" \"\"\"\n" +"\n" +" def handle(self, record):\n" +" if record.name == \"root\":\n" +" logger = logging.getLogger()\n" +" else:\n" +" logger = logging.getLogger(record.name)\n" +"\n" +" if logger.isEnabledFor(record.levelno):\n" +" # The process name is transformed just to show that it's the " +"listener\n" +" # doing the logging to files and console\n" +" record.processName = '%s (for %s)' % (current_process().name, " +"record.processName)\n" +" logger.handle(record)\n" +"\n" +"def listener_process(q, stop_event, config):\n" +" \"\"\"\n" +" This could be done in the main process, but is just done in a separate\n" +" process for illustrative purposes.\n" +"\n" +" This initialises logging according to the specified configuration,\n" +" starts the listener and waits for the main process to signal completion\n" +" via the event. The listener is then stopped, and the process exits.\n" +" \"\"\"\n" +" logging.config.dictConfig(config)\n" +" listener = logging.handlers.QueueListener(q, MyHandler())\n" +" listener.start()\n" +" if os.name == 'posix':\n" +" # On POSIX, the setup logger will have been configured in the\n" +" # parent process, but should have been disabled following the\n" +" # dictConfig call.\n" +" # On Windows, since fork isn't used, the setup logger won't\n" +" # exist in the child, so it would be created and the message\n" +" # would appear - hence the \"if posix\" clause.\n" +" logger = logging.getLogger('setup')\n" +" logger.critical('Should not appear, because of disabled " +"logger ...')\n" +" stop_event.wait()\n" +" listener.stop()\n" +"\n" +"def worker_process(config):\n" +" \"\"\"\n" +" A number of these are spawned for the purpose of illustration. In\n" +" practice, they could be a heterogeneous bunch of processes rather than\n" +" ones which are identical to each other.\n" +"\n" +" This initialises logging according to the specified configuration,\n" +" and logs a hundred messages with random levels to randomly selected\n" +" loggers.\n" +"\n" +" A small sleep is added to allow other processes a chance to run. This\n" +" is not strictly needed, but it mixes the output from the different\n" +" processes a bit more than if it's left out.\n" +" \"\"\"\n" +" logging.config.dictConfig(config)\n" +" levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,\n" +" logging.CRITICAL]\n" +" loggers = ['foo', 'foo.bar', 'foo.bar.baz',\n" +" 'spam', 'spam.ham', 'spam.ham.eggs']\n" +" if os.name == 'posix':\n" +" # On POSIX, the setup logger will have been configured in the\n" +" # parent process, but should have been disabled following the\n" +" # dictConfig call.\n" +" # On Windows, since fork isn't used, the setup logger won't\n" +" # exist in the child, so it would be created and the message\n" +" # would appear - hence the \"if posix\" clause.\n" +" logger = logging.getLogger('setup')\n" +" logger.critical('Should not appear, because of disabled " +"logger ...')\n" +" for i in range(100):\n" +" lvl = random.choice(levels)\n" +" logger = logging.getLogger(random.choice(loggers))\n" +" logger.log(lvl, 'Message no. %d', i)\n" +" time.sleep(0.01)\n" +"\n" +"def main():\n" +" q = Queue()\n" +" # The main process gets a simple configuration which prints to the " +"console.\n" +" config_initial = {\n" +" 'version': 1,\n" +" 'handlers': {\n" +" 'console': {\n" +" 'class': 'logging.StreamHandler',\n" +" 'level': 'INFO'\n" +" }\n" +" },\n" +" 'root': {\n" +" 'handlers': ['console'],\n" +" 'level': 'DEBUG'\n" +" }\n" +" }\n" +" # The worker process configuration is just a QueueHandler attached to " +"the\n" +" # root logger, which allows all messages to be sent to the queue.\n" +" # We disable existing loggers to disable the \"setup\" logger used in " +"the\n" +" # parent process. This is needed on POSIX because the logger will\n" +" # be there in the child following a fork().\n" +" config_worker = {\n" +" 'version': 1,\n" +" 'disable_existing_loggers': True,\n" +" 'handlers': {\n" +" 'queue': {\n" +" 'class': 'logging.handlers.QueueHandler',\n" +" 'queue': q\n" +" }\n" +" },\n" +" 'root': {\n" +" 'handlers': ['queue'],\n" +" 'level': 'DEBUG'\n" +" }\n" +" }\n" +" # The listener process configuration shows that the full flexibility of\n" +" # logging configuration is available to dispatch events to handlers " +"however\n" +" # you want.\n" +" # We disable existing loggers to disable the \"setup\" logger used in " +"the\n" +" # parent process. This is needed on POSIX because the logger will\n" +" # be there in the child following a fork().\n" +" config_listener = {\n" +" 'version': 1,\n" +" 'disable_existing_loggers': True,\n" +" 'formatters': {\n" +" 'detailed': {\n" +" 'class': 'logging.Formatter',\n" +" 'format': '%(asctime)s %(name)-15s %(levelname)-8s " +"%(processName)-10s %(message)s'\n" +" },\n" +" 'simple': {\n" +" 'class': 'logging.Formatter',\n" +" 'format': '%(name)-15s %(levelname)-8s %(processName)-10s " +"%(message)s'\n" +" }\n" +" },\n" +" 'handlers': {\n" +" 'console': {\n" +" 'class': 'logging.StreamHandler',\n" +" 'formatter': 'simple',\n" +" 'level': 'INFO'\n" +" },\n" +" 'file': {\n" +" 'class': 'logging.FileHandler',\n" +" 'filename': 'mplog.log',\n" +" 'mode': 'w',\n" +" 'formatter': 'detailed'\n" +" },\n" +" 'foofile': {\n" +" 'class': 'logging.FileHandler',\n" +" 'filename': 'mplog-foo.log',\n" +" 'mode': 'w',\n" +" 'formatter': 'detailed'\n" +" },\n" +" 'errors': {\n" +" 'class': 'logging.FileHandler',\n" +" 'filename': 'mplog-errors.log',\n" +" 'mode': 'w',\n" +" 'formatter': 'detailed',\n" +" 'level': 'ERROR'\n" +" }\n" +" },\n" +" 'loggers': {\n" +" 'foo': {\n" +" 'handlers': ['foofile']\n" +" }\n" +" },\n" +" 'root': {\n" +" 'handlers': ['console', 'file', 'errors'],\n" +" 'level': 'DEBUG'\n" +" }\n" +" }\n" +" # Log some initial events, just to show that logging in the parent " +"works\n" +" # normally.\n" +" logging.config.dictConfig(config_initial)\n" +" logger = logging.getLogger('setup')\n" +" logger.info('About to create workers ...')\n" +" workers = []\n" +" for i in range(5):\n" +" wp = Process(target=worker_process, name='worker %d' % (i + 1),\n" +" args=(config_worker,))\n" +" workers.append(wp)\n" +" wp.start()\n" +" logger.info('Started worker: %s', wp.name)\n" +" logger.info('About to create listener ...')\n" +" stop_event = Event()\n" +" lp = Process(target=listener_process, name='listener',\n" +" args=(q, stop_event, config_listener))\n" +" lp.start()\n" +" logger.info('Started listener')\n" +" # We now hang around for the workers to finish their work.\n" +" for wp in workers:\n" +" wp.join()\n" +" # Workers all done, listening can now stop.\n" +" # Logging in the parent still works normally.\n" +" logger.info('Telling listener to stop ...')\n" +" stop_event.set()\n" +" lp.join()\n" +" logger.info('All done.')\n" +"\n" +"if __name__ == '__main__':\n" +" main()" +msgstr "" + #: howto/logging-cookbook.rst:2435 msgid "Inserting a BOM into messages sent to a SysLogHandler" msgstr "" @@ -1199,6 +3069,10 @@ msgid "" "handlers.SysLogHandler` instance, with a format string such as::" msgstr "" +#: howto/logging-cookbook.rst:2459 +msgid "'ASCII section\\ufeffUnicode section'" +msgstr "" + #: howto/logging-cookbook.rst:2461 msgid "" "The Unicode code point U+FEFF, when encoded using UTF-8, will be encoded as " @@ -1244,10 +3118,35 @@ msgid "" "machine-parseable manner::" msgstr "" +#: howto/logging-cookbook.rst:2489 +msgid "" +"import json\n" +"import logging\n" +"\n" +"class StructuredMessage:\n" +" def __init__(self, message, /, **kwargs):\n" +" self.message = message\n" +" self.kwargs = kwargs\n" +"\n" +" def __str__(self):\n" +" return '%s >>> %s' % (self.message, json.dumps(self.kwargs))\n" +"\n" +"_ = StructuredMessage # optional, to improve readability\n" +"\n" +"logging.basicConfig(level=logging.INFO, format='%(message)s')\n" +"logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456))" +msgstr "" + #: howto/logging-cookbook.rst:2505 msgid "If the above script is run, it prints:" msgstr "" +#: howto/logging-cookbook.rst:2507 +msgid "" +"message 1 >>> {\"fnum\": 123.456, \"num\": 123, \"bar\": \"baz\", \"foo\": " +"\"bar\"}" +msgstr "" + #: howto/logging-cookbook.rst:2511 howto/logging-cookbook.rst:2553 msgid "" "Note that the order of items might be different according to the version of " @@ -1260,10 +3159,47 @@ msgid "" "as in the following complete example::" msgstr "" +#: howto/logging-cookbook.rst:2517 +msgid "" +"import json\n" +"import logging\n" +"\n" +"\n" +"class Encoder(json.JSONEncoder):\n" +" def default(self, o):\n" +" if isinstance(o, set):\n" +" return tuple(o)\n" +" elif isinstance(o, str):\n" +" return o.encode('unicode_escape').decode('ascii')\n" +" return super().default(o)\n" +"\n" +"class StructuredMessage:\n" +" def __init__(self, message, /, **kwargs):\n" +" self.message = message\n" +" self.kwargs = kwargs\n" +"\n" +" def __str__(self):\n" +" s = Encoder().encode(self.kwargs)\n" +" return '%s >>> %s' % (self.message, s)\n" +"\n" +"_ = StructuredMessage # optional, to improve readability\n" +"\n" +"def main():\n" +" logging.basicConfig(level=logging.INFO, format='%(message)s')\n" +" logging.info(_('message 1', set_value={1, 2, 3}, snowman='\\u2603'))\n" +"\n" +"if __name__ == '__main__':\n" +" main()" +msgstr "" + #: howto/logging-cookbook.rst:2547 msgid "When the above script is run, it prints:" msgstr "" +#: howto/logging-cookbook.rst:2549 +msgid "message 1 >>> {\"snowman\": \"\\u2603\", \"set_value\": [1, 2, 3]}" +msgstr "" + #: howto/logging-cookbook.rst:2562 msgid "Customizing handlers with :func:`dictConfig`" msgstr "" @@ -1278,12 +3214,55 @@ msgid "" "customize handler creation using a plain function such as::" msgstr "" +#: howto/logging-cookbook.rst:2571 +msgid "" +"def owned_file_handler(filename, mode='a', encoding=None, owner=None):\n" +" if owner:\n" +" if not os.path.exists(filename):\n" +" open(filename, 'a').close()\n" +" shutil.chown(filename, *owner)\n" +" return logging.FileHandler(filename, mode, encoding)" +msgstr "" + #: howto/logging-cookbook.rst:2578 msgid "" "You can then specify, in a logging configuration passed to :func:" "`dictConfig`, that a logging handler be created by calling this function::" msgstr "" +#: howto/logging-cookbook.rst:2581 +msgid "" +"LOGGING = {\n" +" 'version': 1,\n" +" 'disable_existing_loggers': False,\n" +" 'formatters': {\n" +" 'default': {\n" +" 'format': '%(asctime)s %(levelname)s %(name)s %(message)s'\n" +" },\n" +" },\n" +" 'handlers': {\n" +" 'file':{\n" +" # The values below are popped from this dictionary and\n" +" # used to create the handler, set the handler's level and\n" +" # its formatter.\n" +" '()': owned_file_handler,\n" +" 'level':'DEBUG',\n" +" 'formatter': 'default',\n" +" # The values below are passed to the handler creator callable\n" +" # as keyword arguments.\n" +" 'owner': ['pulse', 'pulse'],\n" +" 'filename': 'chowntest.log',\n" +" 'mode': 'w',\n" +" 'encoding': 'utf-8',\n" +" },\n" +" },\n" +" 'root': {\n" +" 'handlers': ['file'],\n" +" 'level': 'DEBUG',\n" +" },\n" +"}" +msgstr "" + #: howto/logging-cookbook.rst:2611 msgid "" "In this example I am setting the ownership using the ``pulse`` user and " @@ -1291,10 +3270,65 @@ msgid "" "working script, ``chowntest.py``::" msgstr "" +#: howto/logging-cookbook.rst:2615 +msgid "" +"import logging, logging.config, os, shutil\n" +"\n" +"def owned_file_handler(filename, mode='a', encoding=None, owner=None):\n" +" if owner:\n" +" if not os.path.exists(filename):\n" +" open(filename, 'a').close()\n" +" shutil.chown(filename, *owner)\n" +" return logging.FileHandler(filename, mode, encoding)\n" +"\n" +"LOGGING = {\n" +" 'version': 1,\n" +" 'disable_existing_loggers': False,\n" +" 'formatters': {\n" +" 'default': {\n" +" 'format': '%(asctime)s %(levelname)s %(name)s %(message)s'\n" +" },\n" +" },\n" +" 'handlers': {\n" +" 'file':{\n" +" # The values below are popped from this dictionary and\n" +" # used to create the handler, set the handler's level and\n" +" # its formatter.\n" +" '()': owned_file_handler,\n" +" 'level':'DEBUG',\n" +" 'formatter': 'default',\n" +" # The values below are passed to the handler creator callable\n" +" # as keyword arguments.\n" +" 'owner': ['pulse', 'pulse'],\n" +" 'filename': 'chowntest.log',\n" +" 'mode': 'w',\n" +" 'encoding': 'utf-8',\n" +" },\n" +" },\n" +" 'root': {\n" +" 'handlers': ['file'],\n" +" 'level': 'DEBUG',\n" +" },\n" +"}\n" +"\n" +"logging.config.dictConfig(LOGGING)\n" +"logger = logging.getLogger('mylogger')\n" +"logger.debug('A debug message')" +msgstr "" + #: howto/logging-cookbook.rst:2658 msgid "To run this, you will probably need to run as ``root``:" msgstr "" +#: howto/logging-cookbook.rst:2660 +msgid "" +"$ sudo python3.3 chowntest.py\n" +"$ cat chowntest.log\n" +"2013-11-05 09:34:51,128 DEBUG mylogger A debug message\n" +"$ ls -l chowntest.log\n" +"-rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log" +msgstr "" + #: howto/logging-cookbook.rst:2668 msgid "" "Note that this example uses Python 3.3 because that's where :func:`shutil." @@ -1310,10 +3344,18 @@ msgid "" "somewhere in your project. Instead of the line in the configuration::" msgstr "" +#: howto/logging-cookbook.rst:2677 +msgid "'()': owned_file_handler," +msgstr "" + #: howto/logging-cookbook.rst:2679 msgid "you could use e.g.::" msgstr "" +#: howto/logging-cookbook.rst:2681 +msgid "'()': 'ext://project.util.owned_file_handler'," +msgstr "" + #: howto/logging-cookbook.rst:2683 msgid "" "where ``project.util`` can be replaced with the actual name of the package " @@ -1438,10 +3480,33 @@ msgid "" "`str.format`::" msgstr "" +#: howto/logging-cookbook.rst:2790 +msgid "" +">>> __ = BraceMessage\n" +">>> print(__('Message with {0} {1}', 2, 'placeholders'))\n" +"Message with 2 placeholders\n" +">>> class Point: pass\n" +"...\n" +">>> p = Point()\n" +">>> p.x = 0.5\n" +">>> p.y = 0.5\n" +">>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', " +"point=p))\n" +"Message with coordinates: (0.50, 0.50)" +msgstr "" + #: howto/logging-cookbook.rst:2801 msgid "Secondly, formatting with :class:`string.Template`::" msgstr "" +#: howto/logging-cookbook.rst:2803 +msgid "" +">>> __ = DollarMessage\n" +">>> print(__('Message with $num $what', num=2, what='placeholders'))\n" +"Message with 2 placeholders\n" +">>>" +msgstr "" + #: howto/logging-cookbook.rst:2808 msgid "" "One thing to note is that you pay no significant performance penalty with " @@ -1473,6 +3538,51 @@ msgid "" "complete example::" msgstr "" +#: howto/logging-cookbook.rst:2835 +msgid "" +"import logging\n" +"import logging.config\n" +"import sys\n" +"\n" +"class MyFilter(logging.Filter):\n" +" def __init__(self, param=None):\n" +" self.param = param\n" +"\n" +" def filter(self, record):\n" +" if self.param is None:\n" +" allow = True\n" +" else:\n" +" allow = self.param not in record.msg\n" +" if allow:\n" +" record.msg = 'changed: ' + record.msg\n" +" return allow\n" +"\n" +"LOGGING = {\n" +" 'version': 1,\n" +" 'filters': {\n" +" 'myfilter': {\n" +" '()': MyFilter,\n" +" 'param': 'noshow',\n" +" }\n" +" },\n" +" 'handlers': {\n" +" 'console': {\n" +" 'class': 'logging.StreamHandler',\n" +" 'filters': ['myfilter']\n" +" }\n" +" },\n" +" 'root': {\n" +" 'level': 'DEBUG',\n" +" 'handlers': ['console']\n" +" },\n" +"}\n" +"\n" +"if __name__ == '__main__':\n" +" logging.config.dictConfig(LOGGING)\n" +" logging.debug('hello')\n" +" logging.debug('hello - noshow')" +msgstr "" + #: howto/logging-cookbook.rst:2877 msgid "" "This example shows how you can pass configuration data to the callable which " @@ -1480,6 +3590,10 @@ msgid "" "above script will print:" msgstr "" +#: howto/logging-cookbook.rst:2881 +msgid "changed: hello" +msgstr "" + #: howto/logging-cookbook.rst:2885 msgid "which shows that the filter is working as configured." msgstr "" @@ -1519,10 +3633,58 @@ msgid "" "formatter class, as shown in the following example::" msgstr "" +#: howto/logging-cookbook.rst:2912 +msgid "" +"import logging\n" +"\n" +"class OneLineExceptionFormatter(logging.Formatter):\n" +" def formatException(self, exc_info):\n" +" \"\"\"\n" +" Format an exception so that it prints on a single line.\n" +" \"\"\"\n" +" result = super().formatException(exc_info)\n" +" return repr(result) # or format into one line however you want to\n" +"\n" +" def format(self, record):\n" +" s = super().format(record)\n" +" if record.exc_text:\n" +" s = s.replace('\\n', '') + '|'\n" +" return s\n" +"\n" +"def configure_logging():\n" +" fh = logging.FileHandler('output.txt', 'w')\n" +" f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|',\n" +" '%d/%m/%Y %H:%M:%S')\n" +" fh.setFormatter(f)\n" +" root = logging.getLogger()\n" +" root.setLevel(logging.DEBUG)\n" +" root.addHandler(fh)\n" +"\n" +"def main():\n" +" configure_logging()\n" +" logging.info('Sample message')\n" +" try:\n" +" x = 1 / 0\n" +" except ZeroDivisionError as e:\n" +" logging.exception('ZeroDivisionError: %s', e)\n" +"\n" +"if __name__ == '__main__':\n" +" main()" +msgstr "" + #: howto/logging-cookbook.rst:2948 msgid "When run, this produces a file with exactly two lines:" msgstr "" +#: howto/logging-cookbook.rst:2950 +msgid "" +"28/01/2015 07:21:23|INFO|Sample message|\n" +"28/01/2015 07:21:23|ERROR|ZeroDivisionError: integer division or modulo by " +"zero|'Traceback (most recent call last):\\n File \"logtest7.py\", line 30, " +"in main\\n x = 1 / 0\\nZeroDivisionError: integer division or modulo by " +"zero'|" +msgstr "" + #: howto/logging-cookbook.rst:2955 msgid "" "While the above treatment is simplistic, it points the way to how exception " @@ -1551,6 +3713,38 @@ msgid "" "approach, which assumes that the ``espeak`` TTS package is available::" msgstr "" +#: howto/logging-cookbook.rst:2977 +msgid "" +"import logging\n" +"import subprocess\n" +"import sys\n" +"\n" +"class TTSHandler(logging.Handler):\n" +" def emit(self, record):\n" +" msg = self.format(record)\n" +" # Speak slowly in a female English voice\n" +" cmd = ['espeak', '-s150', '-ven+f3', msg]\n" +" p = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n" +" stderr=subprocess.STDOUT)\n" +" # wait for the program to finish\n" +" p.communicate()\n" +"\n" +"def configure_logging():\n" +" h = TTSHandler()\n" +" root = logging.getLogger()\n" +" root.addHandler(h)\n" +" # the default formatter just returns the message\n" +" root.setLevel(logging.DEBUG)\n" +"\n" +"def main():\n" +" logging.info('Hello')\n" +" logging.debug('Goodbye')\n" +"\n" +"if __name__ == '__main__':\n" +" configure_logging()\n" +" sys.exit(main())" +msgstr "" + #: howto/logging-cookbook.rst:3006 msgid "" "When run, this script should say \"Hello\" and then \"Goodbye\" in a female " @@ -1616,10 +3810,105 @@ msgstr "" msgid "Here's the script::" msgstr "" +#: howto/logging-cookbook.rst:3051 +msgid "" +"import logging\n" +"from logging.handlers import MemoryHandler\n" +"import sys\n" +"\n" +"logger = logging.getLogger(__name__)\n" +"logger.addHandler(logging.NullHandler())\n" +"\n" +"def log_if_errors(logger, target_handler=None, flush_level=None, " +"capacity=None):\n" +" if target_handler is None:\n" +" target_handler = logging.StreamHandler()\n" +" if flush_level is None:\n" +" flush_level = logging.ERROR\n" +" if capacity is None:\n" +" capacity = 100\n" +" handler = MemoryHandler(capacity, flushLevel=flush_level, " +"target=target_handler)\n" +"\n" +" def decorator(fn):\n" +" def wrapper(*args, **kwargs):\n" +" logger.addHandler(handler)\n" +" try:\n" +" return fn(*args, **kwargs)\n" +" except Exception:\n" +" logger.exception('call failed')\n" +" raise\n" +" finally:\n" +" super(MemoryHandler, handler).flush()\n" +" logger.removeHandler(handler)\n" +" return wrapper\n" +"\n" +" return decorator\n" +"\n" +"def write_line(s):\n" +" sys.stderr.write('%s\\n' % s)\n" +"\n" +"def foo(fail=False):\n" +" write_line('about to log at DEBUG ...')\n" +" logger.debug('Actually logged at DEBUG')\n" +" write_line('about to log at INFO ...')\n" +" logger.info('Actually logged at INFO')\n" +" write_line('about to log at WARNING ...')\n" +" logger.warning('Actually logged at WARNING')\n" +" if fail:\n" +" write_line('about to log at ERROR ...')\n" +" logger.error('Actually logged at ERROR')\n" +" write_line('about to log at CRITICAL ...')\n" +" logger.critical('Actually logged at CRITICAL')\n" +" return fail\n" +"\n" +"decorated_foo = log_if_errors(logger)(foo)\n" +"\n" +"if __name__ == '__main__':\n" +" logger.setLevel(logging.DEBUG)\n" +" write_line('Calling undecorated foo with False')\n" +" assert not foo(False)\n" +" write_line('Calling undecorated foo with True')\n" +" assert foo(True)\n" +" write_line('Calling decorated foo with False')\n" +" assert not decorated_foo(False)\n" +" write_line('Calling decorated foo with True')\n" +" assert decorated_foo(True)" +msgstr "" + #: howto/logging-cookbook.rst:3112 msgid "When this script is run, the following output should be observed:" msgstr "" +#: howto/logging-cookbook.rst:3114 +msgid "" +"Calling undecorated foo with False\n" +"about to log at DEBUG ...\n" +"about to log at INFO ...\n" +"about to log at WARNING ...\n" +"Calling undecorated foo with True\n" +"about to log at DEBUG ...\n" +"about to log at INFO ...\n" +"about to log at WARNING ...\n" +"about to log at ERROR ...\n" +"about to log at CRITICAL ...\n" +"Calling decorated foo with False\n" +"about to log at DEBUG ...\n" +"about to log at INFO ...\n" +"about to log at WARNING ...\n" +"Calling decorated foo with True\n" +"about to log at DEBUG ...\n" +"about to log at INFO ...\n" +"about to log at WARNING ...\n" +"about to log at ERROR ...\n" +"Actually logged at DEBUG\n" +"Actually logged at INFO\n" +"Actually logged at WARNING\n" +"Actually logged at ERROR\n" +"about to log at CRITICAL ...\n" +"Actually logged at CRITICAL" +msgstr "" + #: howto/logging-cookbook.rst:3142 msgid "" "As you can see, actual logging output only occurs when an event is logged " @@ -1631,6 +3920,13 @@ msgstr "" msgid "You can of course use the conventional means of decoration::" msgstr "" +#: howto/logging-cookbook.rst:3148 +msgid "" +"@log_if_errors(logger)\n" +"def foo(fail=False):\n" +" ..." +msgstr "" + #: howto/logging-cookbook.rst:3156 msgid "Sending logging messages to email, with buffering" msgstr "" @@ -1646,6 +3942,74 @@ msgid "" "argument to see the required and optional arguments.)" msgstr "" +#: howto/logging-cookbook.rst:3166 +msgid "" +"import logging\n" +"import logging.handlers\n" +"import smtplib\n" +"\n" +"class BufferingSMTPHandler(logging.handlers.BufferingHandler):\n" +" def __init__(self, mailhost, port, username, password, fromaddr, " +"toaddrs,\n" +" subject, capacity):\n" +" logging.handlers.BufferingHandler.__init__(self, capacity)\n" +" self.mailhost = mailhost\n" +" self.mailport = port\n" +" self.username = username\n" +" self.password = password\n" +" self.fromaddr = fromaddr\n" +" if isinstance(toaddrs, str):\n" +" toaddrs = [toaddrs]\n" +" self.toaddrs = toaddrs\n" +" self.subject = subject\n" +" self.setFormatter(logging.Formatter(\"%(asctime)s %(levelname)-5s " +"%(message)s\"))\n" +"\n" +" def flush(self):\n" +" if len(self.buffer) > 0:\n" +" try:\n" +" smtp = smtplib.SMTP(self.mailhost, self.mailport)\n" +" smtp.starttls()\n" +" smtp.login(self.username, self.password)\n" +" msg = \"From: %s\\r\\nTo: %s\\r\\nSubject: %s\\r\\n\\r\\n\" " +"% (self.fromaddr, ','.join(self.toaddrs), self.subject)\n" +" for record in self.buffer:\n" +" s = self.format(record)\n" +" msg = msg + s + \"\\r\\n\"\n" +" smtp.sendmail(self.fromaddr, self.toaddrs, msg)\n" +" smtp.quit()\n" +" except Exception:\n" +" if logging.raiseExceptions:\n" +" raise\n" +" self.buffer = []\n" +"\n" +"if __name__ == '__main__':\n" +" import argparse\n" +"\n" +" ap = argparse.ArgumentParser()\n" +" aa = ap.add_argument\n" +" aa('host', metavar='HOST', help='SMTP server')\n" +" aa('--port', '-p', type=int, default=587, help='SMTP port')\n" +" aa('user', metavar='USER', help='SMTP username')\n" +" aa('password', metavar='PASSWORD', help='SMTP password')\n" +" aa('to', metavar='TO', help='Addressee for emails')\n" +" aa('sender', metavar='SENDER', help='Sender email address')\n" +" aa('--subject', '-s',\n" +" default='Test Logging email from Python logging module (buffering)',\n" +" help='Subject of email')\n" +" options = ap.parse_args()\n" +" logger = logging.getLogger()\n" +" logger.setLevel(logging.DEBUG)\n" +" h = BufferingSMTPHandler(options.host, options.port, options.user,\n" +" options.password, options.sender,\n" +" options.to, options.subject, 10)\n" +" logger.addHandler(h)\n" +" for i in range(102):\n" +" logger.info(\"Info index = %d\", i)\n" +" h.flush()\n" +" h.close()" +msgstr "" + #: howto/logging-cookbook.rst:3230 msgid "" "If you run this script and your SMTP server is correctly set up, you should " @@ -1664,6 +4028,15 @@ msgid "" "class such as ``UTCFormatter``, shown below::" msgstr "" +#: howto/logging-cookbook.rst:3243 +msgid "" +"import logging\n" +"import time\n" +"\n" +"class UTCFormatter(logging.Formatter):\n" +" converter = time.gmtime" +msgstr "" + #: howto/logging-cookbook.rst:3249 msgid "" "and you can then use the ``UTCFormatter`` in your code instead of :class:" @@ -1672,10 +4045,57 @@ msgid "" "the following complete example::" msgstr "" +#: howto/logging-cookbook.rst:3254 +msgid "" +"import logging\n" +"import logging.config\n" +"import time\n" +"\n" +"class UTCFormatter(logging.Formatter):\n" +" converter = time.gmtime\n" +"\n" +"LOGGING = {\n" +" 'version': 1,\n" +" 'disable_existing_loggers': False,\n" +" 'formatters': {\n" +" 'utc': {\n" +" '()': UTCFormatter,\n" +" 'format': '%(asctime)s %(message)s',\n" +" },\n" +" 'local': {\n" +" 'format': '%(asctime)s %(message)s',\n" +" }\n" +" },\n" +" 'handlers': {\n" +" 'console1': {\n" +" 'class': 'logging.StreamHandler',\n" +" 'formatter': 'utc',\n" +" },\n" +" 'console2': {\n" +" 'class': 'logging.StreamHandler',\n" +" 'formatter': 'local',\n" +" },\n" +" },\n" +" 'root': {\n" +" 'handlers': ['console1', 'console2'],\n" +" }\n" +"}\n" +"\n" +"if __name__ == '__main__':\n" +" logging.config.dictConfig(LOGGING)\n" +" logging.warning('The local time is %s', time.asctime())" +msgstr "" + #: howto/logging-cookbook.rst:3292 msgid "When this script is run, it should print something like:" msgstr "" +#: howto/logging-cookbook.rst:3294 +msgid "" +"2015-10-17 12:53:29,501 The local time is Sat Oct 17 13:53:29 2015\n" +"2015-10-17 13:53:29,501 The local time is Sat Oct 17 13:53:29 2015" +msgstr "" + #: howto/logging-cookbook.rst:3299 msgid "" "showing how the time is formatted both as local time and UTC, one for each " @@ -1696,6 +4116,35 @@ msgid "" "scope of the context manager::" msgstr "" +#: howto/logging-cookbook.rst:3315 +msgid "" +"import logging\n" +"import sys\n" +"\n" +"class LoggingContext:\n" +" def __init__(self, logger, level=None, handler=None, close=True):\n" +" self.logger = logger\n" +" self.level = level\n" +" self.handler = handler\n" +" self.close = close\n" +"\n" +" def __enter__(self):\n" +" if self.level is not None:\n" +" self.old_level = self.logger.level\n" +" self.logger.setLevel(self.level)\n" +" if self.handler:\n" +" self.logger.addHandler(self.handler)\n" +"\n" +" def __exit__(self, et, ev, tb):\n" +" if self.level is not None:\n" +" self.logger.setLevel(self.old_level)\n" +" if self.handler:\n" +" self.logger.removeHandler(self.handler)\n" +" if self.handler and self.close:\n" +" self.handler.close()\n" +" # implicit return of None => don't swallow exceptions" +msgstr "" + #: howto/logging-cookbook.rst:3341 msgid "" "If you specify a level value, the logger's level is set to that value in the " @@ -1711,6 +4160,26 @@ msgid "" "above::" msgstr "" +#: howto/logging-cookbook.rst:3350 +msgid "" +"if __name__ == '__main__':\n" +" logger = logging.getLogger('foo')\n" +" logger.addHandler(logging.StreamHandler())\n" +" logger.setLevel(logging.INFO)\n" +" logger.info('1. This should appear just once on stderr.')\n" +" logger.debug('2. This should not appear.')\n" +" with LoggingContext(logger, level=logging.DEBUG):\n" +" logger.debug('3. This should appear once on stderr.')\n" +" logger.debug('4. This should not appear.')\n" +" h = logging.StreamHandler(sys.stdout)\n" +" with LoggingContext(logger, level=logging.DEBUG, handler=h, " +"close=True):\n" +" logger.debug('5. This should appear twice - once on stderr and once " +"on stdout.')\n" +" logger.info('6. This should appear just once on stderr.')\n" +" logger.debug('7. This should not appear.')" +msgstr "" + #: howto/logging-cookbook.rst:3365 msgid "" "We initially set the logger's level to ``INFO``, so message #1 appears and " @@ -1728,16 +4197,41 @@ msgstr "" msgid "If we run the resulting script, the result is as follows:" msgstr "" +#: howto/logging-cookbook.rst:3377 +msgid "" +"$ python logctx.py\n" +"1. This should appear just once on stderr.\n" +"3. This should appear once on stderr.\n" +"5. This should appear twice - once on stderr and once on stdout.\n" +"5. This should appear twice - once on stderr and once on stdout.\n" +"6. This should appear just once on stderr." +msgstr "" + #: howto/logging-cookbook.rst:3386 msgid "" "If we run it again, but pipe ``stderr`` to ``/dev/null``, we see the " "following, which is the only message written to ``stdout``:" msgstr "" +#: howto/logging-cookbook.rst:3389 +msgid "" +"$ python logctx.py 2>/dev/null\n" +"5. This should appear twice - once on stderr and once on stdout." +msgstr "" + #: howto/logging-cookbook.rst:3394 msgid "Once again, but piping ``stdout`` to ``/dev/null``, we get:" msgstr "" +#: howto/logging-cookbook.rst:3396 +msgid "" +"$ python logctx.py >/dev/null\n" +"1. This should appear just once on stderr.\n" +"3. This should appear once on stderr.\n" +"5. This should appear twice - once on stderr and once on stdout.\n" +"6. This should appear just once on stderr." +msgstr "" + #: howto/logging-cookbook.rst:3404 msgid "" "In this case, the message #5 printed to ``stdout`` doesn't appear, as " @@ -1784,26 +4278,142 @@ msgid "" "``logging.INFO``. Here's one way that ``app.py`` could be written::" msgstr "" +#: howto/logging-cookbook.rst:3431 +msgid "" +"import argparse\n" +"import importlib\n" +"import logging\n" +"import os\n" +"import sys\n" +"\n" +"def main(args=None):\n" +" scriptname = os.path.basename(__file__)\n" +" parser = argparse.ArgumentParser(scriptname)\n" +" levels = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')\n" +" parser.add_argument('--log-level', default='INFO', choices=levels)\n" +" subparsers = parser.add_subparsers(dest='command',\n" +" help='Available commands:')\n" +" start_cmd = subparsers.add_parser('start', help='Start a service')\n" +" start_cmd.add_argument('name', metavar='NAME',\n" +" help='Name of service to start')\n" +" stop_cmd = subparsers.add_parser('stop',\n" +" help='Stop one or more services')\n" +" stop_cmd.add_argument('names', metavar='NAME', nargs='+',\n" +" help='Name of service to stop')\n" +" restart_cmd = subparsers.add_parser('restart',\n" +" help='Restart one or more " +"services')\n" +" restart_cmd.add_argument('names', metavar='NAME', nargs='+',\n" +" help='Name of service to restart')\n" +" options = parser.parse_args()\n" +" # the code to dispatch commands could all be in this file. For the " +"purposes\n" +" # of illustration only, we implement each command in a separate module.\n" +" try:\n" +" mod = importlib.import_module(options.command)\n" +" cmd = getattr(mod, 'command')\n" +" except (ImportError, AttributeError):\n" +" print('Unable to find the code for command \\'%s\\'' % options." +"command)\n" +" return 1\n" +" # Could get fancy here and load configuration from file or dictionary\n" +" logging.basicConfig(level=options.log_level,\n" +" format='%(levelname)s %(name)s %(message)s')\n" +" cmd(options)\n" +"\n" +"if __name__ == '__main__':\n" +" sys.exit(main())" +msgstr "" + #: howto/logging-cookbook.rst:3472 msgid "" "And the ``start``, ``stop`` and ``restart`` commands can be implemented in " "separate modules, like so for starting::" msgstr "" +#: howto/logging-cookbook.rst:3475 +msgid "" +"# start.py\n" +"import logging\n" +"\n" +"logger = logging.getLogger(__name__)\n" +"\n" +"def command(options):\n" +" logger.debug('About to start %s', options.name)\n" +" # actually do the command processing here ...\n" +" logger.info('Started the \\'%s\\' service.', options.name)" +msgstr "" + #: howto/logging-cookbook.rst:3485 msgid "and thus for stopping::" msgstr "" +#: howto/logging-cookbook.rst:3487 +msgid "" +"# stop.py\n" +"import logging\n" +"\n" +"logger = logging.getLogger(__name__)\n" +"\n" +"def command(options):\n" +" n = len(options.names)\n" +" if n == 1:\n" +" plural = ''\n" +" services = '\\'%s\\'' % options.names[0]\n" +" else:\n" +" plural = 's'\n" +" services = ', '.join('\\'%s\\'' % name for name in options.names)\n" +" i = services.rfind(', ')\n" +" services = services[:i] + ' and ' + services[i + 2:]\n" +" logger.debug('About to stop %s', services)\n" +" # actually do the command processing here ...\n" +" logger.info('Stopped the %s service%s.', services, plural)" +msgstr "" + #: howto/logging-cookbook.rst:3506 msgid "and similarly for restarting::" msgstr "" +#: howto/logging-cookbook.rst:3508 +msgid "" +"# restart.py\n" +"import logging\n" +"\n" +"logger = logging.getLogger(__name__)\n" +"\n" +"def command(options):\n" +" n = len(options.names)\n" +" if n == 1:\n" +" plural = ''\n" +" services = '\\'%s\\'' % options.names[0]\n" +" else:\n" +" plural = 's'\n" +" services = ', '.join('\\'%s\\'' % name for name in options.names)\n" +" i = services.rfind(', ')\n" +" services = services[:i] + ' and ' + services[i + 2:]\n" +" logger.debug('About to restart %s', services)\n" +" # actually do the command processing here ...\n" +" logger.info('Restarted the %s service%s.', services, plural)" +msgstr "" + #: howto/logging-cookbook.rst:3527 msgid "" "If we run this application with the default log level, we get output like " "this:" msgstr "" +#: howto/logging-cookbook.rst:3529 +msgid "" +"$ python app.py start foo\n" +"INFO start Started the 'foo' service.\n" +"\n" +"$ python app.py stop foo bar\n" +"INFO stop Stopped the 'foo' and 'bar' services.\n" +"\n" +"$ python app.py restart foo bar baz\n" +"INFO restart Restarted the 'foo', 'bar' and 'baz' services." +msgstr "" + #: howto/logging-cookbook.rst:3540 msgid "" "The first word is the logging level, and the second word is the module or " @@ -1816,10 +4426,32 @@ msgid "" "the log. For example, if we want more information:" msgstr "" +#: howto/logging-cookbook.rst:3546 +msgid "" +"$ python app.py --log-level DEBUG start foo\n" +"DEBUG start About to start foo\n" +"INFO start Started the 'foo' service.\n" +"\n" +"$ python app.py --log-level DEBUG stop foo bar\n" +"DEBUG stop About to stop 'foo' and 'bar'\n" +"INFO stop Stopped the 'foo' and 'bar' services.\n" +"\n" +"$ python app.py --log-level DEBUG restart foo bar baz\n" +"DEBUG restart About to restart 'foo', 'bar' and 'baz'\n" +"INFO restart Restarted the 'foo', 'bar' and 'baz' services." +msgstr "" + #: howto/logging-cookbook.rst:3560 msgid "And if we want less:" msgstr "" +#: howto/logging-cookbook.rst:3562 +msgid "" +"$ python app.py --log-level WARNING start foo\n" +"$ python app.py --log-level WARNING stop foo bar\n" +"$ python app.py --log-level WARNING restart foo bar baz" +msgstr "" + #: howto/logging-cookbook.rst:3568 msgid "" "In this case, the commands don't print anything to the console, since " @@ -1863,6 +4495,257 @@ msgid "" "more detailed information." msgstr "" +#: howto/logging-cookbook.rst:3597 +msgid "" +"import datetime\n" +"import logging\n" +"import random\n" +"import sys\n" +"import time\n" +"\n" +"# Deal with minor differences between different Qt packages\n" +"try:\n" +" from PySide6 import QtCore, QtGui, QtWidgets\n" +" Signal = QtCore.Signal\n" +" Slot = QtCore.Slot\n" +"except ImportError:\n" +" try:\n" +" from PyQt6 import QtCore, QtGui, QtWidgets\n" +" Signal = QtCore.pyqtSignal\n" +" Slot = QtCore.pyqtSlot\n" +" except ImportError:\n" +" try:\n" +" from PySide2 import QtCore, QtGui, QtWidgets\n" +" Signal = QtCore.Signal\n" +" Slot = QtCore.Slot\n" +" except ImportError:\n" +" from PyQt5 import QtCore, QtGui, QtWidgets\n" +" Signal = QtCore.pyqtSignal\n" +" Slot = QtCore.pyqtSlot\n" +"\n" +"logger = logging.getLogger(__name__)\n" +"\n" +"\n" +"#\n" +"# Signals need to be contained in a QObject or subclass in order to be " +"correctly\n" +"# initialized.\n" +"#\n" +"class Signaller(QtCore.QObject):\n" +" signal = Signal(str, logging.LogRecord)\n" +"\n" +"#\n" +"# Output to a Qt GUI is only supposed to happen on the main thread. So, " +"this\n" +"# handler is designed to take a slot function which is set up to run in the " +"main\n" +"# thread. In this example, the function takes a string argument which is a\n" +"# formatted log message, and the log record which generated it. The " +"formatted\n" +"# string is just a convenience - you could format a string for output any " +"way\n" +"# you like in the slot function itself.\n" +"#\n" +"# You specify the slot function to do whatever GUI updates you want. The " +"handler\n" +"# doesn't know or care about specific UI elements.\n" +"#\n" +"class QtHandler(logging.Handler):\n" +" def __init__(self, slotfunc, *args, **kwargs):\n" +" super().__init__(*args, **kwargs)\n" +" self.signaller = Signaller()\n" +" self.signaller.signal.connect(slotfunc)\n" +"\n" +" def emit(self, record):\n" +" s = self.format(record)\n" +" self.signaller.signal.emit(s, record)\n" +"\n" +"#\n" +"# This example uses QThreads, which means that the threads at the Python " +"level\n" +"# are named something like \"Dummy-1\". The function below gets the Qt name " +"of the\n" +"# current thread.\n" +"#\n" +"def ctname():\n" +" return QtCore.QThread.currentThread().objectName()\n" +"\n" +"\n" +"#\n" +"# Used to generate random levels for logging.\n" +"#\n" +"LEVELS = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,\n" +" logging.CRITICAL)\n" +"\n" +"#\n" +"# This worker class represents work that is done in a thread separate to " +"the\n" +"# main thread. The way the thread is kicked off to do work is via a button " +"press\n" +"# that connects to a slot in the worker.\n" +"#\n" +"# Because the default threadName value in the LogRecord isn't much use, we " +"add\n" +"# a qThreadName which contains the QThread name as computed above, and pass " +"that\n" +"# value in an \"extra\" dictionary which is used to update the LogRecord " +"with the\n" +"# QThread name.\n" +"#\n" +"# This example worker just outputs messages sequentially, interspersed with\n" +"# random delays of the order of a few seconds.\n" +"#\n" +"class Worker(QtCore.QObject):\n" +" @Slot()\n" +" def start(self):\n" +" extra = {'qThreadName': ctname() }\n" +" logger.debug('Started work', extra=extra)\n" +" i = 1\n" +" # Let the thread run until interrupted. This allows reasonably " +"clean\n" +" # thread termination.\n" +" while not QtCore.QThread.currentThread().isInterruptionRequested():\n" +" delay = 0.5 + random.random() * 2\n" +" time.sleep(delay)\n" +" try:\n" +" if random.random() < 0.1:\n" +" raise ValueError('Exception raised: %d' % i)\n" +" else:\n" +" level = random.choice(LEVELS)\n" +" logger.log(level, 'Message after delay of %3.1f: %d', " +"delay, i, extra=extra)\n" +" except ValueError as e:\n" +" logger.exception('Failed: %s', e, extra=extra)\n" +" i += 1\n" +"\n" +"#\n" +"# Implement a simple UI for this cookbook example. This contains:\n" +"#\n" +"# * A read-only text edit window which holds formatted log messages\n" +"# * A button to start work and log stuff in a separate thread\n" +"# * A button to log something from the main thread\n" +"# * A button to clear the log window\n" +"#\n" +"class Window(QtWidgets.QWidget):\n" +"\n" +" COLORS = {\n" +" logging.DEBUG: 'black',\n" +" logging.INFO: 'blue',\n" +" logging.WARNING: 'orange',\n" +" logging.ERROR: 'red',\n" +" logging.CRITICAL: 'purple',\n" +" }\n" +"\n" +" def __init__(self, app):\n" +" super().__init__()\n" +" self.app = app\n" +" self.textedit = te = QtWidgets.QPlainTextEdit(self)\n" +" # Set whatever the default monospace font is for the platform\n" +" f = QtGui.QFont('nosuchfont')\n" +" if hasattr(f, 'Monospace'):\n" +" f.setStyleHint(f.Monospace)\n" +" else:\n" +" f.setStyleHint(f.StyleHint.Monospace) # for Qt6\n" +" te.setFont(f)\n" +" te.setReadOnly(True)\n" +" PB = QtWidgets.QPushButton\n" +" self.work_button = PB('Start background work', self)\n" +" self.log_button = PB('Log a message at a random level', self)\n" +" self.clear_button = PB('Clear log window', self)\n" +" self.handler = h = QtHandler(self.update_status)\n" +" # Remember to use qThreadName rather than threadName in the format " +"string.\n" +" fs = '%(asctime)s %(qThreadName)-12s %(levelname)-8s %(message)s'\n" +" formatter = logging.Formatter(fs)\n" +" h.setFormatter(formatter)\n" +" logger.addHandler(h)\n" +" # Set up to terminate the QThread when we exit\n" +" app.aboutToQuit.connect(self.force_quit)\n" +"\n" +" # Lay out all the widgets\n" +" layout = QtWidgets.QVBoxLayout(self)\n" +" layout.addWidget(te)\n" +" layout.addWidget(self.work_button)\n" +" layout.addWidget(self.log_button)\n" +" layout.addWidget(self.clear_button)\n" +" self.setFixedSize(900, 400)\n" +"\n" +" # Connect the non-worker slots and signals\n" +" self.log_button.clicked.connect(self.manual_update)\n" +" self.clear_button.clicked.connect(self.clear_display)\n" +"\n" +" # Start a new worker thread and connect the slots for the worker\n" +" self.start_thread()\n" +" self.work_button.clicked.connect(self.worker.start)\n" +" # Once started, the button should be disabled\n" +" self.work_button.clicked.connect(lambda : self.work_button." +"setEnabled(False))\n" +"\n" +" def start_thread(self):\n" +" self.worker = Worker()\n" +" self.worker_thread = QtCore.QThread()\n" +" self.worker.setObjectName('Worker')\n" +" self.worker_thread.setObjectName('WorkerThread') # for qThreadName\n" +" self.worker.moveToThread(self.worker_thread)\n" +" # This will start an event loop in the worker thread\n" +" self.worker_thread.start()\n" +"\n" +" def kill_thread(self):\n" +" # Just tell the worker to stop, then tell it to quit and wait for " +"that\n" +" # to happen\n" +" self.worker_thread.requestInterruption()\n" +" if self.worker_thread.isRunning():\n" +" self.worker_thread.quit()\n" +" self.worker_thread.wait()\n" +" else:\n" +" print('worker has already exited.')\n" +"\n" +" def force_quit(self):\n" +" # For use when the window is closed\n" +" if self.worker_thread.isRunning():\n" +" self.kill_thread()\n" +"\n" +" # The functions below update the UI and run in the main thread because\n" +" # that's where the slots are set up\n" +"\n" +" @Slot(str, logging.LogRecord)\n" +" def update_status(self, status, record):\n" +" color = self.COLORS.get(record.levelno, 'black')\n" +" s = '
%s
' % (color, status)\n" +" self.textedit.appendHtml(s)\n" +"\n" +" @Slot()\n" +" def manual_update(self):\n" +" # This function uses the formatted message passed in, but also uses\n" +" # information from the record to format the message in an " +"appropriate\n" +" # color according to its severity (level).\n" +" level = random.choice(LEVELS)\n" +" extra = {'qThreadName': ctname() }\n" +" logger.log(level, 'Manually logged!', extra=extra)\n" +"\n" +" @Slot()\n" +" def clear_display(self):\n" +" self.textedit.clear()\n" +"\n" +"\n" +"def main():\n" +" QtCore.QThread.currentThread().setObjectName('MainThread')\n" +" logging.getLogger().setLevel(logging.DEBUG)\n" +" app = QtWidgets.QApplication(sys.argv)\n" +" example = Window(app)\n" +" example.show()\n" +" if hasattr(app, 'exec'):\n" +" rc = app.exec()\n" +" else:\n" +" rc = app.exec_()\n" +" sys.exit(rc)\n" +"\n" +"if __name__=='__main__':\n" +" main()" +msgstr "" + #: howto/logging-cookbook.rst:3829 msgid "Logging to syslog with RFC5424 support" msgstr "" @@ -1884,6 +4767,76 @@ msgid "" "you can do so with a subclassed handler which looks something like this::" msgstr "" +#: howto/logging-cookbook.rst:3842 +msgid "" +"import datetime\n" +"import logging.handlers\n" +"import re\n" +"import socket\n" +"import time\n" +"\n" +"class SysLogHandler5424(logging.handlers.SysLogHandler):\n" +"\n" +" tz_offset = re.compile(r'([+-]\\d{2})(\\d{2})$')\n" +" escaped = re.compile(r'([\\]\"\\\\])')\n" +"\n" +" def __init__(self, *args, **kwargs):\n" +" self.msgid = kwargs.pop('msgid', None)\n" +" self.appname = kwargs.pop('appname', None)\n" +" super().__init__(*args, **kwargs)\n" +"\n" +" def format(self, record):\n" +" version = 1\n" +" asctime = datetime.datetime.fromtimestamp(record.created)." +"isoformat()\n" +" m = self.tz_offset.match(time.strftime('%z'))\n" +" has_offset = False\n" +" if m and time.timezone:\n" +" hrs, mins = m.groups()\n" +" if int(hrs) or int(mins):\n" +" has_offset = True\n" +" if not has_offset:\n" +" asctime += 'Z'\n" +" else:\n" +" asctime += f'{hrs}:{mins}'\n" +" try:\n" +" hostname = socket.gethostname()\n" +" except Exception:\n" +" hostname = '-'\n" +" appname = self.appname or '-'\n" +" procid = record.process\n" +" msgid = '-'\n" +" msg = super().format(record)\n" +" sdata = '-'\n" +" if hasattr(record, 'structured_data'):\n" +" sd = record.structured_data\n" +" # This should be a dict where the keys are SD-ID and the value " +"is a\n" +" # dict mapping PARAM-NAME to PARAM-VALUE (refer to the RFC for " +"what these\n" +" # mean)\n" +" # There's no error checking here - it's purely for illustration, " +"and you\n" +" # can adapt this code for use in production environments\n" +" parts = []\n" +"\n" +" def replacer(m):\n" +" g = m.groups()\n" +" return '\\\\' + g[0]\n" +"\n" +" for sdid, dv in sd.items():\n" +" part = f'[{sdid}'\n" +" for k, v in dv.items():\n" +" s = str(v)\n" +" s = self.escaped.sub(replacer, s)\n" +" part += f' {k}=\"{s}\"'\n" +" part += ']'\n" +" parts.append(part)\n" +" sdata = ''.join(parts)\n" +" return f'{version} {asctime} {hostname} {appname} {procid} {msgid} " +"{sdata} {msg}'" +msgstr "" + #: howto/logging-cookbook.rst:3904 msgid "" "You'll need to be familiar with RFC 5424 to fully understand the above code, " @@ -1893,6 +4846,17 @@ msgid "" "using something like this::" msgstr "" +#: howto/logging-cookbook.rst:3909 +msgid "" +"sd = {\n" +" 'foo@12345': {'bar': 'baz', 'baz': 'bozz', 'fizz': r'buzz'},\n" +" 'foo@54321': {'rab': 'baz', 'zab': 'bozz', 'zzif': r'buzz'}\n" +"}\n" +"extra = {'structured_data': sd}\n" +"i = 1\n" +"logger.debug('Message %d', i, extra=extra)" +msgstr "" + #: howto/logging-cookbook.rst:3918 msgid "How to treat a logger like an output stream" msgstr "" @@ -1905,16 +4869,68 @@ msgid "" "API. Here's a short script illustrating such a class:" msgstr "" +#: howto/logging-cookbook.rst:3925 +msgid "" +"import logging\n" +"\n" +"class LoggerWriter:\n" +" def __init__(self, logger, level):\n" +" self.logger = logger\n" +" self.level = level\n" +"\n" +" def write(self, message):\n" +" if message != '\\n': # avoid printing bare newlines, if you like\n" +" self.logger.log(self.level, message)\n" +"\n" +" def flush(self):\n" +" # doesn't actually do anything, but might be expected of a file-" +"like\n" +" # object - so optional depending on your situation\n" +" pass\n" +"\n" +" def close(self):\n" +" # doesn't actually do anything, but might be expected of a file-" +"like\n" +" # object - so optional depending on your situation. You might want\n" +" # to set a flag so that later calls to write raise an exception\n" +" pass\n" +"\n" +"def main():\n" +" logging.basicConfig(level=logging.DEBUG)\n" +" logger = logging.getLogger('demo')\n" +" info_fp = LoggerWriter(logger, logging.INFO)\n" +" debug_fp = LoggerWriter(logger, logging.DEBUG)\n" +" print('An INFO message', file=info_fp)\n" +" print('A DEBUG message', file=debug_fp)\n" +"\n" +"if __name__ == \"__main__\":\n" +" main()" +msgstr "" + #: howto/logging-cookbook.rst:3960 msgid "When this script is run, it prints" msgstr "" +#: howto/logging-cookbook.rst:3962 +msgid "" +"INFO:demo:An INFO message\n" +"DEBUG:demo:A DEBUG message" +msgstr "" + #: howto/logging-cookbook.rst:3967 msgid "" "You could also use ``LoggerWriter`` to redirect ``sys.stdout`` and ``sys." "stderr`` by doing something like this:" msgstr "" +#: howto/logging-cookbook.rst:3970 +msgid "" +"import sys\n" +"\n" +"sys.stdout = LoggerWriter(logger, logging.INFO)\n" +"sys.stderr = LoggerWriter(logger, logging.WARNING)" +msgstr "" + #: howto/logging-cookbook.rst:3977 msgid "" "You should do this *after* configuring logging for your needs. In the above " @@ -1923,6 +4939,15 @@ msgid "" "Then, you'd get this kind of result:" msgstr "" +#: howto/logging-cookbook.rst:3982 +msgid "" +">>> print('Foo')\n" +"INFO:demo:Foo\n" +">>> print('Bar', file=sys.stderr)\n" +"WARNING:demo:Bar\n" +">>>" +msgstr "" + #: howto/logging-cookbook.rst:3990 msgid "" "Of course, the examples above show output according to the format used by :" @@ -1937,10 +4962,35 @@ msgid "" "with the definition of ``LoggerWriter`` above, if you have the snippet" msgstr "" +#: howto/logging-cookbook.rst:3998 +msgid "" +"sys.stderr = LoggerWriter(logger, logging.WARNING)\n" +"1 / 0" +msgstr "" + #: howto/logging-cookbook.rst:4003 msgid "then running the script results in" msgstr "" +#: howto/logging-cookbook.rst:4005 +msgid "" +"WARNING:demo:Traceback (most recent call last):\n" +"\n" +"WARNING:demo: File \"/home/runner/cookbook-loggerwriter/test.py\", line 53, " +"in \n" +"\n" +"WARNING:demo:\n" +"WARNING:demo:main()\n" +"WARNING:demo: File \"/home/runner/cookbook-loggerwriter/test.py\", line 49, " +"in main\n" +"\n" +"WARNING:demo:\n" +"WARNING:demo:1 / 0\n" +"WARNING:demo:ZeroDivisionError\n" +"WARNING:demo::\n" +"WARNING:demo:division by zero" +msgstr "" + #: howto/logging-cookbook.rst:4021 msgid "" "As you can see, this output isn't ideal. That's because the underlying code " @@ -1951,12 +5001,44 @@ msgid "" "``LoggerWriter``:" msgstr "" +#: howto/logging-cookbook.rst:4027 +msgid "" +"class BufferingLoggerWriter(LoggerWriter):\n" +" def __init__(self, logger, level):\n" +" super().__init__(logger, level)\n" +" self.buffer = ''\n" +"\n" +" def write(self, message):\n" +" if '\\n' not in message:\n" +" self.buffer += message\n" +" else:\n" +" parts = message.split('\\n')\n" +" if self.buffer:\n" +" s = self.buffer + parts.pop(0)\n" +" self.logger.log(self.level, s)\n" +" self.buffer = parts.pop()\n" +" for part in parts:\n" +" self.logger.log(self.level, part)" +msgstr "" + #: howto/logging-cookbook.rst:4046 msgid "" "This just buffers up stuff until a newline is seen, and then logs complete " "lines. With this approach, you get better output:" msgstr "" +#: howto/logging-cookbook.rst:4049 +msgid "" +"WARNING:demo:Traceback (most recent call last):\n" +"WARNING:demo: File \"/home/runner/cookbook-loggerwriter/main.py\", line 55, " +"in \n" +"WARNING:demo: main()\n" +"WARNING:demo: File \"/home/runner/cookbook-loggerwriter/main.py\", line 52, " +"in main\n" +"WARNING:demo: 1/0\n" +"WARNING:demo:ZeroDivisionError: division by zero" +msgstr "" + #: howto/logging-cookbook.rst:4062 msgid "Patterns to avoid" msgstr "" diff --git a/howto/logging.po b/howto/logging.po index de51068cf..b1deac8f3 100644 --- a/howto/logging.po +++ b/howto/logging.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -136,7 +136,7 @@ msgid "" "below (in increasing order of severity):" msgstr "" -#: howto/logging.rst:870 +#: howto/logging.rst:874 msgid "Level" msgstr "" @@ -144,7 +144,7 @@ msgstr "" msgid "When it's used" msgstr "" -#: howto/logging.rst:880 +#: howto/logging.rst:884 msgid "``DEBUG``" msgstr "" @@ -153,7 +153,7 @@ msgid "" "Detailed information, typically of interest only when diagnosing problems." msgstr "" -#: howto/logging.rst:878 +#: howto/logging.rst:882 msgid "``INFO``" msgstr "" @@ -161,7 +161,7 @@ msgstr "" msgid "Confirmation that things are working as expected." msgstr "" -#: howto/logging.rst:876 +#: howto/logging.rst:880 msgid "``WARNING``" msgstr "" @@ -172,7 +172,7 @@ msgid "" "working as expected." msgstr "" -#: howto/logging.rst:874 +#: howto/logging.rst:878 msgid "``ERROR``" msgstr "" @@ -182,7 +182,7 @@ msgid "" "some function." msgstr "" -#: howto/logging.rst:872 +#: howto/logging.rst:876 msgid "``CRITICAL``" msgstr "" @@ -214,10 +214,21 @@ msgstr "" msgid "A very simple example is::" msgstr "" +#: howto/logging.rst:111 +msgid "" +"import logging\n" +"logging.warning('Watch out!') # will print a message to the console\n" +"logging.info('I told you so') # will not print anything" +msgstr "" + #: howto/logging.rst:115 msgid "If you type these lines into a script and run it, you'll see:" msgstr "" +#: howto/logging.rst:117 +msgid "WARNING:root:Watch out!" +msgstr "" + #: howto/logging.rst:121 msgid "" "printed out on the console. The ``INFO`` message doesn't appear because the " @@ -251,6 +262,18 @@ msgid "" "above::" msgstr "" +#: howto/logging.rst:142 +msgid "" +"import logging\n" +"logger = logging.getLogger(__name__)\n" +"logging.basicConfig(filename='example.log', encoding='utf-8', level=logging." +"DEBUG)\n" +"logger.debug('This message should go to the log file')\n" +"logger.info('So should this')\n" +"logger.warning('And this, too')\n" +"logger.error('And non-ASCII stuff, too, like Øresund and Malmö')" +msgstr "" + #: howto/logging.rst:150 msgid "" "The *encoding* argument was added. In earlier Python versions, or if not " @@ -266,6 +289,14 @@ msgid "" "messages:" msgstr "" +#: howto/logging.rst:160 +msgid "" +"DEBUG:__main__:This message should go to the log file\n" +"INFO:__main__:So should this\n" +"WARNING:__main__:And this, too\n" +"ERROR:__main__:And non-ASCII stuff, too, like Øresund and Malmö" +msgstr "" + #: howto/logging.rst:167 msgid "" "This example also shows how you can set the logging level which acts as the " @@ -278,12 +309,20 @@ msgid "" "If you want to set the logging level from a command-line option such as:" msgstr "" +#: howto/logging.rst:173 +msgid "--log=INFO" +msgstr "" + #: howto/logging.rst:177 msgid "" "and you have the value of the parameter passed for ``--log`` in some " "variable *loglevel*, you can use::" msgstr "" +#: howto/logging.rst:180 +msgid "getattr(logging, loglevel.upper())" +msgstr "" + #: howto/logging.rst:182 msgid "" "to get the value which you'll pass to :func:`basicConfig` via the *level* " @@ -291,6 +330,17 @@ msgid "" "the following example::" msgstr "" +#: howto/logging.rst:186 +msgid "" +"# assuming loglevel is bound to the string value obtained from the\n" +"# command line argument. Convert to upper case to allow the user to\n" +"# specify --log=DEBUG or --log=debug\n" +"numeric_level = getattr(logging, loglevel.upper(), None)\n" +"if not isinstance(numeric_level, int):\n" +" raise ValueError('Invalid log level: %s' % loglevel)\n" +"logging.basicConfig(level=numeric_level, ...)" +msgstr "" + #: howto/logging.rst:194 msgid "" "The call to :func:`basicConfig` should come *before* any calls to a logger's " @@ -306,6 +356,12 @@ msgid "" "*filemode* argument, by changing the call in the above example to::" msgstr "" +#: howto/logging.rst:203 +msgid "" +"logging.basicConfig(filename='example.log', filemode='w', level=logging." +"DEBUG)" +msgstr "" + #: howto/logging.rst:205 msgid "" "The output will be the same as before, but the log file is no longer " @@ -322,10 +378,20 @@ msgid "" "and append the variable data as arguments. For example::" msgstr "" +#: howto/logging.rst:215 +msgid "" +"import logging\n" +"logging.warning('%s before you %s', 'Look', 'leap!')" +msgstr "" + #: howto/logging.rst:218 msgid "will display:" msgstr "" +#: howto/logging.rst:220 +msgid "WARNING:root:Look before you leap!" +msgstr "" + #: howto/logging.rst:224 msgid "" "As you can see, merging of variable data into the event description message " @@ -346,10 +412,27 @@ msgid "" "the format you want to use::" msgstr "" +#: howto/logging.rst:238 +msgid "" +"import logging\n" +"logging.basicConfig(format='%(levelname)s:%(message)s', level=logging." +"DEBUG)\n" +"logging.debug('This message should appear on the console')\n" +"logging.info('So should this')\n" +"logging.warning('And this, too')" +msgstr "" + #: howto/logging.rst:244 msgid "which would print:" msgstr "" +#: howto/logging.rst:246 +msgid "" +"DEBUG:This message should appear on the console\n" +"INFO:So should this\n" +"WARNING:And this, too" +msgstr "" + #: howto/logging.rst:252 msgid "" "Notice that the 'root' which appeared in earlier examples has disappeared. " @@ -370,10 +453,21 @@ msgid "" "your format string::" msgstr "" +#: howto/logging.rst:266 +msgid "" +"import logging\n" +"logging.basicConfig(format='%(asctime)s %(message)s')\n" +"logging.warning('is when this event was logged.')" +msgstr "" + #: howto/logging.rst:270 msgid "which should print something like this:" msgstr "" +#: howto/logging.rst:272 +msgid "2010-12-12 11:41:42,612 is when this event was logged." +msgstr "" + #: howto/logging.rst:276 msgid "" "The default format for date/time display (shown above) is like ISO8601 or :" @@ -381,10 +475,22 @@ msgid "" "provide a *datefmt* argument to ``basicConfig``, as in this example::" msgstr "" +#: howto/logging.rst:280 +msgid "" +"import logging\n" +"logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:" +"%M:%S %p')\n" +"logging.warning('is when this event was logged.')" +msgstr "" + #: howto/logging.rst:284 msgid "which would display something like this:" msgstr "" +#: howto/logging.rst:286 +msgid "12/12/2010 11:46:36 AM is when this event was logged." +msgstr "" + #: howto/logging.rst:290 msgid "" "The format of the *datefmt* argument is the same as supported by :func:`time." @@ -473,6 +579,10 @@ msgid "" "logger, in each module which uses logging, named as follows::" msgstr "" +#: howto/logging.rst:342 +msgid "logger = logging.getLogger(__name__)" +msgstr "" + #: howto/logging.rst:344 msgid "" "This means that logger names track the package/module hierarchy, and it's " @@ -515,6 +625,10 @@ msgstr "" msgid "The default format set by :func:`basicConfig` for messages is:" msgstr "" +#: howto/logging.rst:370 +msgid "severity:logger name:message" +msgstr "" + #: howto/logging.rst:374 msgid "" "You can change this by passing a format string to :func:`basicConfig` with " @@ -532,11 +646,11 @@ msgid "" "the following diagram." msgstr "" -#: howto/logging.rst:428 +#: howto/logging.rst:432 msgid "Loggers" msgstr "" -#: howto/logging.rst:430 +#: howto/logging.rst:434 msgid "" ":class:`Logger` objects have a threefold job. First, they expose several " "methods to application code so that applications can log messages at " @@ -546,17 +660,17 @@ msgid "" "handlers." msgstr "" -#: howto/logging.rst:436 +#: howto/logging.rst:440 msgid "" "The most widely used methods on logger objects fall into two categories: " "configuration and message sending." msgstr "" -#: howto/logging.rst:439 +#: howto/logging.rst:443 msgid "These are the most common configuration methods:" msgstr "" -#: howto/logging.rst:441 +#: howto/logging.rst:445 msgid "" ":meth:`Logger.setLevel` specifies the lowest-severity log message a logger " "will handle, where debug is the lowest built-in severity level and critical " @@ -565,32 +679,32 @@ msgid "" "messages and will ignore DEBUG messages." msgstr "" -#: howto/logging.rst:447 +#: howto/logging.rst:451 msgid "" ":meth:`Logger.addHandler` and :meth:`Logger.removeHandler` add and remove " "handler objects from the logger object. Handlers are covered in more detail " "in :ref:`handler-basic`." msgstr "" -#: howto/logging.rst:451 +#: howto/logging.rst:455 msgid "" ":meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove " "filter objects from the logger object. Filters are covered in more detail " "in :ref:`filter`." msgstr "" -#: howto/logging.rst:455 +#: howto/logging.rst:459 msgid "" "You don't need to always call these methods on every logger you create. See " "the last two paragraphs in this section." msgstr "" -#: howto/logging.rst:458 +#: howto/logging.rst:462 msgid "" "With the logger object configured, the following methods create log messages:" msgstr "" -#: howto/logging.rst:460 +#: howto/logging.rst:464 msgid "" ":meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`, :meth:" "`Logger.error`, and :meth:`Logger.critical` all create log records with a " @@ -603,14 +717,14 @@ msgid "" "exception information." msgstr "" -#: howto/logging.rst:470 +#: howto/logging.rst:474 msgid "" ":meth:`Logger.exception` creates a log message similar to :meth:`Logger." "error`. The difference is that :meth:`Logger.exception` dumps a stack trace " "along with it. Call this method only from an exception handler." msgstr "" -#: howto/logging.rst:474 +#: howto/logging.rst:478 msgid "" ":meth:`Logger.log` takes a log level as an explicit argument. This is a " "little more verbose for logging messages than using the log level " @@ -618,7 +732,7 @@ msgid "" "levels." msgstr "" -#: howto/logging.rst:478 +#: howto/logging.rst:482 msgid "" ":func:`getLogger` returns a reference to a logger instance with the " "specified name if it is provided, or ``root`` if not. The names are period-" @@ -630,7 +744,7 @@ msgid "" "descendants of ``foo``." msgstr "" -#: howto/logging.rst:486 +#: howto/logging.rst:490 msgid "" "Loggers have a concept of *effective level*. If a level is not explicitly " "set on a logger, the level of its parent is used instead as its effective " @@ -642,7 +756,7 @@ msgid "" "handlers." msgstr "" -#: howto/logging.rst:494 +#: howto/logging.rst:498 msgid "" "Child loggers propagate messages up to the handlers associated with their " "ancestor loggers. Because of this, it is unnecessary to define and configure " @@ -652,11 +766,11 @@ msgid "" "attribute of a logger to ``False``.)" msgstr "" -#: howto/logging.rst:505 +#: howto/logging.rst:509 msgid "Handlers" msgstr "" -#: howto/logging.rst:507 +#: howto/logging.rst:511 msgid "" ":class:`~logging.Handler` objects are responsible for dispatching the " "appropriate log messages (based on the log messages' severity) to the " @@ -669,14 +783,14 @@ msgid "" "of a specific severity to a specific location." msgstr "" -#: howto/logging.rst:517 +#: howto/logging.rst:521 msgid "" "The standard library includes quite a few handler types (see :ref:`useful-" "handlers`); the tutorials use mainly :class:`StreamHandler` and :class:" "`FileHandler` in its examples." msgstr "" -#: howto/logging.rst:521 +#: howto/logging.rst:525 msgid "" "There are very few methods in a handler for application developers to " "concern themselves with. The only handler methods that seem relevant for " @@ -684,7 +798,7 @@ msgid "" "not creating custom handlers) are the following configuration methods:" msgstr "" -#: howto/logging.rst:526 +#: howto/logging.rst:530 msgid "" "The :meth:`~Handler.setLevel` method, just as in logger objects, specifies " "the lowest severity that will be dispatched to the appropriate destination. " @@ -694,19 +808,19 @@ msgid "" "send on." msgstr "" -#: howto/logging.rst:532 +#: howto/logging.rst:536 msgid "" ":meth:`~Handler.setFormatter` selects a Formatter object for this handler to " "use." msgstr "" -#: howto/logging.rst:535 +#: howto/logging.rst:539 msgid "" ":meth:`~Handler.addFilter` and :meth:`~Handler.removeFilter` respectively " "configure and deconfigure filter objects on handlers." msgstr "" -#: howto/logging.rst:538 +#: howto/logging.rst:542 msgid "" "Application code should not directly instantiate and use instances of :class:" "`Handler`. Instead, the :class:`Handler` class is a base class that defines " @@ -714,11 +828,11 @@ msgid "" "behavior that child classes can use (or override)." msgstr "" -#: howto/logging.rst:545 +#: howto/logging.rst:549 msgid "Formatters" msgstr "" -#: howto/logging.rst:547 +#: howto/logging.rst:551 msgid "" "Formatter objects configure the final order, structure, and contents of the " "log message. Unlike the base :class:`logging.Handler` class, application " @@ -728,20 +842,24 @@ msgid "" "string and a style indicator." msgstr "" -#: howto/logging.rst:556 +#: howto/logging.rst:560 msgid "" "If there is no message format string, the default is to use the raw " "message. If there is no date format string, the default date format is:" msgstr "" #: howto/logging.rst:563 +msgid "%Y-%m-%d %H:%M:%S" +msgstr "" + +#: howto/logging.rst:567 msgid "" "with the milliseconds tacked on at the end. The ``style`` is one of ``'%'``, " "``'{'``, or ``'$'``. If one of these is not specified, then ``'%'`` will be " "used." msgstr "" -#: howto/logging.rst:566 +#: howto/logging.rst:570 msgid "" "If the ``style`` is ``'%'``, the message format string uses ``%()s`` styled string substitution; the possible keys are documented in :" @@ -751,18 +869,22 @@ msgid "" "should conform to what is expected by :meth:`string.Template.substitute`." msgstr "" -#: howto/logging.rst:573 +#: howto/logging.rst:577 msgid "Added the ``style`` parameter." msgstr "" -#: howto/logging.rst:576 +#: howto/logging.rst:580 msgid "" "The following message format string will log the time in a human-readable " "format, the severity of the message, and the contents of the message, in " "that order::" msgstr "" -#: howto/logging.rst:582 +#: howto/logging.rst:584 +msgid "'%(asctime)s - %(levelname)s - %(message)s'" +msgstr "" + +#: howto/logging.rst:586 msgid "" "Formatters use a user-configurable function to convert the creation time of " "a record to a tuple. By default, :func:`time.localtime` is used; to change " @@ -773,68 +895,167 @@ msgid "" "in the Formatter class (to ``time.gmtime`` for GMT display)." msgstr "" -#: howto/logging.rst:592 +#: howto/logging.rst:596 msgid "Configuring Logging" msgstr "" -#: howto/logging.rst:596 +#: howto/logging.rst:600 msgid "Programmers can configure logging in three ways:" msgstr "" -#: howto/logging.rst:598 +#: howto/logging.rst:602 msgid "" "Creating loggers, handlers, and formatters explicitly using Python code that " "calls the configuration methods listed above." msgstr "" -#: howto/logging.rst:600 +#: howto/logging.rst:604 msgid "" "Creating a logging config file and reading it using the :func:`fileConfig` " "function." msgstr "" -#: howto/logging.rst:602 +#: howto/logging.rst:606 msgid "" "Creating a dictionary of configuration information and passing it to the :" "func:`dictConfig` function." msgstr "" -#: howto/logging.rst:605 +#: howto/logging.rst:609 msgid "" "For the reference documentation on the last two options, see :ref:`logging-" "config-api`. The following example configures a very simple logger, a " "console handler, and a simple formatter using Python code::" msgstr "" -#: howto/logging.rst:635 +#: howto/logging.rst:613 +msgid "" +"import logging\n" +"\n" +"# create logger\n" +"logger = logging.getLogger('simple_example')\n" +"logger.setLevel(logging.DEBUG)\n" +"\n" +"# create console handler and set level to debug\n" +"ch = logging.StreamHandler()\n" +"ch.setLevel(logging.DEBUG)\n" +"\n" +"# create formatter\n" +"formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - " +"%(message)s')\n" +"\n" +"# add formatter to ch\n" +"ch.setFormatter(formatter)\n" +"\n" +"# add ch to logger\n" +"logger.addHandler(ch)\n" +"\n" +"# 'application' code\n" +"logger.debug('debug message')\n" +"logger.info('info message')\n" +"logger.warning('warn message')\n" +"logger.error('error message')\n" +"logger.critical('critical message')" +msgstr "" + +#: howto/logging.rst:639 msgid "" "Running this module from the command line produces the following output:" msgstr "" -#: howto/logging.rst:646 +#: howto/logging.rst:641 +msgid "" +"$ python simple_logging_module.py\n" +"2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message\n" +"2005-03-19 15:10:26,620 - simple_example - INFO - info message\n" +"2005-03-19 15:10:26,695 - simple_example - WARNING - warn message\n" +"2005-03-19 15:10:26,697 - simple_example - ERROR - error message\n" +"2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message" +msgstr "" + +#: howto/logging.rst:650 msgid "" "The following Python module creates a logger, handler, and formatter nearly " "identical to those in the example listed above, with the only difference " "being the names of the objects::" msgstr "" -#: howto/logging.rst:665 +#: howto/logging.rst:654 +msgid "" +"import logging\n" +"import logging.config\n" +"\n" +"logging.config.fileConfig('logging.conf')\n" +"\n" +"# create logger\n" +"logger = logging.getLogger('simpleExample')\n" +"\n" +"# 'application' code\n" +"logger.debug('debug message')\n" +"logger.info('info message')\n" +"logger.warning('warn message')\n" +"logger.error('error message')\n" +"logger.critical('critical message')" +msgstr "" + +#: howto/logging.rst:669 msgid "Here is the logging.conf file:" msgstr "" -#: howto/logging.rst:697 +#: howto/logging.rst:671 +msgid "" +"[loggers]\n" +"keys=root,simpleExample\n" +"\n" +"[handlers]\n" +"keys=consoleHandler\n" +"\n" +"[formatters]\n" +"keys=simpleFormatter\n" +"\n" +"[logger_root]\n" +"level=DEBUG\n" +"handlers=consoleHandler\n" +"\n" +"[logger_simpleExample]\n" +"level=DEBUG\n" +"handlers=consoleHandler\n" +"qualname=simpleExample\n" +"propagate=0\n" +"\n" +"[handler_consoleHandler]\n" +"class=StreamHandler\n" +"level=DEBUG\n" +"formatter=simpleFormatter\n" +"args=(sys.stdout,)\n" +"\n" +"[formatter_simpleFormatter]\n" +"format=%(asctime)s - %(name)s - %(levelname)s - %(message)s" +msgstr "" + +#: howto/logging.rst:701 msgid "" "The output is nearly identical to that of the non-config-file-based example:" msgstr "" -#: howto/logging.rst:708 +#: howto/logging.rst:703 +msgid "" +"$ python simple_logging_config.py\n" +"2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message\n" +"2005-03-19 15:38:55,979 - simpleExample - INFO - info message\n" +"2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message\n" +"2005-03-19 15:38:56,055 - simpleExample - ERROR - error message\n" +"2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message" +msgstr "" + +#: howto/logging.rst:712 msgid "" "You can see that the config file approach has a few advantages over the " "Python code approach, mainly separation of configuration and code and the " "ability of noncoders to easily modify the logging properties." msgstr "" -#: howto/logging.rst:712 +#: howto/logging.rst:716 msgid "" "The :func:`fileConfig` function takes a default parameter, " "``disable_existing_loggers``, which defaults to ``True`` for reasons of " @@ -845,7 +1066,7 @@ msgid "" "information, and specify ``False`` for this parameter if you wish." msgstr "" -#: howto/logging.rst:720 +#: howto/logging.rst:724 msgid "" "The dictionary passed to :func:`dictConfig` can also specify a Boolean value " "with key ``disable_existing_loggers``, which if not specified explicitly in " @@ -854,7 +1075,7 @@ msgid "" "want - in which case, provide the key explicitly with a value of ``False``." msgstr "" -#: howto/logging.rst:730 +#: howto/logging.rst:734 msgid "" "Note that the class names referenced in config files need to be either " "relative to the logging module, or absolute values which can be resolved " @@ -865,7 +1086,7 @@ msgid "" "path)." msgstr "" -#: howto/logging.rst:738 +#: howto/logging.rst:742 msgid "" "In Python 3.2, a new means of configuring logging has been introduced, using " "dictionaries to hold configuration information. This provides a superset of " @@ -880,30 +1101,52 @@ msgid "" "a socket, or use whatever approach makes sense for your application." msgstr "" -#: howto/logging.rst:750 +#: howto/logging.rst:754 msgid "" "Here's an example of the same configuration as above, in YAML format for the " "new dictionary-based approach:" msgstr "" -#: howto/logging.rst:774 +#: howto/logging.rst:757 +msgid "" +"version: 1\n" +"formatters:\n" +" simple:\n" +" format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n" +"handlers:\n" +" console:\n" +" class: logging.StreamHandler\n" +" level: DEBUG\n" +" formatter: simple\n" +" stream: ext://sys.stdout\n" +"loggers:\n" +" simpleExample:\n" +" level: DEBUG\n" +" handlers: [console]\n" +" propagate: no\n" +"root:\n" +" level: DEBUG\n" +" handlers: [console]" +msgstr "" + +#: howto/logging.rst:778 msgid "" "For more information about logging using a dictionary, see :ref:`logging-" "config-api`." msgstr "" -#: howto/logging.rst:778 +#: howto/logging.rst:782 msgid "What happens if no configuration is provided" msgstr "" -#: howto/logging.rst:780 +#: howto/logging.rst:784 msgid "" "If no logging configuration is provided, it is possible to have a situation " "where a logging event needs to be output, but no handlers can be found to " "output the event." msgstr "" -#: howto/logging.rst:784 +#: howto/logging.rst:788 msgid "" "The event is output using a 'handler of last resort', stored in :data:" "`lastResort`. This internal handler is not associated with any logger, and " @@ -915,32 +1158,32 @@ msgid "" "severities will be output." msgstr "" -#: howto/logging.rst:795 +#: howto/logging.rst:799 msgid "For versions of Python prior to 3.2, the behaviour is as follows:" msgstr "" -#: howto/logging.rst:797 +#: howto/logging.rst:801 msgid "" "If :data:`raiseExceptions` is ``False`` (production mode), the event is " "silently dropped." msgstr "" -#: howto/logging.rst:800 +#: howto/logging.rst:804 msgid "" "If :data:`raiseExceptions` is ``True`` (development mode), a message 'No " "handlers could be found for logger X.Y.Z' is printed once." msgstr "" -#: howto/logging.rst:803 +#: howto/logging.rst:807 msgid "" "To obtain the pre-3.2 behaviour, :data:`lastResort` can be set to ``None``." msgstr "" -#: howto/logging.rst:809 +#: howto/logging.rst:813 msgid "Configuring Logging for a Library" msgstr "" -#: howto/logging.rst:811 +#: howto/logging.rst:815 msgid "" "When developing a library which uses logging, you should take care to " "document how the library uses logging - for example, the names of loggers " @@ -951,7 +1194,7 @@ msgid "" "is regarded as the best default behaviour." msgstr "" -#: howto/logging.rst:819 +#: howto/logging.rst:823 msgid "" "If for some reason you *don't* want these messages printed in the absence of " "any logging configuration, you can attach a do-nothing handler to the top-" @@ -963,7 +1206,7 @@ msgid "" "to those handlers, as normal." msgstr "" -#: howto/logging.rst:828 +#: howto/logging.rst:832 msgid "" "A do-nothing handler is included in the logging package: :class:`~logging." "NullHandler` (since Python 3.1). An instance of this handler could be added " @@ -974,14 +1217,20 @@ msgid "" "etc. then the code::" msgstr "" -#: howto/logging.rst:839 +#: howto/logging.rst:840 +msgid "" +"import logging\n" +"logging.getLogger('foo').addHandler(logging.NullHandler())" +msgstr "" + +#: howto/logging.rst:843 msgid "" "should have the desired effect. If an organisation produces a number of " "libraries, then the logger name specified can be 'orgname.foo' rather than " "just 'foo'." msgstr "" -#: howto/logging.rst:843 +#: howto/logging.rst:847 msgid "" "It is strongly advised that you *do not log to the root logger* in your " "library. Instead, use a logger with a unique and easily identifiable name, " @@ -991,7 +1240,7 @@ msgid "" "library as they wish." msgstr "" -#: howto/logging.rst:850 +#: howto/logging.rst:854 msgid "" "It is strongly advised that you *do not add any handlers other than* :class:" "`~logging.NullHandler` *to your library's loggers*. This is because the " @@ -1002,11 +1251,11 @@ msgid "" "carry out unit tests and deliver logs which suit their requirements." msgstr "" -#: howto/logging.rst:861 +#: howto/logging.rst:865 msgid "Logging Levels" msgstr "" -#: howto/logging.rst:863 +#: howto/logging.rst:867 msgid "" "The numeric values of logging levels are given in the following table. These " "are primarily of interest if you want to define your own levels, and need " @@ -1015,39 +1264,39 @@ msgid "" "value; the predefined name is lost." msgstr "" -#: howto/logging.rst:870 +#: howto/logging.rst:874 msgid "Numeric value" msgstr "" -#: howto/logging.rst:872 +#: howto/logging.rst:876 msgid "50" msgstr "" -#: howto/logging.rst:874 +#: howto/logging.rst:878 msgid "40" msgstr "" -#: howto/logging.rst:876 +#: howto/logging.rst:880 msgid "30" msgstr "" -#: howto/logging.rst:878 +#: howto/logging.rst:882 msgid "20" msgstr "" -#: howto/logging.rst:880 +#: howto/logging.rst:884 msgid "10" msgstr "" -#: howto/logging.rst:882 +#: howto/logging.rst:886 msgid "``NOTSET``" msgstr "" -#: howto/logging.rst:882 +#: howto/logging.rst:886 msgid "0" msgstr "" -#: howto/logging.rst:885 +#: howto/logging.rst:889 msgid "" "Levels can also be associated with loggers, being set either by the " "developer or through loading a saved logging configuration. When a logging " @@ -1057,14 +1306,14 @@ msgid "" "basic mechanism controlling the verbosity of logging output." msgstr "" -#: howto/logging.rst:892 +#: howto/logging.rst:896 msgid "" "Logging messages are encoded as instances of the :class:`~logging.LogRecord` " "class. When a logger decides to actually log an event, a :class:`~logging." "LogRecord` instance is created from the logging message." msgstr "" -#: howto/logging.rst:896 +#: howto/logging.rst:900 msgid "" "Logging messages are subjected to a dispatch mechanism through the use of :" "dfn:`handlers`, which are instances of subclasses of the :class:`Handler` " @@ -1081,7 +1330,7 @@ msgid "" "at which point the passing to ancestor handlers stops)." msgstr "" -#: howto/logging.rst:910 +#: howto/logging.rst:914 msgid "" "Just as for loggers, handlers can have levels associated with them. A " "handler's level acts as a filter in the same way as a logger's level does. " @@ -1091,11 +1340,11 @@ msgid "" "`~Handler.emit`." msgstr "" -#: howto/logging.rst:919 +#: howto/logging.rst:923 msgid "Custom Levels" msgstr "" -#: howto/logging.rst:921 +#: howto/logging.rst:925 msgid "" "Defining your own levels is possible, but should not be necessary, as the " "existing levels have been chosen on the basis of practical experience. " @@ -1108,27 +1357,27 @@ msgid "" "given numeric value might mean different things for different libraries." msgstr "" -#: howto/logging.rst:934 +#: howto/logging.rst:938 msgid "Useful Handlers" msgstr "" -#: howto/logging.rst:936 +#: howto/logging.rst:940 msgid "" "In addition to the base :class:`Handler` class, many useful subclasses are " "provided:" msgstr "" -#: howto/logging.rst:939 +#: howto/logging.rst:943 msgid "" ":class:`StreamHandler` instances send messages to streams (file-like " "objects)." msgstr "" -#: howto/logging.rst:942 +#: howto/logging.rst:946 msgid ":class:`FileHandler` instances send messages to disk files." msgstr "" -#: howto/logging.rst:944 +#: howto/logging.rst:948 msgid "" ":class:`~handlers.BaseRotatingHandler` is the base class for handlers that " "rotate log files at a certain point. It is not meant to be instantiated " @@ -1136,61 +1385,61 @@ msgid "" "`~handlers.TimedRotatingFileHandler`." msgstr "" -#: howto/logging.rst:949 +#: howto/logging.rst:953 msgid "" ":class:`~handlers.RotatingFileHandler` instances send messages to disk " "files, with support for maximum log file sizes and log file rotation." msgstr "" -#: howto/logging.rst:952 +#: howto/logging.rst:956 msgid "" ":class:`~handlers.TimedRotatingFileHandler` instances send messages to disk " "files, rotating the log file at certain timed intervals." msgstr "" -#: howto/logging.rst:955 +#: howto/logging.rst:959 msgid "" ":class:`~handlers.SocketHandler` instances send messages to TCP/IP sockets. " "Since 3.4, Unix domain sockets are also supported." msgstr "" -#: howto/logging.rst:958 +#: howto/logging.rst:962 msgid "" ":class:`~handlers.DatagramHandler` instances send messages to UDP sockets. " "Since 3.4, Unix domain sockets are also supported." msgstr "" -#: howto/logging.rst:961 +#: howto/logging.rst:965 msgid "" ":class:`~handlers.SMTPHandler` instances send messages to a designated email " "address." msgstr "" -#: howto/logging.rst:964 +#: howto/logging.rst:968 msgid "" ":class:`~handlers.SysLogHandler` instances send messages to a Unix syslog " "daemon, possibly on a remote machine." msgstr "" -#: howto/logging.rst:967 +#: howto/logging.rst:971 msgid "" ":class:`~handlers.NTEventLogHandler` instances send messages to a Windows " "NT/2000/XP event log." msgstr "" -#: howto/logging.rst:970 +#: howto/logging.rst:974 msgid "" ":class:`~handlers.MemoryHandler` instances send messages to a buffer in " "memory, which is flushed whenever specific criteria are met." msgstr "" -#: howto/logging.rst:973 +#: howto/logging.rst:977 msgid "" ":class:`~handlers.HTTPHandler` instances send messages to an HTTP server " "using either ``GET`` or ``POST`` semantics." msgstr "" -#: howto/logging.rst:976 +#: howto/logging.rst:980 msgid "" ":class:`~handlers.WatchedFileHandler` instances watch the file they are " "logging to. If the file changes, it is closed and reopened using the file " @@ -1198,13 +1447,13 @@ msgid "" "support the underlying mechanism used." msgstr "" -#: howto/logging.rst:981 +#: howto/logging.rst:985 msgid "" ":class:`~handlers.QueueHandler` instances send messages to a queue, such as " "those implemented in the :mod:`queue` or :mod:`multiprocessing` modules." msgstr "" -#: howto/logging.rst:984 +#: howto/logging.rst:988 msgid "" ":class:`NullHandler` instances do nothing with error messages. They are used " "by library developers who want to use logging, but want to avoid the 'No " @@ -1213,15 +1462,15 @@ msgid "" "more information." msgstr "" -#: howto/logging.rst:990 +#: howto/logging.rst:994 msgid "The :class:`NullHandler` class." msgstr "" -#: howto/logging.rst:993 +#: howto/logging.rst:997 msgid "The :class:`~handlers.QueueHandler` class." msgstr "" -#: howto/logging.rst:996 +#: howto/logging.rst:1000 msgid "" "The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler` " "classes are defined in the core logging package. The other handlers are " @@ -1229,14 +1478,14 @@ msgid "" "module, :mod:`logging.config`, for configuration functionality.)" msgstr "" -#: howto/logging.rst:1001 +#: howto/logging.rst:1005 msgid "" "Logged messages are formatted for presentation through instances of the :" "class:`Formatter` class. They are initialized with a format string suitable " "for use with the % operator and a dictionary." msgstr "" -#: howto/logging.rst:1005 +#: howto/logging.rst:1009 msgid "" "For formatting multiple messages in a batch, instances of :class:" "`BufferingFormatter` can be used. In addition to the format string (which is " @@ -1244,7 +1493,7 @@ msgid "" "trailer format strings." msgstr "" -#: howto/logging.rst:1010 +#: howto/logging.rst:1014 msgid "" "When filtering based on logger level and/or handler level is not enough, " "instances of :class:`Filter` can be added to both :class:`Logger` and :class:" @@ -1254,18 +1503,18 @@ msgid "" "value, the message is not processed further." msgstr "" -#: howto/logging.rst:1017 +#: howto/logging.rst:1021 msgid "" "The basic :class:`Filter` functionality allows filtering by specific logger " "name. If this feature is used, messages sent to the named logger and its " "children are allowed through the filter, and all others dropped." msgstr "" -#: howto/logging.rst:1025 +#: howto/logging.rst:1029 msgid "Exceptions raised during logging" msgstr "" -#: howto/logging.rst:1027 +#: howto/logging.rst:1031 msgid "" "The logging package is designed to swallow exceptions which occur while " "logging in production. This is so that errors which occur while handling " @@ -1273,7 +1522,7 @@ msgid "" "errors - do not cause the application using logging to terminate prematurely." msgstr "" -#: howto/logging.rst:1032 +#: howto/logging.rst:1036 msgid "" ":class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never " "swallowed. Other exceptions which occur during the :meth:`~Handler.emit` " @@ -1281,7 +1530,7 @@ msgid "" "handleError` method." msgstr "" -#: howto/logging.rst:1037 +#: howto/logging.rst:1041 msgid "" "The default implementation of :meth:`~Handler.handleError` in :class:" "`Handler` checks to see if a module-level variable, :data:`raiseExceptions`, " @@ -1289,7 +1538,7 @@ msgid "" "the exception is swallowed." msgstr "" -#: howto/logging.rst:1043 +#: howto/logging.rst:1047 msgid "" "The default value of :data:`raiseExceptions` is ``True``. This is because " "during development, you typically want to be notified of any exceptions that " @@ -1297,11 +1546,11 @@ msgid "" "production usage." msgstr "" -#: howto/logging.rst:1053 +#: howto/logging.rst:1057 msgid "Using arbitrary objects as messages" msgstr "" -#: howto/logging.rst:1055 +#: howto/logging.rst:1059 msgid "" "In the preceding sections and examples, it has been assumed that the message " "passed when logging the event is a string. However, this is not the only " @@ -1313,11 +1562,11 @@ msgid "" "the wire." msgstr "" -#: howto/logging.rst:1066 +#: howto/logging.rst:1070 msgid "Optimization" msgstr "" -#: howto/logging.rst:1068 +#: howto/logging.rst:1072 msgid "" "Formatting of message arguments is deferred until it cannot be avoided. " "However, computing the arguments passed to the logging method can also be " @@ -1330,11 +1579,18 @@ msgstr "" #: howto/logging.rst:1080 msgid "" +"if logger.isEnabledFor(logging.DEBUG):\n" +" logger.debug('Message with %s, %s', expensive_func1(),\n" +" expensive_func2())" +msgstr "" + +#: howto/logging.rst:1084 +msgid "" "so that if the logger's threshold is set above ``DEBUG``, the calls to " "``expensive_func1`` and ``expensive_func2`` are never made." msgstr "" -#: howto/logging.rst:1083 +#: howto/logging.rst:1087 msgid "" "In some cases, :meth:`~Logger.isEnabledFor` can itself be more expensive " "than you'd like (e.g. for deeply nested loggers where an explicit level is " @@ -1346,7 +1602,7 @@ msgid "" "while the application is running (which is not all that common)." msgstr "" -#: howto/logging.rst:1092 +#: howto/logging.rst:1096 msgid "" "There are other optimizations which can be made for specific applications " "which need more precise control over what logging information is collected. " @@ -1354,94 +1610,94 @@ msgid "" "you don't need:" msgstr "" -#: howto/logging.rst:1098 +#: howto/logging.rst:1102 msgid "What you don't want to collect" msgstr "" -#: howto/logging.rst:1098 +#: howto/logging.rst:1102 msgid "How to avoid collecting it" msgstr "" -#: howto/logging.rst:1100 +#: howto/logging.rst:1104 msgid "Information about where calls were made from." msgstr "" -#: howto/logging.rst:1100 +#: howto/logging.rst:1104 msgid "" "Set ``logging._srcfile`` to ``None``. This avoids calling :func:`sys." "_getframe`, which may help to speed up your code in environments like PyPy " "(which can't speed up code that uses :func:`sys._getframe`)." msgstr "" -#: howto/logging.rst:1106 +#: howto/logging.rst:1110 msgid "Threading information." msgstr "" -#: howto/logging.rst:1106 +#: howto/logging.rst:1110 msgid "Set ``logging.logThreads`` to ``False``." msgstr "" -#: howto/logging.rst:1108 +#: howto/logging.rst:1112 msgid "Current process ID (:func:`os.getpid`)" msgstr "" -#: howto/logging.rst:1108 +#: howto/logging.rst:1112 msgid "Set ``logging.logProcesses`` to ``False``." msgstr "" -#: howto/logging.rst:1110 +#: howto/logging.rst:1114 msgid "" "Current process name when using ``multiprocessing`` to manage multiple " "processes." msgstr "" -#: howto/logging.rst:1110 +#: howto/logging.rst:1114 msgid "Set ``logging.logMultiprocessing`` to ``False``." msgstr "" -#: howto/logging.rst:1113 +#: howto/logging.rst:1117 msgid "Current :class:`asyncio.Task` name when using ``asyncio``." msgstr "" -#: howto/logging.rst:1113 +#: howto/logging.rst:1117 msgid "Set ``logging.logAsyncioTasks`` to ``False``." msgstr "" -#: howto/logging.rst:1117 +#: howto/logging.rst:1121 msgid "" "Also note that the core logging module only includes the basic handlers. If " "you don't import :mod:`logging.handlers` and :mod:`logging.config`, they " "won't take up any memory." msgstr "" -#: howto/logging.rst:1124 +#: howto/logging.rst:1128 msgid "Other resources" msgstr "" -#: howto/logging.rst:1128 +#: howto/logging.rst:1132 msgid "Module :mod:`logging`" msgstr "" -#: howto/logging.rst:1129 +#: howto/logging.rst:1133 msgid "API reference for the logging module." msgstr "" -#: howto/logging.rst:1131 +#: howto/logging.rst:1135 msgid "Module :mod:`logging.config`" msgstr "" -#: howto/logging.rst:1132 +#: howto/logging.rst:1136 msgid "Configuration API for the logging module." msgstr "" -#: howto/logging.rst:1134 +#: howto/logging.rst:1138 msgid "Module :mod:`logging.handlers`" msgstr "" -#: howto/logging.rst:1135 +#: howto/logging.rst:1139 msgid "Useful handlers included with the logging module." msgstr "" -#: howto/logging.rst:1137 +#: howto/logging.rst:1141 msgid ":ref:`A logging cookbook `" msgstr "" diff --git a/howto/mro.po b/howto/mro.po index f30085c23..aa2ba82df 100644 --- a/howto/mro.po +++ b/howto/mro.po @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: TURKISH \n" @@ -181,6 +181,20 @@ msgid "" "for new style classes:" msgstr "" +#: howto/mro.rst:120 +msgid "" +" -----------\n" +"| |\n" +"| O |\n" +"| / \\ |\n" +" - X Y /\n" +" | / | /\n" +" | / |/\n" +" A B\n" +" \\ /\n" +" ?" +msgstr "" + #: howto/mro.rst:133 msgid "" "In this case, it is not possible to derive a new class C from A and B, since " @@ -206,6 +220,10 @@ msgid "" "following discussion. I will use the shortcut notation::" msgstr "" +#: howto/mro.rst:148 +msgid "C1 C2 ... CN" +msgstr "" + #: howto/mro.rst:150 msgid "to indicate the list of classes [C1, C2, ... , CN]." msgstr "" @@ -214,14 +232,26 @@ msgstr "" msgid "The *head* of the list is its first element::" msgstr "" +#: howto/mro.rst:154 +msgid "head = C1" +msgstr "" + #: howto/mro.rst:156 msgid "whereas the *tail* is the rest of the list::" msgstr "" +#: howto/mro.rst:158 +msgid "tail = C2 ... CN." +msgstr "" + #: howto/mro.rst:160 msgid "I shall also use the notation::" msgstr "" +#: howto/mro.rst:162 +msgid "C + (C1 C2 ... CN) = C C1 C2 ... CN" +msgstr "" + #: howto/mro.rst:164 msgid "to denote the sum of the lists [C] + [C1, C2, ... ,CN]." msgstr "" @@ -247,12 +277,20 @@ msgstr "" msgid "In symbolic notation::" msgstr "" +#: howto/mro.rst:178 +msgid "L[C(B1 ... BN)] = C + merge(L[B1] ... L[BN], B1 ... BN)" +msgstr "" + #: howto/mro.rst:180 msgid "" "In particular, if C is the ``object`` class, which has no parents, the " "linearization is trivial::" msgstr "" +#: howto/mro.rst:183 +msgid "L[object] = object." +msgstr "" + #: howto/mro.rst:185 msgid "" "However, in general one has to compute the merge according to the following " @@ -284,6 +322,10 @@ msgid "" "inheritance); in this case::" msgstr "" +#: howto/mro.rst:205 +msgid "L[C(B)] = C + merge(L[B],B) = C + L[B]" +msgstr "" + #: howto/mro.rst:207 msgid "" "However, in the case of multiple inheritance things are more cumbersome and " @@ -302,14 +344,51 @@ msgstr "" msgid "In this case the inheritance graph can be drawn as:" msgstr "" +#: howto/mro.rst:226 +msgid "" +" 6\n" +" ---\n" +"Level 3 | O | (more general)\n" +" / --- \\\n" +" / | \\ |\n" +" / | \\ |\n" +" / | \\ |\n" +" --- --- --- |\n" +"Level 2 3 | D | 4| E | | F | 5 |\n" +" --- --- --- |\n" +" \\ \\ _ / | |\n" +" \\ / \\ _ | |\n" +" \\ / \\ | |\n" +" --- --- |\n" +"Level 1 1 | B | | C | 2 |\n" +" --- --- |\n" +" \\ / |\n" +" \\ / \\ /\n" +" ---\n" +"Level 0 0 | A | (more specialized)\n" +" ---" +msgstr "" + #: howto/mro.rst:251 msgid "The linearizations of O,D,E and F are trivial::" msgstr "" +#: howto/mro.rst:253 +msgid "" +"L[O] = O\n" +"L[D] = D O\n" +"L[E] = E O\n" +"L[F] = F O" +msgstr "" + #: howto/mro.rst:258 msgid "The linearization of B can be computed as::" msgstr "" +#: howto/mro.rst:260 +msgid "L[B] = B + merge(DO, EO, DE)" +msgstr "" + #: howto/mro.rst:262 msgid "" "We see that D is a good head, therefore we take it and we are reduced to " @@ -319,14 +398,37 @@ msgid "" "reduced to compute ``merge(O,O)`` which gives O. Therefore::" msgstr "" +#: howto/mro.rst:268 +msgid "L[B] = B D E O" +msgstr "" + #: howto/mro.rst:270 msgid "Using the same procedure one finds::" msgstr "" +#: howto/mro.rst:272 +msgid "" +"L[C] = C + merge(DO,FO,DF)\n" +" = C + D + merge(O,FO,F)\n" +" = C + D + F + merge(O,O)\n" +" = C D F O" +msgstr "" + #: howto/mro.rst:277 msgid "Now we can compute::" msgstr "" +#: howto/mro.rst:279 +msgid "" +"L[A] = A + merge(BDEO,CDFO,BC)\n" +" = A + B + merge(DEO,CDFO,C)\n" +" = A + B + C + merge(DEO,DFO)\n" +" = A + B + C + D + merge(EO,FO)\n" +" = A + B + C + D + E + merge(O,FO)\n" +" = A + B + C + D + E + F + merge(O,O)\n" +" = A B C D E F O" +msgstr "" + #: howto/mro.rst:287 msgid "" "In this example, the linearization is ordered in a pretty nice way according " @@ -348,6 +450,31 @@ msgid "" "of the hierarchy:" msgstr "" +#: howto/mro.rst:307 +msgid "" +" 6\n" +" ---\n" +"Level 3 | O |\n" +" / --- \\\n" +" / | \\\n" +" / | \\\n" +" / | \\\n" +" --- --- ---\n" +"Level 2 2 | E | 4 | D | | F | 5\n" +" --- --- ---\n" +" \\ / \\ /\n" +" \\ / \\ /\n" +" \\ / \\ /\n" +" --- ---\n" +"Level 1 1 | B | | C | 3\n" +" --- ---\n" +" \\ /\n" +" \\ /\n" +" ---\n" +"Level 0 0 | A |\n" +" ---" +msgstr "" + #: howto/mro.rst:332 msgid "" "Notice that the class E, which is in the second level of the hierarchy, " @@ -359,7 +486,7 @@ msgstr "" msgid "" "A lazy programmer can obtain the MRO directly from Python 2.2, since in this " "case it coincides with the Python 2.3 linearization. It is enough to invoke " -"the .mro() method of class A:" +"the :meth:`~type.mro` method of class A:" msgstr "" #: howto/mro.rst:345 @@ -369,12 +496,28 @@ msgid "" "to compute the linearizations of O, X, Y, A and B:" msgstr "" +#: howto/mro.rst:349 +msgid "" +"L[O] = 0\n" +"L[X] = X O\n" +"L[Y] = Y O\n" +"L[A] = A X Y O\n" +"L[B] = B Y X O" +msgstr "" + #: howto/mro.rst:357 msgid "" "However, it is impossible to compute the linearization for a class C that " "inherits from A and B::" msgstr "" +#: howto/mro.rst:360 +msgid "" +"L[C] = C + merge(AXYO, BYXO, AB)\n" +" = C + A + merge(XYO, BYXO, B)\n" +" = C + A + B + merge(XYO, YXO)" +msgstr "" + #: howto/mro.rst:364 msgid "" "At this point we cannot merge the lists XYO and YXO, since X is in the tail " @@ -405,6 +548,19 @@ msgstr "" msgid "with inheritance diagram" msgstr "" +#: howto/mro.rst:386 +msgid "" +" O\n" +" |\n" +"(buy spam) F\n" +" | \\\n" +" | E (buy eggs)\n" +" | /\n" +" G\n" +"\n" +" (buy eggs or spam ?)" +msgstr "" + #: howto/mro.rst:399 msgid "" "We see that class G inherits from F and E, with F *before* E: therefore we " @@ -419,6 +575,10 @@ msgid "" "Python 2.2 linearization of G::" msgstr "" +#: howto/mro.rst:411 +msgid "L[G,P22]= G E F object # F *follows* E" +msgstr "" + #: howto/mro.rst:413 msgid "" "One could argue that the reason why F follows E in the Python 2.2 " @@ -442,6 +602,10 @@ msgid "" "The reason for that is that the C3 algorithm fails when the merge::" msgstr "" +#: howto/mro.rst:435 +msgid "merge(FO,EFO,FE)" +msgstr "" + #: howto/mro.rst:437 msgid "" "cannot be computed, because F is in the tail of EFO and E is in the tail of " @@ -455,6 +619,18 @@ msgid "" "the MRO is GEF without any doubt." msgstr "" +#: howto/mro.rst:444 +msgid "" +" O\n" +" |\n" +" F (spam)\n" +" / |\n" +"(eggs) E |\n" +" \\ |\n" +" G\n" +" (eggs, no doubt)" +msgstr "" + #: howto/mro.rst:456 msgid "" "Python 2.3 forces the programmer to write good hierarchies (or, at least, " @@ -504,16 +680,37 @@ msgid "" "trivial, it is enough to look at the diamond diagram:" msgstr "" +#: howto/mro.rst:489 +msgid "" +" C\n" +" / \\\n" +" / \\\n" +"A B\n" +" \\ /\n" +" \\ /\n" +" D" +msgstr "" + #: howto/mro.rst:500 msgid "One easily discerns the inconsistency::" msgstr "" +#: howto/mro.rst:502 +msgid "" +"L[B,P21] = B C # B precedes C : B's methods win\n" +"L[D,P21] = D A C B C # B follows C : C's methods win!" +msgstr "" + #: howto/mro.rst:505 msgid "" "On the other hand, there are no problems with the Python 2.2 and 2.3 MROs, " "they give both::" msgstr "" +#: howto/mro.rst:508 +msgid "L[D] = D A B C" +msgstr "" + #: howto/mro.rst:510 msgid "" "Guido points out in his essay [#]_ that the classic MRO is not so bad in " @@ -536,12 +733,29 @@ msgid "" "diagram ;-) ::" msgstr "" +#: howto/mro.rst:534 +msgid "" +"L[A] = A O\n" +"L[B] = B O\n" +"L[C] = C O\n" +"L[D] = D O\n" +"L[E] = E O\n" +"L[K1]= K1 A B C O\n" +"L[K2]= K2 D B E O\n" +"L[K3]= K3 D A O\n" +"L[Z] = Z K1 K2 K3 D A B C E O" +msgstr "" + #: howto/mro.rst:544 msgid "" "Python 2.2 gives exactly the same linearizations for A, B, C, D, E, K1, K2 " "and K3, but a different linearization for Z::" msgstr "" +#: howto/mro.rst:547 +msgid "L[Z,P22] = Z K1 K3 A K2 D B C E O" +msgstr "" + #: howto/mro.rst:549 msgid "" "It is clear that this linearization is *wrong*, since A comes before D " @@ -573,6 +787,92 @@ msgid "" "paper.::" msgstr "" +#: howto/mro.rst:574 +msgid "" +"#\n" +"\n" +"\"\"\"C3 algorithm by Samuele Pedroni (with readability enhanced by me)." +"\"\"\"\n" +"\n" +"class __metaclass__(type):\n" +" \"All classes are metamagically modified to be nicely printed\"\n" +" __repr__ = lambda cls: cls.__name__\n" +"\n" +"class ex_2:\n" +" \"Serious order disagreement\" #From Guido\n" +" class O: pass\n" +" class X(O): pass\n" +" class Y(O): pass\n" +" class A(X,Y): pass\n" +" class B(Y,X): pass\n" +" try:\n" +" class Z(A,B): pass #creates Z(A,B) in Python 2.2\n" +" except TypeError:\n" +" pass # Z(A,B) cannot be created in Python 2.3\n" +"\n" +"class ex_5:\n" +" \"My first example\"\n" +" class O: pass\n" +" class F(O): pass\n" +" class E(O): pass\n" +" class D(O): pass\n" +" class C(D,F): pass\n" +" class B(D,E): pass\n" +" class A(B,C): pass\n" +"\n" +"class ex_6:\n" +" \"My second example\"\n" +" class O: pass\n" +" class F(O): pass\n" +" class E(O): pass\n" +" class D(O): pass\n" +" class C(D,F): pass\n" +" class B(E,D): pass\n" +" class A(B,C): pass\n" +"\n" +"class ex_9:\n" +" \"Difference between Python 2.2 MRO and C3\" #From Samuele\n" +" class O: pass\n" +" class A(O): pass\n" +" class B(O): pass\n" +" class C(O): pass\n" +" class D(O): pass\n" +" class E(O): pass\n" +" class K1(A,B,C): pass\n" +" class K2(D,B,E): pass\n" +" class K3(D,A): pass\n" +" class Z(K1,K2,K3): pass\n" +"\n" +"def merge(seqs):\n" +" print '\\n\\nCPL[%s]=%s' % (seqs[0][0],seqs),\n" +" res = []; i=0\n" +" while 1:\n" +" nonemptyseqs=[seq for seq in seqs if seq]\n" +" if not nonemptyseqs: return res\n" +" i+=1; print '\\n',i,'round: candidates...',\n" +" for seq in nonemptyseqs: # find merge candidates among seq heads\n" +" cand = seq[0]; print ' ',cand,\n" +" nothead=[s for s in nonemptyseqs if cand in s[1:]]\n" +" if nothead: cand=None #reject candidate\n" +" else: break\n" +" if not cand: raise \"Inconsistent hierarchy\"\n" +" res.append(cand)\n" +" for seq in nonemptyseqs: # remove cand\n" +" if seq[0] == cand: del seq[0]\n" +"\n" +"def mro(C):\n" +" \"Compute the class precedence list (mro) according to C3\"\n" +" return merge([[C]]+map(mro,C.__bases__)+[list(C.__bases__)])\n" +"\n" +"def print_mro(C):\n" +" print '\\nMRO[%s]=%s' % (C,mro(C))\n" +" print '\\nP22 MRO[%s]=%s' % (C,C.mro())\n" +"\n" +"print_mro(ex_9.Z)\n" +"\n" +"#" +msgstr "" + #: howto/mro.rst:656 msgid "That's all folks," msgstr "" diff --git a/howto/perf_profiling.po b/howto/perf_profiling.po index cf94a6b84..14fe83bcb 100644 --- a/howto/perf_profiling.po +++ b/howto/perf_profiling.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-12-01 14:57+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -67,14 +67,92 @@ msgstr "" msgid "For example, consider the following script:" msgstr "" +#: howto/perf_profiling.rst:38 +msgid "" +"def foo(n):\n" +" result = 0\n" +" for _ in range(n):\n" +" result += 1\n" +" return result\n" +"\n" +"def bar(n):\n" +" foo(n)\n" +"\n" +"def baz(n):\n" +" bar(n)\n" +"\n" +"if __name__ == \"__main__\":\n" +" baz(1000000)" +msgstr "" + #: howto/perf_profiling.rst:55 msgid "We can run ``perf`` to sample CPU stack traces at 9999 hertz::" msgstr "" +#: howto/perf_profiling.rst:57 +msgid "$ perf record -F 9999 -g -o perf.data python my_script.py" +msgstr "" + #: howto/perf_profiling.rst:59 msgid "Then we can use ``perf report`` to analyze the data:" msgstr "" +#: howto/perf_profiling.rst:61 +msgid "" +"$ perf report --stdio -n -g\n" +"\n" +"# Children Self Samples Command Shared Object Symbol\n" +"# ........ ........ ............ .......... .................. ..........................................\n" +"#\n" +" 91.08% 0.00% 0 python.exe python.exe [.] " +"_start\n" +" |\n" +" ---_start\n" +" |\n" +" --90.71%--__libc_start_main\n" +" Py_BytesMain\n" +" |\n" +" |--56.88%--pymain_run_python.constprop.0\n" +" | |\n" +" | |--56.13%--_PyRun_AnyFileObject\n" +" | | _PyRun_SimpleFileObject\n" +" | | |\n" +" | | |--55.02%--run_mod\n" +" | | | |\n" +" | | | --54.65%--" +"PyEval_EvalCode\n" +" | | | " +"_PyEval_EvalFrameDefault\n" +" | | | " +"PyObject_Vectorcall\n" +" | | | " +"_PyEval_Vector\n" +" | | | " +"_PyEval_EvalFrameDefault\n" +" | | | " +"PyObject_Vectorcall\n" +" | | | " +"_PyEval_Vector\n" +" | | | " +"_PyEval_EvalFrameDefault\n" +" | | | " +"PyObject_Vectorcall\n" +" | | | " +"_PyEval_Vector\n" +" | | | |\n" +" | | | " +"|--51.67%--_PyEval_EvalFrameDefault\n" +" | | | " +"| |\n" +" | | | " +"| |--11.52%--_PyLong_Add\n" +" | | | " +"| | |\n" +" | | | " +"| | |--2.97%--_PyObject_Malloc\n" +"..." +msgstr "" + #: howto/perf_profiling.rst:100 msgid "" "As you can see, the Python functions are not shown in the output, only " @@ -89,6 +167,69 @@ msgid "" "Instead, if we run the same experiment with ``perf`` support enabled we get:" msgstr "" +#: howto/perf_profiling.rst:107 +msgid "" +"$ perf report --stdio -n -g\n" +"\n" +"# Children Self Samples Command Shared Object Symbol\n" +"# ........ ........ ............ .......... .................. .....................................................................\n" +"#\n" +" 90.58% 0.36% 1 python.exe python.exe [.] " +"_start\n" +" |\n" +" ---_start\n" +" |\n" +" --89.86%--__libc_start_main\n" +" Py_BytesMain\n" +" |\n" +" |--55.43%--pymain_run_python.constprop.0\n" +" | |\n" +" | |--54.71%--_PyRun_AnyFileObject\n" +" | | _PyRun_SimpleFileObject\n" +" | | |\n" +" | | |--53.62%--run_mod\n" +" | | | |\n" +" | | | --53.26%--" +"PyEval_EvalCode\n" +" | | | py::" +":/src/script.py\n" +" | | | " +"_PyEval_EvalFrameDefault\n" +" | | | " +"PyObject_Vectorcall\n" +" | | | " +"_PyEval_Vector\n" +" | | | py::baz:/" +"src/script.py\n" +" | | | " +"_PyEval_EvalFrameDefault\n" +" | | | " +"PyObject_Vectorcall\n" +" | | | " +"_PyEval_Vector\n" +" | | | py::bar:/" +"src/script.py\n" +" | | | " +"_PyEval_EvalFrameDefault\n" +" | | | " +"PyObject_Vectorcall\n" +" | | | " +"_PyEval_Vector\n" +" | | | py::foo:/" +"src/script.py\n" +" | | | |\n" +" | | | " +"|--51.81%--_PyEval_EvalFrameDefault\n" +" | | | " +"| |\n" +" | | | " +"| |--13.77%--_PyLong_Add\n" +" | | | " +"| | |\n" +" | | | " +"| | |--3.26%--_PyObject_Malloc" +msgstr "" + #: howto/perf_profiling.rst:152 msgid "How to enable ``perf`` profiling support" msgstr "" @@ -111,18 +252,47 @@ msgstr "" msgid "Example, using the environment variable::" msgstr "" +#: howto/perf_profiling.rst:165 +msgid "" +"$ PYTHONPERFSUPPORT=1 python script.py\n" +"$ perf report -g -i perf.data" +msgstr "" + #: howto/perf_profiling.rst:168 msgid "Example, using the :option:`!-X` option::" msgstr "" +#: howto/perf_profiling.rst:170 +msgid "" +"$ python -X perf script.py\n" +"$ perf report -g -i perf.data" +msgstr "" + #: howto/perf_profiling.rst:173 msgid "Example, using the :mod:`sys` APIs in file :file:`example.py`:" msgstr "" +#: howto/perf_profiling.rst:175 +msgid "" +"import sys\n" +"\n" +"sys.activate_stack_trampoline(\"perf\")\n" +"do_profiled_stuff()\n" +"sys.deactivate_stack_trampoline()\n" +"\n" +"non_profiled_stuff()" +msgstr "" + #: howto/perf_profiling.rst:185 msgid "...then::" msgstr "" +#: howto/perf_profiling.rst:187 +msgid "" +"$ python ./example.py\n" +"$ perf report -g -i perf.data" +msgstr "" + #: howto/perf_profiling.rst:192 msgid "How to obtain the best results" msgstr "" @@ -142,6 +312,10 @@ msgid "" "You can check if your system has been compiled with this flag by running::" msgstr "" +#: howto/perf_profiling.rst:203 +msgid "$ python -m sysconfig | grep 'no-omit-frame-pointer'" +msgstr "" + #: howto/perf_profiling.rst:205 msgid "" "If you don't see any output it means that your interpreter has not been " diff --git a/howto/regex.po b/howto/regex.po index f00cca248..2bcdea3bd 100644 --- a/howto/regex.po +++ b/howto/regex.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-05-01 21:53+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -124,6 +124,10 @@ msgid "" "discussed in the rest of this HOWTO." msgstr "" +#: howto/regex.rst:79 +msgid ". ^ $ * + ? { } [ ] \\ | ( )" +msgstr "" + #: howto/regex.rst:83 msgid "" "The first metacharacters we'll look at are ``[`` and ``]``. They're used for " @@ -480,6 +484,14 @@ msgid "" "string substitutions. ::" msgstr "" +#: howto/regex.rst:274 +msgid "" +">>> import re\n" +">>> p = re.compile('ab*')\n" +">>> p\n" +"re.compile('ab*')" +msgstr "" + #: howto/regex.rst:279 msgid "" ":func:`re.compile` also accepts an optional *flags* argument, used to enable " @@ -487,6 +499,10 @@ msgid "" "settings later, but for now a single example will do::" msgstr "" +#: howto/regex.rst:283 +msgid ">>> p = re.compile('ab*', re.IGNORECASE)" +msgstr "" + #: howto/regex.rst:285 msgid "" "The RE is passed to :func:`re.compile` as a string. REs are handled as " @@ -690,6 +706,14 @@ msgid "" "the Python interpreter, import the :mod:`re` module, and compile a RE::" msgstr "" +#: howto/regex.rst:389 +msgid "" +">>> import re\n" +">>> p = re.compile('[a-z]+')\n" +">>> p\n" +"re.compile('[a-z]+')" +msgstr "" + #: howto/regex.rst:394 msgid "" "Now, you can try matching various strings against the RE ``[a-z]+``. An " @@ -699,6 +723,13 @@ msgid "" "print the result of :meth:`!match` to make this clear. ::" msgstr "" +#: howto/regex.rst:400 +msgid "" +">>> p.match(\"\")\n" +">>> print(p.match(\"\"))\n" +"None" +msgstr "" + #: howto/regex.rst:404 msgid "" "Now, let's try it on a string that it should match, such as ``tempo``. In " @@ -706,6 +737,13 @@ msgid "" "objects>`, so you should store the result in a variable for later use. ::" msgstr "" +#: howto/regex.rst:408 +msgid "" +">>> m = p.match('tempo')\n" +">>> m\n" +"" +msgstr "" + #: howto/regex.rst:412 msgid "" "Now you can query the :ref:`match object ` for information " @@ -749,6 +787,16 @@ msgstr "" msgid "Trying these methods will soon clarify their meaning::" msgstr "" +#: howto/regex.rst:431 +msgid "" +">>> m.group()\n" +"'tempo'\n" +">>> m.start(), m.end()\n" +"(0, 5)\n" +">>> m.span()\n" +"(0, 5)" +msgstr "" + #: howto/regex.rst:438 msgid "" ":meth:`~re.Match.group` returns the substring that was matched by the RE. :" @@ -761,6 +809,18 @@ msgid "" "case. ::" msgstr "" +#: howto/regex.rst:446 +msgid "" +">>> print(p.match('::: message'))\n" +"None\n" +">>> m = p.search('::: message'); print(m)\n" +"\n" +">>> m.group()\n" +"'message'\n" +">>> m.span()\n" +"(4, 11)" +msgstr "" + #: howto/regex.rst:455 msgid "" "In actual programs, the most common style is to store the :ref:`match object " @@ -768,12 +828,29 @@ msgid "" "usually looks like::" msgstr "" +#: howto/regex.rst:459 +msgid "" +"p = re.compile( ... )\n" +"m = p.match( 'string goes here' )\n" +"if m:\n" +" print('Match found: ', m.group())\n" +"else:\n" +" print('No match')" +msgstr "" + #: howto/regex.rst:466 msgid "" "Two pattern methods return all of the matches for a pattern. :meth:`~re." "Pattern.findall` returns a list of matching strings::" msgstr "" +#: howto/regex.rst:469 +msgid "" +">>> p = re.compile(r'\\d+')\n" +">>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')\n" +"['12', '11', '10']" +msgstr "" + #: howto/regex.rst:473 msgid "" "The ``r`` prefix, making the literal a raw string literal, is needed in this " @@ -791,6 +868,19 @@ msgid "" "`iterator`::" msgstr "" +#: howto/regex.rst:483 +msgid "" +">>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')\n" +">>> iterator \n" +"\n" +">>> for match in iterator:\n" +"... print(match.span())\n" +"...\n" +"(0, 2)\n" +"(22, 24)\n" +"(29, 31)" +msgstr "" + #: howto/regex.rst:495 msgid "Module-Level Functions" msgstr "" @@ -805,6 +895,14 @@ msgid "" "``None`` or a :ref:`match object ` instance. ::" msgstr "" +#: howto/regex.rst:504 +msgid "" +">>> print(re.match(r'From\\s+', 'Fromage amk'))\n" +"None\n" +">>> re.match(r'From\\s+', 'From amk Thu May 14 19:12:10 1998') \n" +"" +msgstr "" + #: howto/regex.rst:509 msgid "" "Under the hood, these functions simply create a pattern object for you and " @@ -991,10 +1089,30 @@ msgid "" "it is to read? ::" msgstr "" +#: howto/regex.rst:651 +msgid "" +"charref = re.compile(r\"\"\"\n" +" &[#] # Start of a numeric entity reference\n" +" (\n" +" 0[0-7]+ # Octal form\n" +" | [0-9]+ # Decimal form\n" +" | x[0-9a-fA-F]+ # Hexadecimal form\n" +" )\n" +" ; # Trailing semicolon\n" +"\"\"\", re.VERBOSE)" +msgstr "" + #: howto/regex.rst:661 msgid "Without the verbose setting, the RE would look like this::" msgstr "" +#: howto/regex.rst:663 +msgid "" +"charref = re.compile(\"&#(0[0-7]+\"\n" +" \"|[0-9]+\"\n" +" \"|x[0-9a-fA-F]+);\")" +msgstr "" + #: howto/regex.rst:667 msgid "" "In the above example, Python's automatic concatenation of string literals " @@ -1073,6 +1191,14 @@ msgid "" "a line, the RE to use is ``^From``. ::" msgstr "" +#: howto/regex.rst:714 +msgid "" +">>> print(re.search('^From', 'From Here to Eternity')) \n" +"\n" +">>> print(re.search('^From', 'Reciting From Memory'))\n" +"None" +msgstr "" + #: howto/regex.rst:719 msgid "To match a literal ``'^'``, use ``\\^``." msgstr "" @@ -1087,6 +1213,16 @@ msgid "" "string, or any location followed by a newline character. ::" msgstr "" +#: howto/regex.rst:725 +msgid "" +">>> print(re.search('}$', '{block}')) \n" +"\n" +">>> print(re.search('}$', '{block} '))\n" +"None\n" +">>> print(re.search('}$', '{block}\\n')) \n" +"" +msgstr "" + #: howto/regex.rst:732 msgid "" "To match a literal ``'$'``, use ``\\$`` or enclose it inside a character " @@ -1132,6 +1268,17 @@ msgid "" "won't match when it's contained inside another word. ::" msgstr "" +#: howto/regex.rst:753 +msgid "" +">>> p = re.compile(r'\\bclass\\b')\n" +">>> print(p.search('no class at all'))\n" +"\n" +">>> print(p.search('the declassified algorithm'))\n" +"None\n" +">>> print(p.search('one subclass is'))\n" +"None" +msgstr "" + #: howto/regex.rst:761 msgid "" "There are two subtleties you should remember when using this special " @@ -1143,6 +1290,15 @@ msgid "" "previous RE, but omits the ``'r'`` in front of the RE string. ::" msgstr "" +#: howto/regex.rst:769 +msgid "" +">>> p = re.compile('\\bclass\\b')\n" +">>> print(p.search('no class at all'))\n" +"None\n" +">>> print(p.search('\\b' + 'class' + '\\b'))\n" +"" +msgstr "" + #: howto/regex.rst:775 msgid "" "Second, inside a character class, where there's no use for this assertion, " @@ -1173,6 +1329,14 @@ msgid "" "name and a value, separated by a ``':'``, like this:" msgstr "" +#: howto/regex.rst:793 +msgid "" +"From: author@example.com\n" +"User-Agent: Thunderbird 1.5.0.9 (X11/20061227)\n" +"MIME-Version: 1.0\n" +"To: editor@example.com" +msgstr "" + #: howto/regex.rst:800 msgid "" "This can be handled by writing a regular expression which matches an entire " @@ -1190,6 +1354,13 @@ msgid "" "repetitions of ``ab``. ::" msgstr "" +#: howto/regex.rst:811 +msgid "" +">>> p = re.compile('(ab)*')\n" +">>> print(p.match('ababababab').span())\n" +"(0, 10)" +msgstr "" + #: howto/regex.rst:815 msgid "" "Groups indicated with ``'('``, ``')'`` also capture the starting and ending " @@ -1202,6 +1373,16 @@ msgid "" "they match. ::" msgstr "" +#: howto/regex.rst:824 +msgid "" +">>> p = re.compile('(a)b')\n" +">>> m = p.match('ab')\n" +">>> m.group()\n" +"'ab'\n" +">>> m.group(0)\n" +"'ab'" +msgstr "" + #: howto/regex.rst:831 msgid "" "Subgroups are numbered from left to right, from 1 upward. Groups can be " @@ -1209,6 +1390,18 @@ msgid "" "characters, going from left to right. ::" msgstr "" +#: howto/regex.rst:835 +msgid "" +">>> p = re.compile('(a(b)c)d')\n" +">>> m = p.match('abcd')\n" +">>> m.group(0)\n" +"'abcd'\n" +">>> m.group(1)\n" +"'abc'\n" +">>> m.group(2)\n" +"'b'" +msgstr "" + #: howto/regex.rst:844 msgid "" ":meth:`~re.Match.group` can be passed multiple group numbers at a time, in " @@ -1216,12 +1409,24 @@ msgid "" "those groups. ::" msgstr "" +#: howto/regex.rst:847 +msgid "" +">>> m.group(2,1,2)\n" +"('b', 'abc', 'b')" +msgstr "" + #: howto/regex.rst:850 msgid "" "The :meth:`~re.Match.groups` method returns a tuple containing the strings " "for all the subgroups, from 1 up to however many there are. ::" msgstr "" +#: howto/regex.rst:853 +msgid "" +">>> m.groups()\n" +"('abc', 'b')" +msgstr "" + #: howto/regex.rst:856 msgid "" "Backreferences in a pattern allow you to specify that the contents of an " @@ -1237,6 +1442,13 @@ msgstr "" msgid "For example, the following RE detects doubled words in a string. ::" msgstr "" +#: howto/regex.rst:866 +msgid "" +">>> p = re.compile(r'\\b(\\w+)\\s+\\1\\b')\n" +">>> p.search('Paris in the the spring').group()\n" +"'the the'" +msgstr "" + #: howto/regex.rst:870 msgid "" "Backreferences like this aren't often useful for just searching through a " @@ -1301,6 +1513,16 @@ msgid "" "where you can replace the ``...`` with any other regular expression. ::" msgstr "" +#: howto/regex.rst:912 +msgid "" +">>> m = re.match(\"([abc])+\", \"abc\")\n" +">>> m.groups()\n" +"('c',)\n" +">>> m = re.match(\"(?:[abc])+\", \"abc\")\n" +">>> m.groups()\n" +"()" +msgstr "" + #: howto/regex.rst:919 msgid "" "Except for the fact that you can't retrieve the contents of what the group " @@ -1332,12 +1554,29 @@ msgid "" "ways::" msgstr "" +#: howto/regex.rst:939 +msgid "" +">>> p = re.compile(r'(?P\\b\\w+\\b)')\n" +">>> m = p.search( '(((( Lots of punctuation )))' )\n" +">>> m.group('word')\n" +"'Lots'\n" +">>> m.group(1)\n" +"'Lots'" +msgstr "" + #: howto/regex.rst:946 msgid "" "Additionally, you can retrieve named groups as a dictionary with :meth:`~re." "Match.groupdict`::" msgstr "" +#: howto/regex.rst:949 +msgid "" +">>> m = re.match(r'(?P\\w+) (?P\\w+)', 'Jane Doe')\n" +">>> m.groupdict()\n" +"{'first': 'Jane', 'last': 'Doe'}" +msgstr "" + #: howto/regex.rst:953 msgid "" "Named groups are handy because they let you use easily remembered names, " @@ -1345,6 +1584,16 @@ msgid "" "`imaplib` module::" msgstr "" +#: howto/regex.rst:957 +msgid "" +"InternalDate = re.compile(r'INTERNALDATE \"'\n" +" r'(?P[ 123][0-9])-(?P[A-Z][a-z][a-z])-'\n" +" r'(?P[0-9][0-9][0-9][0-9])'\n" +" r' (?P[0-9][0-9]):(?P[0-9][0-9]):(?P[0-9][0-9])'\n" +" r' (?P[-+])(?P[0-9][0-9])(?P[0-9][0-9])'\n" +" r'\"')" +msgstr "" + #: howto/regex.rst:964 msgid "" "It's obviously much easier to retrieve ``m.group('zonem')``, instead of " @@ -1362,6 +1611,13 @@ msgid "" "P\\w+)\\s+(?P=word)\\b``::" msgstr "" +#: howto/regex.rst:974 +msgid "" +">>> p = re.compile(r'\\b(?P\\w+)\\s+(?P=word)\\b')\n" +">>> p.search('Paris in the the spring').group()\n" +"'the the'" +msgstr "" + #: howto/regex.rst:980 msgid "Lookahead Assertions" msgstr "" @@ -1565,6 +1821,15 @@ msgid "" "characters. ::" msgstr "" +#: howto/regex.rst:1104 +msgid "" +">>> p = re.compile(r'\\W+')\n" +">>> p.split('This is a test, short and sweet, of split().')\n" +"['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', '']\n" +">>> p.split('This is a test, short and sweet, of split().', 3)\n" +"['This', 'is', 'a', 'test, short and sweet, of split().']" +msgstr "" + #: howto/regex.rst:1110 msgid "" "Sometimes you're not only interested in what the text between delimiters is, " @@ -1573,12 +1838,32 @@ msgid "" "Compare the following calls::" msgstr "" +#: howto/regex.rst:1115 +msgid "" +">>> p = re.compile(r'\\W+')\n" +">>> p2 = re.compile(r'(\\W+)')\n" +">>> p.split('This... is a test.')\n" +"['This', 'is', 'a', 'test', '']\n" +">>> p2.split('This... is a test.')\n" +"['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']" +msgstr "" + #: howto/regex.rst:1122 msgid "" "The module-level function :func:`re.split` adds the RE to be used as the " "first argument, but is otherwise the same. ::" msgstr "" +#: howto/regex.rst:1125 +msgid "" +">>> re.split(r'[\\W]+', 'Words, words, words.')\n" +"['Words', 'words', 'words', '']\n" +">>> re.split(r'([\\W]+)', 'Words, words, words.')\n" +"['Words', ', ', 'words', ', ', 'words', '.', '']\n" +">>> re.split(r'[\\W]+', 'Words, words, words.', 1)\n" +"['Words', 'words, words.']" +msgstr "" + #: howto/regex.rst:1134 msgid "Search and Replace" msgstr "" @@ -1611,6 +1896,15 @@ msgid "" "replaces colour names with the word ``colour``::" msgstr "" +#: howto/regex.rst:1154 +msgid "" +">>> p = re.compile('(blue|white|red)')\n" +">>> p.sub('colour', 'blue socks and red shoes')\n" +"'colour socks and colour shoes'\n" +">>> p.sub('colour', 'blue socks and red shoes', count=1)\n" +"'colour socks and red shoes'" +msgstr "" + #: howto/regex.rst:1160 msgid "" "The :meth:`~re.Pattern.subn` method does the same work, but returns a 2-" @@ -1618,12 +1912,28 @@ msgid "" "were performed::" msgstr "" +#: howto/regex.rst:1163 +msgid "" +">>> p = re.compile('(blue|white|red)')\n" +">>> p.subn('colour', 'blue socks and red shoes')\n" +"('colour socks and colour shoes', 2)\n" +">>> p.subn('colour', 'no colours at all')\n" +"('no colours at all', 0)" +msgstr "" + #: howto/regex.rst:1169 msgid "" "Empty matches are replaced only when they're not adjacent to a previous " "empty match. ::" msgstr "" +#: howto/regex.rst:1172 +msgid "" +">>> p = re.compile('x*')\n" +">>> p.sub('-', 'abxd')\n" +"'-a-b--d-'" +msgstr "" + #: howto/regex.rst:1176 msgid "" "If *replacement* is a string, any backslash escapes in it are processed. " @@ -1641,6 +1951,13 @@ msgid "" "``{``, ``}``, and changes ``section`` to ``subsection``::" msgstr "" +#: howto/regex.rst:1186 +msgid "" +">>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE)\n" +">>> p.sub(r'subsection{\\1}','section{First} section{second}')\n" +"'subsection{First} subsection{second}'" +msgstr "" + #: howto/regex.rst:1190 msgid "" "There's also a syntax for referring to named groups as defined by the ``(?" @@ -1653,6 +1970,17 @@ msgid "" "but use all three variations of the replacement string. ::" msgstr "" +#: howto/regex.rst:1199 +msgid "" +">>> p = re.compile('section{ (?P [^}]* ) }', re.VERBOSE)\n" +">>> p.sub(r'subsection{\\1}','section{First}')\n" +"'subsection{First}'\n" +">>> p.sub(r'subsection{\\g<1>}','section{First}')\n" +"'subsection{First}'\n" +">>> p.sub(r'subsection{\\g}','section{First}')\n" +"'subsection{First}'" +msgstr "" + #: howto/regex.rst:1207 msgid "" "*replacement* can also be a function, which gives you even more control. If " @@ -1668,6 +1996,18 @@ msgid "" "hexadecimal::" msgstr "" +#: howto/regex.rst:1216 +msgid "" +">>> def hexrepl(match):\n" +"... \"Return the hex string for a decimal number\"\n" +"... value = int(match.group())\n" +"... return hex(value)\n" +"...\n" +">>> p = re.compile(r'\\d+')\n" +">>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')\n" +"'Call 0xffd2 for printing, 0xc000 for user code.'" +msgstr "" + #: howto/regex.rst:1225 msgid "" "When using the module-level :func:`re.sub` function, the pattern is passed " @@ -1748,12 +2088,28 @@ msgid "" "report it. ::" msgstr "" +#: howto/regex.rst:1279 +msgid "" +">>> print(re.match('super', 'superstition').span())\n" +"(0, 5)\n" +">>> print(re.match('super', 'insuperable'))\n" +"None" +msgstr "" + #: howto/regex.rst:1284 msgid "" "On the other hand, :func:`~re.search` will scan forward through the string, " "reporting the first match it finds. ::" msgstr "" +#: howto/regex.rst:1287 +msgid "" +">>> print(re.search('super', 'superstition').span())\n" +"(0, 5)\n" +">>> print(re.search('super', 'insuperable').span())\n" +"(2, 7)" +msgstr "" + #: howto/regex.rst:1292 msgid "" "Sometimes you'll be tempted to keep using :func:`re.match`, and just add ``." @@ -1786,6 +2142,17 @@ msgid "" "HTML tag doesn't work because of the greedy nature of ``.*``. ::" msgstr "" +#: howto/regex.rst:1315 +msgid "" +">>> s = 'Title'\n" +">>> len(s)\n" +"32\n" +">>> print(re.match('<.*>', s).span())\n" +"(0, 32)\n" +">>> print(re.match('<.*>', s).group())\n" +"Title" +msgstr "" + #: howto/regex.rst:1323 msgid "" "The RE matches the ``'<'`` in ``''``, and the ``.*`` consumes the rest " @@ -1805,6 +2172,12 @@ msgid "" "retrying the ``'>'`` at every step. This produces just the right result::" msgstr "" +#: howto/regex.rst:1336 +msgid "" +">>> print(re.match('<.*?>', s).group())\n" +"" +msgstr "" + #: howto/regex.rst:1339 msgid "" "(Note that parsing HTML or XML with regular expressions is painful. Quick-" @@ -1845,10 +2218,26 @@ msgid "" "quoted strings, this enables REs to be formatted more neatly::" msgstr "" +#: howto/regex.rst:1366 +msgid "" +"pat = re.compile(r\"\"\"\n" +" \\s* # Skip leading whitespace\n" +" (?P
[^:]+) # Header name\n" +" \\s* : # Whitespace, and a colon\n" +" (?P.*?) # The header's value -- *? used to\n" +" # lose the following trailing whitespace\n" +" \\s*$ # Trailing whitespace to end-of-line\n" +"\"\"\", re.VERBOSE)" +msgstr "" + #: howto/regex.rst:1375 msgid "This is far more readable than::" msgstr "" +#: howto/regex.rst:1377 +msgid "pat = re.compile(r\"\\s*(?P
[^:]+)\\s*:(?P.*?)\\s*$\")" +msgstr "" + #: howto/regex.rst:1381 msgid "Feedback" msgstr "" diff --git a/howto/sockets.po b/howto/sockets.po index b4da9ed94..b89f53e44 100644 --- a/howto/sockets.po +++ b/howto/sockets.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-02-24 17:22+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -99,6 +99,14 @@ msgid "" "page, your browser did something like the following::" msgstr "" +#: howto/sockets.rst:59 +msgid "" +"# create an INET, STREAMing socket\n" +"s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n" +"# now connect to the web server on port 80 - the normal http port\n" +"s.connect((\"www.python.org\", 80))" +msgstr "" + #: howto/sockets.rst:64 msgid "" "When the ``connect`` completes, the socket ``s`` can be used to send in a " @@ -113,6 +121,16 @@ msgid "" "creates a \"server socket\"::" msgstr "" +#: howto/sockets.rst:73 +msgid "" +"# create an INET, STREAMing socket\n" +"serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n" +"# bind the socket to a public host, and a well-known port\n" +"serversocket.bind((socket.gethostname(), 80))\n" +"# become a server socket\n" +"serversocket.listen(5)" +msgstr "" + #: howto/sockets.rst:80 msgid "" "A couple things to notice: we used ``socket.gethostname()`` so that the " @@ -144,6 +162,17 @@ msgid "" "mainloop of the web server::" msgstr "" +#: howto/sockets.rst:98 +msgid "" +"while True:\n" +" # accept connections from outside\n" +" (clientsocket, address) = serversocket.accept()\n" +" # now do something with the clientsocket\n" +" # in this case, we'll pretend this is a threaded server\n" +" ct = client_thread(clientsocket)\n" +" ct.run()" +msgstr "" + #: howto/sockets.rst:106 msgid "" "There's actually 3 general ways in which this loop could work - dispatching " @@ -252,6 +281,43 @@ msgid "" "fixed length message::" msgstr "" +#: howto/sockets.rst:183 +msgid "" +"class MySocket:\n" +" \"\"\"demonstration class only\n" +" - coded for clarity, not efficiency\n" +" \"\"\"\n" +"\n" +" def __init__(self, sock=None):\n" +" if sock is None:\n" +" self.sock = socket.socket(\n" +" socket.AF_INET, socket.SOCK_STREAM)\n" +" else:\n" +" self.sock = sock\n" +"\n" +" def connect(self, host, port):\n" +" self.sock.connect((host, port))\n" +"\n" +" def mysend(self, msg):\n" +" totalsent = 0\n" +" while totalsent < MSGLEN:\n" +" sent = self.sock.send(msg[totalsent:])\n" +" if sent == 0:\n" +" raise RuntimeError(\"socket connection broken\")\n" +" totalsent = totalsent + sent\n" +"\n" +" def myreceive(self):\n" +" chunks = []\n" +" bytes_recd = 0\n" +" while bytes_recd < MSGLEN:\n" +" chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048))\n" +" if chunk == b'':\n" +" raise RuntimeError(\"socket connection broken\")\n" +" chunks.append(chunk)\n" +" bytes_recd = bytes_recd + len(chunk)\n" +" return b''.join(chunks)" +msgstr "" + #: howto/sockets.rst:217 msgid "" "The sending code here is usable for almost any messaging scheme - in Python " @@ -433,6 +499,16 @@ msgid "" "Python, you'll have little trouble with it in C::" msgstr "" +#: howto/sockets.rst:345 +msgid "" +"ready_to_read, ready_to_write, in_error = \\\n" +" select.select(\n" +" potential_readers,\n" +" potential_writers,\n" +" potential_errs,\n" +" timeout)" +msgstr "" + #: howto/sockets.rst:352 msgid "" "You pass ``select`` three lists: the first contains all sockets that you " diff --git a/howto/sorting.po b/howto/sorting.po index 2a8594eba..4080ffda4 100644 --- a/howto/sorting.po +++ b/howto/sorting.po @@ -6,7 +6,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-02-24 17:22+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: 2023-04-19 21:42+0300\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -59,6 +59,12 @@ msgstr "" "Basit bir artan sıralama yaratmak çok kolaydır: :func:`sorted` fonksiyonunu " "çağırmanız yeterlidir. Bu fonksiyon, yeni bir sıralanmış liste döndürür:" +#: howto/sorting.rst:22 +msgid "" +">>> sorted([5, 2, 3, 1, 4])\n" +"[1, 2, 3, 4, 5]" +msgstr "" + #: howto/sorting.rst:27 msgid "" "You can also use the :meth:`list.sort` method. It modifies the list in-place " @@ -71,6 +77,14 @@ msgstr "" "func:`sorted` yönteminden daha az kullanışlıdır - ancak orijinal listeye " "ihtiyacınız yoksa, biraz daha verimlidir." +#: howto/sorting.rst:32 +msgid "" +">>> a = [5, 2, 3, 1, 4]\n" +">>> a.sort()\n" +">>> a\n" +"[1, 2, 3, 4, 5]" +msgstr "" + #: howto/sorting.rst:39 msgid "" "Another difference is that the :meth:`list.sort` method is only defined for " @@ -80,6 +94,12 @@ msgstr "" "tanımlanmış olmasıdır. Buna karşılık, :func:`sorted` fonksiyonu herhangi bir " "yinelenebiliri kabul eder." +#: howto/sorting.rst:42 +msgid "" +">>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})\n" +"[1, 2, 3, 4, 5]" +msgstr "" + #: howto/sorting.rst:48 msgid "Key Functions" msgstr "Anahtar Fonksiyonları" @@ -100,6 +120,12 @@ msgstr "" "Örneğin, büyük/küçük harfe duyarlı olmayan bir dize karşılaştırması bu " "şekilde yapılmaktadır:" +#: howto/sorting.rst:56 +msgid "" +">>> sorted(\"This is a test string from Andrew\".split(), key=str.casefold)\n" +"['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']" +msgstr "" + #: howto/sorting.rst:61 msgid "" "The value of the *key* parameter should be a function (or other callable) " @@ -120,6 +146,17 @@ msgstr "" "Yaygın bir model, nesnenin bazı indislerini anahtar olarak kullanarak " "karmaşık nesneleri sıralamaktır. Örneğin:" +#: howto/sorting.rst:69 +msgid "" +">>> student_tuples = [\n" +"... ('john', 'A', 15),\n" +"... ('jane', 'B', 12),\n" +"... ('dave', 'B', 10),\n" +"... ]\n" +">>> sorted(student_tuples, key=lambda student: student[2]) # sort by age\n" +"[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]" +msgstr "" + #: howto/sorting.rst:79 msgid "" "The same technique works for objects with named attributes. For example:" @@ -127,6 +164,26 @@ msgstr "" "Aynı teknik, adlandırılmış niteliklere sahip nesneler için de geçerlidir. " "Örneğin:" +#: howto/sorting.rst:81 +msgid "" +">>> class Student:\n" +"... def __init__(self, name, grade, age):\n" +"... self.name = name\n" +"... self.grade = grade\n" +"... self.age = age\n" +"... def __repr__(self):\n" +"... return repr((self.name, self.grade, self.age))\n" +"\n" +">>> student_objects = [\n" +"... Student('john', 'A', 15),\n" +"... Student('jane', 'B', 12),\n" +"... Student('dave', 'B', 10),\n" +"... ]\n" +">>> sorted(student_objects, key=lambda student: student.age) # sort by " +"age\n" +"[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]" +msgstr "" + #: howto/sorting.rst:99 msgid "" "Objects with named attributes can be made by a regular class as shown above, " @@ -159,6 +216,17 @@ msgstr "" "Bu fonksiyonların kullanımı sonucunda, yukarıdaki örnekler daha basit ve " "hızlı hale gelir:" +#: howto/sorting.rst:113 +msgid "" +">>> from operator import itemgetter, attrgetter\n" +"\n" +">>> sorted(student_tuples, key=itemgetter(2))\n" +"[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]\n" +"\n" +">>> sorted(student_objects, key=attrgetter('age'))\n" +"[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]" +msgstr "" + #: howto/sorting.rst:123 msgid "" "The operator module functions allow multiple levels of sorting. For example, " @@ -167,6 +235,15 @@ msgstr "" "Operatör modülü fonksiyonları birden fazla seviyede sıralama yapılmasına " "izin verir. Örneğin, *sınıf* ve ardından *yaş*'a göre sıralamak için:" +#: howto/sorting.rst:126 +msgid "" +">>> sorted(student_tuples, key=itemgetter(1,2))\n" +"[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]\n" +"\n" +">>> sorted(student_objects, key=attrgetter('grade', 'age'))\n" +"[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]" +msgstr "" + #: howto/sorting.rst:134 msgid "" "The :mod:`functools` module provides another helpful tool for making key-" @@ -175,6 +252,20 @@ msgid "" "it suitable for use as a key-function." msgstr "" +#: howto/sorting.rst:139 +msgid "" +">>> from functools import partial\n" +">>> from unicodedata import normalize\n" +"\n" +">>> names = 'Zoë Åbjørn Núñez Élana Zeke Abe Nubia Eloise'.split()\n" +"\n" +">>> sorted(names, key=partial(normalize, 'NFD'))\n" +"['Abe', 'Åbjørn', 'Eloise', 'Élana', 'Nubia', 'Núñez', 'Zeke', 'Zoë']\n" +"\n" +">>> sorted(names, key=partial(normalize, 'NFC'))\n" +"['Abe', 'Eloise', 'Nubia', 'Núñez', 'Zeke', 'Zoë', 'Åbjørn', 'Élana']" +msgstr "" + #: howto/sorting.rst:153 msgid "Ascending and Descending" msgstr "Yükselen ve Alçalan" @@ -189,6 +280,15 @@ msgstr "" "parametresi kabul eder. Bu, azalan sıralamaları işaretlemek için kullanılır. " "Örneğin, öğrenci verilerini ters olarak *yaş* sırasına göre elde etmek için:" +#: howto/sorting.rst:159 +msgid "" +">>> sorted(student_tuples, key=itemgetter(2), reverse=True)\n" +"[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]\n" +"\n" +">>> sorted(student_objects, key=attrgetter('age'), reverse=True)\n" +"[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]" +msgstr "" + #: howto/sorting.rst:168 msgid "Sort Stability and Complex Sorts" msgstr "Sıralama Kararlılığı ve Karmaşık Sıralamalar" @@ -204,6 +304,13 @@ msgstr "" "fazla kayıt aynı anahtara sahip olduğunda, orijinal sıralamanın " "korunacağıdır." +#: howto/sorting.rst:174 +msgid "" +">>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]\n" +">>> sorted(data, key=itemgetter(0))\n" +"[('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]" +msgstr "" + #: howto/sorting.rst:180 msgid "" "Notice how the two records for *blue* retain their original order so that " @@ -224,6 +331,15 @@ msgstr "" "ardından artan *yaş* ile sıralamak için, önce *yaş* sıralamasını yapın ve " "ardından *sınıf* kullanarak tekrar sıralayın:" +#: howto/sorting.rst:187 +msgid "" +">>> s = sorted(student_objects, key=attrgetter('age')) # sort on " +"secondary key\n" +">>> sorted(s, key=attrgetter('grade'), reverse=True) # now sort on " +"primary key, descending\n" +"[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]" +msgstr "" + #: howto/sorting.rst:193 msgid "" "This can be abstracted out into a wrapper function that can take a list and " @@ -232,6 +348,17 @@ msgstr "" "Bu, bir listeyi ve alan çiftlerini alıp bunları birden fazla geçişte " "sıralayabilen bir sarmalayıcı fonksiyon oluşturacak şekilde soyutlanabilir." +#: howto/sorting.rst:196 +msgid "" +">>> def multisort(xs, specs):\n" +"... for key, reverse in reversed(specs):\n" +"... xs.sort(key=attrgetter(key), reverse=reverse)\n" +"... return xs\n" +"\n" +">>> multisort(list(student_objects), (('grade', True), ('age', False)))\n" +"[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]" +msgstr "" + #: howto/sorting.rst:206 msgid "" "The `Timsort `_ algorithm used in " @@ -278,6 +405,15 @@ msgstr "" "Örneğin, DSU yaklaşımını kullanarak öğrenci verilerini *sınıf* bazında " "sıralamak için:" +#: howto/sorting.rst:224 +msgid "" +">>> decorated = [(student.grade, i, student) for i, student in " +"enumerate(student_objects)]\n" +">>> decorated.sort()\n" +">>> [student for grade, i, student in decorated] # undecorate\n" +"[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]" +msgstr "" + #: howto/sorting.rst:231 msgid "" "This idiom works because tuples are compared lexicographically; the first " @@ -381,6 +517,10 @@ msgstr "" "anahtar fonksiyon olarak kullanılabilir hale getirmek için :class:`functools." "cmp_to_key` aracını sağlar::" +#: howto/sorting.rst:273 +msgid "sorted(words, key=cmp_to_key(strcoll)) # locale-aware sort order" +msgstr "" + #: howto/sorting.rst:276 msgid "Odds and Ends" msgstr "Tuhaflıklar ve Sonlar" @@ -409,6 +549,17 @@ msgstr "" "şekilde bu etki, parametre olmadan yerleşik :func:`reversed` fonksiyonu iki " "kez kullanılarak da simüle edilebilir:" +#: howto/sorting.rst:288 +msgid "" +">>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]\n" +">>> standard_way = sorted(data, key=itemgetter(0), reverse=True)\n" +">>> double_reversed = list(reversed(sorted(reversed(data), " +"key=itemgetter(0))))\n" +">>> assert standard_way == double_reversed\n" +">>> standard_way\n" +"[('red', 1), ('red', 2), ('blue', 1), ('blue', 2)]" +msgstr "" + #: howto/sorting.rst:297 #, fuzzy msgid "" @@ -420,6 +571,13 @@ msgstr "" "kullanır. Bu nedenle, bir :meth:`__lt__` yöntemi tanımlayarak, bir sınıfa " "standart bir sıralama düzeni eklemek kolaydır:" +#: howto/sorting.rst:301 +msgid "" +">>> Student.__lt__ = lambda self, other: self.age < other.age\n" +">>> sorted(student_objects)\n" +"[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]" +msgstr "" + #: howto/sorting.rst:307 msgid "" "However, note that ``<`` can fall back to using :meth:`~object.__gt__` if :" @@ -441,6 +599,14 @@ msgstr "" "bir sözlükte saklanıyorsa, öğrenci adlarından oluşan ayrı bir listenin " "sıralanmasında da kullanılabilirler:" +#: howto/sorting.rst:319 +msgid "" +">>> students = ['dave', 'john', 'jane']\n" +">>> newgrades = {'john': 'F', 'jane':'A', 'dave': 'C'}\n" +">>> sorted(students, key=newgrades.__getitem__)\n" +"['jane', 'dave', 'john']" +msgstr "" + #: howto/sorting.rst:327 msgid "Partial Sorts" msgstr "" diff --git a/howto/unicode.po b/howto/unicode.po index 728e6fcbf..e1e7cd0d0 100644 --- a/howto/unicode.po +++ b/howto/unicode.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-09-18 19:05+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -89,6 +89,25 @@ msgid "" "corresponding code points:" msgstr "" +#: howto/unicode.rst:53 +msgid "" +"0061 'a'; LATIN SMALL LETTER A\n" +"0062 'b'; LATIN SMALL LETTER B\n" +"0063 'c'; LATIN SMALL LETTER C\n" +"...\n" +"007B '{'; LEFT CURLY BRACKET\n" +"...\n" +"2167 'Ⅷ'; ROMAN NUMERAL EIGHT\n" +"2168 'Ⅸ'; ROMAN NUMERAL NINE\n" +"...\n" +"265E '♞'; BLACK CHESS KNIGHT\n" +"265F '♟'; BLACK CHESS PAWN\n" +"...\n" +"1F600 '😀'; GRINNING FACE\n" +"1F609 '😉'; WINKING FACE\n" +"..." +msgstr "" + #: howto/unicode.rst:71 msgid "" "Strictly, these definitions imply that it's meaningless to say 'this is " @@ -129,6 +148,13 @@ msgid "" "representation, the string \"Python\" might look like this:" msgstr "" +#: howto/unicode.rst:101 +msgid "" +" P y t h o n\n" +"0x50 00 00 00 79 00 00 00 74 00 00 00 68 00 00 00 6f 00 00 00 6e 00 00 00\n" +" 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23" +msgstr "" + #: howto/unicode.rst:107 msgid "" "This representation is straightforward but using it presents a number of " @@ -296,11 +322,28 @@ msgid "" "include a Unicode character in a string literal::" msgstr "" +#: howto/unicode.rst:199 +msgid "" +"try:\n" +" with open('/tmp/input.txt', 'r') as f:\n" +" ...\n" +"except OSError:\n" +" # 'File not found' error message.\n" +" print(\"Fichier non trouvé\")" +msgstr "" + #: howto/unicode.rst:206 msgid "" "Side note: Python 3 also supports using Unicode characters in identifiers::" msgstr "" +#: howto/unicode.rst:208 +msgid "" +"répertoire = \"/tmp/records.log\"\n" +"with open(répertoire, \"w\") as f:\n" +" f.write(\"test\\n\")" +msgstr "" + #: howto/unicode.rst:212 msgid "" "If you can't enter a particular character in your editor or want to keep the " @@ -309,6 +352,16 @@ msgid "" "delta glyph instead of a \\u escape.) ::" msgstr "" +#: howto/unicode.rst:217 +msgid "" +">>> \"\\N{GREEK CAPITAL LETTER DELTA}\" # Using the character name\n" +"'\\u0394'\n" +">>> \"\\u0394\" # Using a 16-bit hex value\n" +"'\\u0394'\n" +">>> \"\\U00000394\" # Using a 32-bit hex value\n" +"'\\u0394'" +msgstr "" + #: howto/unicode.rst:224 msgid "" "In addition, one can create a string using the :func:`~bytes.decode` method " @@ -327,6 +380,21 @@ msgid "" "examples show the differences::" msgstr "" +#: howto/unicode.rst:236 +msgid "" +">>> b'\\x80abc'.decode(\"utf-8\", \"strict\") \n" +"Traceback (most recent call last):\n" +" ...\n" +"UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0:\n" +" invalid start byte\n" +">>> b'\\x80abc'.decode(\"utf-8\", \"replace\")\n" +"'\\ufffdabc'\n" +">>> b'\\x80abc'.decode(\"utf-8\", \"backslashreplace\")\n" +"'\\\\x80abc'\n" +">>> b'\\x80abc'.decode(\"utf-8\", \"ignore\")\n" +"'abc'" +msgstr "" + #: howto/unicode.rst:248 msgid "" "Encodings are specified as strings containing the encoding's name. Python " @@ -345,6 +413,14 @@ msgid "" "returns the code point value::" msgstr "" +#: howto/unicode.rst:260 +msgid "" +">>> chr(57344)\n" +"'\\ue000'\n" +">>> ord('\\ue000')\n" +"57344" +msgstr "" + #: howto/unicode.rst:266 msgid "Converting to Bytes" msgstr "" @@ -371,6 +447,28 @@ msgstr "" msgid "The following example shows the different results::" msgstr "" +#: howto/unicode.rst:282 +msgid "" +">>> u = chr(40960) + 'abcd' + chr(1972)\n" +">>> u.encode('utf-8')\n" +"b'\\xea\\x80\\x80abcd\\xde\\xb4'\n" +">>> u.encode('ascii') \n" +"Traceback (most recent call last):\n" +" ...\n" +"UnicodeEncodeError: 'ascii' codec can't encode character '\\ua000' in\n" +" position 0: ordinal not in range(128)\n" +">>> u.encode('ascii', 'ignore')\n" +"b'abcd'\n" +">>> u.encode('ascii', 'replace')\n" +"b'?abcd?'\n" +">>> u.encode('ascii', 'xmlcharrefreplace')\n" +"b'ꀀabcd޴'\n" +">>> u.encode('ascii', 'backslashreplace')\n" +"b'\\\\ua000abcd\\\\u07b4'\n" +">>> u.encode('ascii', 'namereplace')\n" +"b'\\\\N{YI SYLLABLE IT}abcd\\\\u07b4'" +msgstr "" + #: howto/unicode.rst:301 msgid "" "The low-level routines for registering and accessing the available encodings " @@ -393,6 +491,16 @@ msgid "" "digits, not four::" msgstr "" +#: howto/unicode.rst:317 +msgid "" +">>> s = \"a\\xac\\u1234\\u20ac\\U00008000\"\n" +"... # ^^^^ two-digit hex escape\n" +"... # ^^^^^^ four-digit Unicode escape\n" +"... # ^^^^^^^^^^ eight-digit Unicode escape\n" +">>> [ord(c) for c in s]\n" +"[97, 172, 4660, 8364, 32768]" +msgstr "" + #: howto/unicode.rst:324 msgid "" "Using escape sequences for code points greater than 127 is fine in small " @@ -418,6 +526,15 @@ msgid "" "file::" msgstr "" +#: howto/unicode.rst:339 +msgid "" +"#!/usr/bin/env python\n" +"# -*- coding: latin-1 -*-\n" +"\n" +"u = 'abcdé'\n" +"print(ord(u[-1]))" +msgstr "" + #: howto/unicode.rst:345 msgid "" "The syntax is inspired by Emacs's notation for specifying variables local to " @@ -453,10 +570,34 @@ msgid "" "and prints the numeric value of one particular character::" msgstr "" +#: howto/unicode.rst:369 +msgid "" +"import unicodedata\n" +"\n" +"u = chr(233) + chr(0x0bf2) + chr(3972) + chr(6000) + chr(13231)\n" +"\n" +"for i, c in enumerate(u):\n" +" print(i, '%04x' % ord(c), unicodedata.category(c), end=\" \")\n" +" print(unicodedata.name(c))\n" +"\n" +"# Get numeric value of second character\n" +"print(unicodedata.numeric(u[1]))" +msgstr "" + #: howto/unicode.rst:380 msgid "When run, this prints:" msgstr "" +#: howto/unicode.rst:382 +msgid "" +"0 00e9 Ll LATIN SMALL LETTER E WITH ACUTE\n" +"1 0bf2 No TAMIL NUMBER ONE THOUSAND\n" +"2 0f84 Mn TIBETAN MARK HALANTA\n" +"3 1770 Lo TAGBANWA LETTER SA\n" +"4 33af So SQUARE RAD OVER S SQUARED\n" +"1000.0" +msgstr "" + #: howto/unicode.rst:391 msgid "" "The category codes are abbreviations describing the nature of the character. " @@ -493,6 +634,13 @@ msgid "" "which becomes the pair of lowercase letters 'ss'." msgstr "" +#: howto/unicode.rst:421 +msgid "" +">>> street = 'Gürzenichstraße'\n" +">>> street.casefold()\n" +"'gürzenichstrasse'" +msgstr "" + #: howto/unicode.rst:425 msgid "" "A second tool is the :mod:`unicodedata` module's :func:`~unicodedata." @@ -503,10 +651,36 @@ msgid "" "combining characters differently:" msgstr "" +#: howto/unicode.rst:434 +msgid "" +"import unicodedata\n" +"\n" +"def compare_strs(s1, s2):\n" +" def NFD(s):\n" +" return unicodedata.normalize('NFD', s)\n" +"\n" +" return NFD(s1) == NFD(s2)\n" +"\n" +"single_char = 'ê'\n" +"multiple_chars = '\\N{LATIN SMALL LETTER E}\\N{COMBINING CIRCUMFLEX " +"ACCENT}'\n" +"print('length of first string=', len(single_char))\n" +"print('length of second string=', len(multiple_chars))\n" +"print(compare_strs(single_char, multiple_chars))" +msgstr "" + #: howto/unicode.rst:448 msgid "When run, this outputs:" msgstr "" +#: howto/unicode.rst:450 +msgid "" +"$ python compare-strs.py\n" +"length of first string= 1\n" +"length of second string= 2\n" +"True" +msgstr "" + #: howto/unicode.rst:457 msgid "" "The first argument to the :func:`~unicodedata.normalize` function is a " @@ -518,6 +692,24 @@ msgstr "" msgid "The Unicode Standard also specifies how to do caseless comparisons::" msgstr "" +#: howto/unicode.rst:463 +msgid "" +"import unicodedata\n" +"\n" +"def compare_caseless(s1, s2):\n" +" def NFD(s):\n" +" return unicodedata.normalize('NFD', s)\n" +"\n" +" return NFD(NFD(s1).casefold()) == NFD(NFD(s2).casefold())\n" +"\n" +"# Example usage\n" +"single_char = 'ê'\n" +"multiple_chars = '\\N{LATIN CAPITAL LETTER E}\\N{COMBINING CIRCUMFLEX " +"ACCENT}'\n" +"\n" +"print(compare_caseless(single_char, multiple_chars))" +msgstr "" + #: howto/unicode.rst:477 msgid "" "This will print ``True``. (Why is :func:`!NFD` invoked twice? Because " @@ -546,6 +738,16 @@ msgid "" "numerals::" msgstr "" +#: howto/unicode.rst:496 +msgid "" +"import re\n" +"p = re.compile(r'\\d+')\n" +"\n" +"s = \"Over \\u0e55\\u0e57 57 flavours\"\n" +"m = p.search(s)\n" +"print(repr(m.group()))" +msgstr "" + #: howto/unicode.rst:503 msgid "" "When executed, ``\\d+`` will match the Thai numerals and print them out. If " @@ -658,12 +860,27 @@ msgstr "" msgid "Reading Unicode from a file is therefore simple::" msgstr "" +#: howto/unicode.rst:576 +msgid "" +"with open('unicode.txt', encoding='utf-8') as f:\n" +" for line in f:\n" +" print(repr(line))" +msgstr "" + #: howto/unicode.rst:580 msgid "" "It's also possible to open files in update mode, allowing both reading and " "writing::" msgstr "" +#: howto/unicode.rst:583 +msgid "" +"with open('test', encoding='utf-8', mode='w+') as f:\n" +" f.write('\\u4500 blah blah blah\\n')\n" +" f.seek(0)\n" +" print(repr(f.readline()[:1]))" +msgstr "" + #: howto/unicode.rst:588 msgid "" "The Unicode character ``U+FEFF`` is used as a byte-order mark (BOM), and is " @@ -712,6 +929,13 @@ msgid "" "and it will be automatically converted to the right encoding for you::" msgstr "" +#: howto/unicode.rst:622 +msgid "" +"filename = 'filename\\u4500abc'\n" +"with open(filename, 'w') as f:\n" +" f.write('blah\\n')" +msgstr "" + #: howto/unicode.rst:626 msgid "" "Functions in the :mod:`os` module such as :func:`os.stat` will also accept " @@ -731,10 +955,28 @@ msgid "" "error handler>` is UTF-8, running the following program::" msgstr "" +#: howto/unicode.rst:639 +msgid "" +"fn = 'filename\\u4500abc'\n" +"f = open(fn, 'w')\n" +"f.close()\n" +"\n" +"import os\n" +"print(os.listdir(b'.'))\n" +"print(os.listdir('.'))" +msgstr "" + #: howto/unicode.rst:647 msgid "will produce the following output:" msgstr "" +#: howto/unicode.rst:649 +msgid "" +"$ python listdir-test.py\n" +"[b'filename\\xe4\\x94\\x80abc', ...]\n" +"['filename\\u4500abc', ...]" +msgstr "" + #: howto/unicode.rst:655 msgid "" "The first list contains UTF-8-encoded filenames, and the second list " @@ -807,6 +1049,17 @@ msgid "" "it with a :class:`~codecs.StreamRecoder` to return bytes encoded in UTF-8::" msgstr "" +#: howto/unicode.rst:701 +msgid "" +"new_f = codecs.StreamRecoder(f,\n" +" # en/decoder: used by read() to encode its results and\n" +" # by write() to decode its input.\n" +" codecs.getencoder('utf-8'), codecs.getdecoder('utf-8'),\n" +"\n" +" # reader/writer: used to read and write to the stream.\n" +" codecs.getreader('latin-1'), codecs.getwriter('latin-1') )" +msgstr "" + #: howto/unicode.rst:711 msgid "Files in an Unknown Encoding" msgstr "" @@ -819,6 +1072,18 @@ msgid "" "``surrogateescape`` error handler::" msgstr "" +#: howto/unicode.rst:718 +msgid "" +"with open(fname, 'r', encoding=\"ascii\", errors=\"surrogateescape\") as f:\n" +" data = f.read()\n" +"\n" +"# make changes to the string 'data'\n" +"\n" +"with open(fname + '.new', 'w',\n" +" encoding=\"ascii\", errors=\"surrogateescape\") as f:\n" +" f.write(data)" +msgstr "" + #: howto/unicode.rst:727 msgid "" "The ``surrogateescape`` error handler will decode any non-ASCII bytes as " diff --git a/howto/urllib2.po b/howto/urllib2.po index 9dcf55768..3dd95b5c0 100644 --- a/howto/urllib2.po +++ b/howto/urllib2.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -87,6 +87,13 @@ msgstr "" msgid "The simplest way to use urllib.request is as follows::" msgstr "" +#: howto/urllib2.rst:48 +msgid "" +"import urllib.request\n" +"with urllib.request.urlopen('http://python.org/') as response:\n" +" html = response.read()" +msgstr "" + #: howto/urllib2.rst:52 msgid "" "If you wish to retrieve a resource via URL and store it in a temporary " @@ -94,6 +101,20 @@ msgid "" "`tempfile.NamedTemporaryFile` functions::" msgstr "" +#: howto/urllib2.rst:56 +msgid "" +"import shutil\n" +"import tempfile\n" +"import urllib.request\n" +"\n" +"with urllib.request.urlopen('http://python.org/') as response:\n" +" with tempfile.NamedTemporaryFile(delete=False) as tmp_file:\n" +" shutil.copyfileobj(response, tmp_file)\n" +"\n" +"with open(tmp_file.name) as html:\n" +" pass" +msgstr "" + #: howto/urllib2.rst:67 msgid "" "Many uses of urllib will be that simple (note that instead of an 'http:' URL " @@ -113,12 +134,25 @@ msgid "" "for example call ``.read()`` on the response::" msgstr "" +#: howto/urllib2.rst:80 +msgid "" +"import urllib.request\n" +"\n" +"req = urllib.request.Request('http://python.org/')\n" +"with urllib.request.urlopen(req) as response:\n" +" the_page = response.read()" +msgstr "" + #: howto/urllib2.rst:86 msgid "" "Note that urllib.request makes use of the same Request interface to handle " "all URL schemes. For example, you can make an FTP request like so::" msgstr "" +#: howto/urllib2.rst:89 +msgid "req = urllib.request.Request('ftp://example.com/')" +msgstr "" + #: howto/urllib2.rst:91 msgid "" "In the case of HTTP, there are two extra things that Request objects allow " @@ -145,6 +179,23 @@ msgid "" "function from the :mod:`urllib.parse` library. ::" msgstr "" +#: howto/urllib2.rst:110 +msgid "" +"import urllib.parse\n" +"import urllib.request\n" +"\n" +"url = 'http://www.someserver.com/cgi-bin/register.cgi'\n" +"values = {'name' : 'Michael Foord',\n" +" 'location' : 'Northampton',\n" +" 'language' : 'Python' }\n" +"\n" +"data = urllib.parse.urlencode(values)\n" +"data = data.encode('ascii') # data should be bytes\n" +"req = urllib.request.Request(url, data)\n" +"with urllib.request.urlopen(req) as response:\n" +" the_page = response.read()" +msgstr "" + #: howto/urllib2.rst:124 msgid "" "Note that other encodings are sometimes required (e.g. for file upload from " @@ -169,6 +220,22 @@ msgstr "" msgid "This is done as follows::" msgstr "" +#: howto/urllib2.rst:141 +msgid "" +">>> import urllib.request\n" +">>> import urllib.parse\n" +">>> data = {}\n" +">>> data['name'] = 'Somebody Here'\n" +">>> data['location'] = 'Northampton'\n" +">>> data['language'] = 'Python'\n" +">>> url_values = urllib.parse.urlencode(data)\n" +">>> print(url_values) # The order may differ from below. \n" +"name=Somebody+Here&language=Python&location=Northampton\n" +">>> url = 'http://www.example.com/example.cgi'\n" +">>> full_url = url + '?' + url_values\n" +">>> data = urllib.request.urlopen(full_url)" +msgstr "" + #: howto/urllib2.rst:154 msgid "" "Notice that the full URL is created by adding a ``?`` to the URL, followed " @@ -198,6 +265,25 @@ msgid "" "Explorer [#]_. ::" msgstr "" +#: howto/urllib2.rst:174 +msgid "" +"import urllib.parse\n" +"import urllib.request\n" +"\n" +"url = 'http://www.someserver.com/cgi-bin/register.cgi'\n" +"user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'\n" +"values = {'name': 'Michael Foord',\n" +" 'location': 'Northampton',\n" +" 'language': 'Python' }\n" +"headers = {'User-Agent': user_agent}\n" +"\n" +"data = urllib.parse.urlencode(values)\n" +"data = data.encode('ascii')\n" +"req = urllib.request.Request(url, data, headers)\n" +"with urllib.request.urlopen(req) as response:\n" +" the_page = response.read()" +msgstr "" + #: howto/urllib2.rst:190 msgid "" "The response also has two useful methods. See the section on `info and " @@ -242,6 +328,16 @@ msgstr "" msgid "e.g. ::" msgstr "" +#: howto/urllib2.rst:216 +msgid "" +">>> req = urllib.request.Request('http://www.pretend_server.org')\n" +">>> try: urllib.request.urlopen(req)\n" +"... except urllib.error.URLError as e:\n" +"... print(e.reason) \n" +"...\n" +"(4, 'getaddrinfo failed')" +msgstr "" + #: howto/urllib2.rst:225 msgid "HTTPError" msgstr "" @@ -287,6 +383,77 @@ msgid "" "The dictionary is reproduced here for convenience ::" msgstr "" +#: howto/urllib2.rst:251 +msgid "" +"# Table mapping response codes to messages; entries have the\n" +"# form {code: (shortmessage, longmessage)}.\n" +"responses = {\n" +" 100: ('Continue', 'Request received, please continue'),\n" +" 101: ('Switching Protocols',\n" +" 'Switching to new protocol; obey Upgrade header'),\n" +"\n" +" 200: ('OK', 'Request fulfilled, document follows'),\n" +" 201: ('Created', 'Document created, URL follows'),\n" +" 202: ('Accepted',\n" +" 'Request accepted, processing continues off-line'),\n" +" 203: ('Non-Authoritative Information', 'Request fulfilled from cache'),\n" +" 204: ('No Content', 'Request fulfilled, nothing follows'),\n" +" 205: ('Reset Content', 'Clear input form for further input.'),\n" +" 206: ('Partial Content', 'Partial content follows.'),\n" +"\n" +" 300: ('Multiple Choices',\n" +" 'Object has several resources -- see URI list'),\n" +" 301: ('Moved Permanently', 'Object moved permanently -- see URI list'),\n" +" 302: ('Found', 'Object moved temporarily -- see URI list'),\n" +" 303: ('See Other', 'Object moved -- see Method and URL list'),\n" +" 304: ('Not Modified',\n" +" 'Document has not changed since given time'),\n" +" 305: ('Use Proxy',\n" +" 'You must use proxy specified in Location to access this '\n" +" 'resource.'),\n" +" 307: ('Temporary Redirect',\n" +" 'Object moved temporarily -- see URI list'),\n" +"\n" +" 400: ('Bad Request',\n" +" 'Bad request syntax or unsupported method'),\n" +" 401: ('Unauthorized',\n" +" 'No permission -- see authorization schemes'),\n" +" 402: ('Payment Required',\n" +" 'No payment -- see charging schemes'),\n" +" 403: ('Forbidden',\n" +" 'Request forbidden -- authorization will not help'),\n" +" 404: ('Not Found', 'Nothing matches the given URI'),\n" +" 405: ('Method Not Allowed',\n" +" 'Specified method is invalid for this server.'),\n" +" 406: ('Not Acceptable', 'URI not available in preferred format.'),\n" +" 407: ('Proxy Authentication Required', 'You must authenticate with '\n" +" 'this proxy before proceeding.'),\n" +" 408: ('Request Timeout', 'Request timed out; try again later.'),\n" +" 409: ('Conflict', 'Request conflict.'),\n" +" 410: ('Gone',\n" +" 'URI no longer exists and has been permanently removed.'),\n" +" 411: ('Length Required', 'Client must specify Content-Length.'),\n" +" 412: ('Precondition Failed', 'Precondition in headers is false.'),\n" +" 413: ('Request Entity Too Large', 'Entity is too large.'),\n" +" 414: ('Request-URI Too Long', 'URI is too long.'),\n" +" 415: ('Unsupported Media Type', 'Entity body in unsupported format.'),\n" +" 416: ('Requested Range Not Satisfiable',\n" +" 'Cannot satisfy request range.'),\n" +" 417: ('Expectation Failed',\n" +" 'Expect condition could not be satisfied.'),\n" +"\n" +" 500: ('Internal Server Error', 'Server got itself in trouble'),\n" +" 501: ('Not Implemented',\n" +" 'Server does not support this operation'),\n" +" 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),\n" +" 503: ('Service Unavailable',\n" +" 'The server cannot process the request due to a high load'),\n" +" 504: ('Gateway Timeout',\n" +" 'The gateway server did not receive a timely response'),\n" +" 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),\n" +" }" +msgstr "" + #: howto/urllib2.rst:319 msgid "" "When an error is raised the server responds by returning an HTTP error code " @@ -296,6 +463,24 @@ msgid "" "``urllib.response`` module::" msgstr "" +#: howto/urllib2.rst:324 +msgid "" +">>> req = urllib.request.Request('http://www.python.org/fish.html')\n" +">>> try:\n" +"... urllib.request.urlopen(req)\n" +"... except urllib.error.HTTPError as e:\n" +"... print(e.code)\n" +"... print(e.read()) \n" +"...\n" +"404\n" +"b'\\n\\n\\nPage Not Found\\n\n" +" ..." +msgstr "" + #: howto/urllib2.rst:339 msgid "Wrapping it Up" msgstr "" @@ -311,6 +496,23 @@ msgstr "" msgid "Number 1" msgstr "" +#: howto/urllib2.rst:350 +msgid "" +"from urllib.request import Request, urlopen\n" +"from urllib.error import URLError, HTTPError\n" +"req = Request(someurl)\n" +"try:\n" +" response = urlopen(req)\n" +"except HTTPError as e:\n" +" print('The server couldn\\'t fulfill the request.')\n" +" print('Error code: ', e.code)\n" +"except URLError as e:\n" +" print('We failed to reach a server.')\n" +" print('Reason: ', e.reason)\n" +"else:\n" +" # everything is fine" +msgstr "" + #: howto/urllib2.rst:367 msgid "" "The ``except HTTPError`` *must* come first, otherwise ``except URLError`` " @@ -321,6 +523,24 @@ msgstr "" msgid "Number 2" msgstr "" +#: howto/urllib2.rst:375 +msgid "" +"from urllib.request import Request, urlopen\n" +"from urllib.error import URLError\n" +"req = Request(someurl)\n" +"try:\n" +" response = urlopen(req)\n" +"except URLError as e:\n" +" if hasattr(e, 'reason'):\n" +" print('We failed to reach a server.')\n" +" print('Reason: ', e.reason)\n" +" elif hasattr(e, 'code'):\n" +" print('The server couldn\\'t fulfill the request.')\n" +" print('Error code: ', e.code)\n" +"else:\n" +" # everything is fine" +msgstr "" + #: howto/urllib2.rst:392 msgid "info and geturl" msgstr "" @@ -436,6 +656,10 @@ msgstr "" msgid "e.g." msgstr "" +#: howto/urllib2.rst:463 +msgid "WWW-Authenticate: Basic realm=\"cPanel Users\"" +msgstr "" + #: howto/urllib2.rst:468 msgid "" "The client should then retry the request with the appropriate name and " @@ -463,6 +687,29 @@ msgid "" "\"deeper\" than the URL you pass to .add_password() will also match. ::" msgstr "" +#: howto/urllib2.rst:486 +msgid "" +"# create a password manager\n" +"password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()\n" +"\n" +"# Add the username and password.\n" +"# If we knew the realm, we could use it instead of None.\n" +"top_level_url = \"http://example.com/foo/\"\n" +"password_mgr.add_password(None, top_level_url, username, password)\n" +"\n" +"handler = urllib.request.HTTPBasicAuthHandler(password_mgr)\n" +"\n" +"# create \"opener\" (OpenerDirector instance)\n" +"opener = urllib.request.build_opener(handler)\n" +"\n" +"# use the opener to fetch a URL\n" +"opener.open(a_url)\n" +"\n" +"# Install the opener.\n" +"# Now all calls to urllib.request.urlopen use our opener.\n" +"urllib.request.install_opener(opener)" +msgstr "" + #: howto/urllib2.rst:508 msgid "" "In the above example we only supplied our ``HTTPBasicAuthHandler`` to " @@ -498,6 +745,13 @@ msgid "" "similar steps to setting up a `Basic Authentication`_ handler: ::" msgstr "" +#: howto/urllib2.rst:534 +msgid "" +">>> proxy_support = urllib.request.ProxyHandler({})\n" +">>> opener = urllib.request.build_opener(proxy_support)\n" +">>> urllib.request.install_opener(opener)" +msgstr "" + #: howto/urllib2.rst:540 msgid "" "Currently ``urllib.request`` *does not* support fetching of ``https`` " @@ -531,6 +785,21 @@ msgid "" "sockets using ::" msgstr "" +#: howto/urllib2.rst:562 +msgid "" +"import socket\n" +"import urllib.request\n" +"\n" +"# timeout in seconds\n" +"timeout = 10\n" +"socket.setdefaulttimeout(timeout)\n" +"\n" +"# this call to urllib.request.urlopen now uses the default timeout\n" +"# we have set in the socket module\n" +"req = urllib.request.Request('http://www.voidspace.org.uk')\n" +"response = urllib.request.urlopen(req)" +msgstr "" + #: howto/urllib2.rst:579 msgid "Footnotes" msgstr "" diff --git a/installing/index.po b/installing/index.po index 68b560829..9df8df848 100644 --- a/installing/index.po +++ b/installing/index.po @@ -6,7 +6,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-09-18 22:33+0300\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: 2023-02-01 17:47-0500\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -194,6 +194,10 @@ msgstr "" "Aşağıdaki komut, bir modülün en son sürümünü ve bağımlılıklarını Python " "Paket Dizininden yükleyecektir::" +#: installing/index.rst:84 +msgid "python -m pip install SomePackage" +msgstr "" + #: installing/index.rst:88 msgid "" "For POSIX users (including macOS and Linux users), the examples in this " @@ -225,6 +229,12 @@ msgstr "" "yorumlanan diğer bazı özel karakterler kullanılırken, paket adı ve sürüm " "çift tırnak içine alınmalıdır::" +#: installing/index.rst:100 +msgid "" +"python -m pip install SomePackage==1.0.4 # specific version\n" +"python -m pip install \"SomePackage>=1.0.4\" # minimum version" +msgstr "" + #: installing/index.rst:103 msgid "" "Normally, if a suitable module is already installed, attempting to install " @@ -234,6 +244,10 @@ msgstr "" "Normalde, uygun bir modül zaten kuruluysa, onu tekrar kurmayı denemenin bir " "etkisi olmaz. Mevcut modüllerin yükseltilmesi açıkça talep edilmelidir::" +#: installing/index.rst:107 +msgid "python -m pip install --upgrade SomePackage" +msgstr "" + #: installing/index.rst:109 msgid "" "More information and resources regarding ``pip`` and its capabilities can be " @@ -346,6 +360,14 @@ msgstr "" "çalıştırmak için ``-m`` anahtarıyla birlikte sürümlü Python komutlarını " "kullanın::" +#: installing/index.rst:171 +msgid "" +"python2 -m pip install SomePackage # default Python 2\n" +"python2.7 -m pip install SomePackage # specifically Python 2.7\n" +"python3 -m pip install SomePackage # default Python 3\n" +"python3.4 -m pip install SomePackage # specifically Python 3.4" +msgstr "" + #: installing/index.rst:176 msgid "Appropriately versioned ``pip`` commands may also be available." msgstr "Uygun sürüme sahip ``pip`` komutları da mevcut olabilir." @@ -358,6 +380,14 @@ msgstr "" "Windows'ta, ``py`` Python başlatıcısını ``-m`` anahtarıyla birlikte " "kullanın::" +#: installing/index.rst:181 +msgid "" +"py -2 -m pip install SomePackage # default Python 2\n" +"py -2.7 -m pip install SomePackage # specifically Python 2.7\n" +"py -3 -m pip install SomePackage # default Python 3\n" +"py -3.4 -m pip install SomePackage # specifically Python 3.4" +msgstr "" + #: installing/index.rst:195 msgid "Common installation issues" msgstr "Genel yükleme sorunları" @@ -399,6 +429,10 @@ msgid "" msgstr "" "``pip`` 'in varsayılan olarak yüklenmemesi mümkündür. Bir olası düzeltme::" +#: installing/index.rst:215 +msgid "python -m ensurepip --default-pip" +msgstr "" + #: installing/index.rst:217 msgid "" "There are also additional resources for `installing pip. \n" @@ -57,10 +57,23 @@ msgstr "" msgid "Here is a sample Python 2.x source file, :file:`example.py`::" msgstr "" +#: library/2to3.rst:33 +msgid "" +"def greet(name):\n" +" print \"Hello, {0}!\".format(name)\n" +"print \"What's your name?\"\n" +"name = raw_input()\n" +"greet(name)" +msgstr "" + #: library/2to3.rst:39 msgid "It can be converted to Python 3.x code via 2to3 on the command line:" msgstr "" +#: library/2to3.rst:41 +msgid "$ 2to3 example.py" +msgstr "" + #: library/2to3.rst:45 msgid "" "A diff against the original source file is printed. 2to3 can also write the " @@ -69,10 +82,23 @@ msgid "" "changes back is enabled with the :option:`!-w` flag:" msgstr "" +#: library/2to3.rst:50 +msgid "$ 2to3 -w example.py" +msgstr "" + #: library/2to3.rst:54 msgid "After transformation, :file:`example.py` looks like this::" msgstr "" +#: library/2to3.rst:56 +msgid "" +"def greet(name):\n" +" print(\"Hello, {0}!\".format(name))\n" +"print(\"What's your name?\")\n" +"name = input()\n" +"greet(name)" +msgstr "" + #: library/2to3.rst:62 msgid "" "Comments and exact indentation are preserved throughout the translation " @@ -88,10 +114,18 @@ msgid "" "``has_key`` fixers:" msgstr "" +#: library/2to3.rst:69 +msgid "$ 2to3 -f imports -f has_key example.py" +msgstr "" + #: library/2to3.rst:73 msgid "This command runs every fixer except the ``apply`` fixer:" msgstr "" +#: library/2to3.rst:75 +msgid "$ 2to3 -x apply example.py" +msgstr "" + #: library/2to3.rst:79 msgid "" "Some fixers are *explicit*, meaning they aren't run by default and must be " @@ -99,6 +133,10 @@ msgid "" "fixers, the ``idioms`` fixer is run:" msgstr "" +#: library/2to3.rst:83 +msgid "$ 2to3 -f all -f idioms example.py" +msgstr "" + #: library/2to3.rst:87 msgid "Notice how passing ``all`` enables all default fixers." msgstr "" @@ -169,6 +207,10 @@ msgid "" "as backups are not necessary when writing to different filenames. Example:" msgstr "" +#: library/2to3.rst:131 +msgid "$ 2to3 -n -W --add-suffix=3 example.py" +msgstr "" + #: library/2to3.rst:135 msgid "Will cause a converted file named ``example.py3`` to be written." msgstr "" @@ -181,6 +223,10 @@ msgstr "" msgid "To translate an entire project from one directory tree to another use:" msgstr "" +#: library/2to3.rst:142 +msgid "$ 2to3 --output-dir=python3-version/mycode -W -n python2-version/mycode" +msgstr "" + #: library/2to3.rst:150 msgid "Fixers" msgstr "" @@ -360,10 +406,20 @@ msgid "" "func:`sorted` in appropriate places. For example, this block ::" msgstr "" +#: library/2to3.rst:262 +msgid "" +"L = list(some_iterable)\n" +"L.sort()" +msgstr "" + #: library/2to3.rst:265 msgid "is changed to ::" msgstr "" +#: library/2to3.rst:267 +msgid "L = sorted(some_iterable)" +msgstr "" + #: library/2to3.rst:271 msgid "Detects sibling imports and converts them to relative imports." msgstr "" diff --git a/library/__future__.po b/library/__future__.po index d953c3162..424a4b877 100644 --- a/library/__future__.po +++ b/library/__future__.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -217,12 +217,29 @@ msgstr "" msgid "Each statement in :file:`__future__.py` is of the form::" msgstr "" +#: library/__future__.rst:79 +msgid "" +"FeatureName = _Feature(OptionalRelease, MandatoryRelease,\n" +" CompilerFlag)" +msgstr "" + #: library/__future__.rst:82 msgid "" "where, normally, *OptionalRelease* is less than *MandatoryRelease*, and both " "are 5-tuples of the same form as :data:`sys.version_info`::" msgstr "" +#: library/__future__.rst:85 +msgid "" +"(PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int\n" +" PY_MINOR_VERSION, # the 1; an int\n" +" PY_MICRO_VERSION, # the 0; an int\n" +" PY_RELEASE_LEVEL, # \"alpha\", \"beta\", \"candidate\" or \"final\"; " +"string\n" +" PY_RELEASE_SERIAL # the 3; an int\n" +")" +msgstr "" + #: library/__future__.rst:94 msgid "" "*OptionalRelease* records the first release in which the feature was " diff --git a/library/__main__.po b/library/__main__.po index 37c58d758..cb28b7b93 100644 --- a/library/__main__.po +++ b/library/__main__.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -55,12 +55,26 @@ msgid "" "the ``.py`` extension::" msgstr "" +#: library/__main__.rst:31 +msgid "" +">>> import configparser\n" +">>> configparser.__name__\n" +"'configparser'" +msgstr "" + #: library/__main__.rst:35 msgid "" "If the file is part of a package, ``__name__`` will also include the parent " "package's path::" msgstr "" +#: library/__main__.rst:38 +msgid "" +">>> from concurrent.futures import process\n" +">>> process.__name__\n" +"'concurrent.futures.process'" +msgstr "" + #: library/__main__.rst:42 msgid "" "However, if the module is executed in the top-level code environment, its " @@ -88,25 +102,63 @@ msgstr "" msgid "the scope of an interactive prompt::" msgstr "" +#: library/__main__.rst:57 +msgid "" +">>> __name__\n" +"'__main__'" +msgstr "" + #: library/__main__.rst:60 msgid "the Python module passed to the Python interpreter as a file argument:" msgstr "" +#: library/__main__.rst:62 +msgid "" +"$ python helloworld.py\n" +"Hello, world!" +msgstr "" + #: library/__main__.rst:67 msgid "" "the Python module or package passed to the Python interpreter with the :" "option:`-m` argument:" msgstr "" +#: library/__main__.rst:70 +msgid "" +"$ python -m tarfile\n" +"usage: tarfile.py [-h] [-v] (...)" +msgstr "" + #: library/__main__.rst:75 msgid "Python code read by the Python interpreter from standard input:" msgstr "" +#: library/__main__.rst:77 +msgid "" +"$ echo \"import this\" | python\n" +"The Zen of Python, by Tim Peters\n" +"\n" +"Beautiful is better than ugly.\n" +"Explicit is better than implicit.\n" +"..." +msgstr "" + #: library/__main__.rst:86 msgid "" "Python code passed to the Python interpreter with the :option:`-c` argument:" msgstr "" +#: library/__main__.rst:88 +msgid "" +"$ python -c \"import this\"\n" +"The Zen of Python, by Tim Peters\n" +"\n" +"Beautiful is better than ugly.\n" +"Explicit is better than implicit.\n" +"..." +msgstr "" + #: library/__main__.rst:97 msgid "" "In each of these situations, the top-level module's ``__name__`` is set to " @@ -121,6 +173,13 @@ msgid "" "from an import statement::" msgstr "" +#: library/__main__.rst:105 +msgid "" +"if __name__ == '__main__':\n" +" # Execute when the module is not initialized from an import statement.\n" +" ..." +msgstr "" + #: library/__main__.rst:111 msgid "" "For a more detailed look at how ``__name__`` is set in all situations, see " @@ -153,6 +212,29 @@ msgid "" "function named ``main`` encapsulates the program's primary behavior::" msgstr "" +#: library/__main__.rst:131 +msgid "" +"# echo.py\n" +"\n" +"import shlex\n" +"import sys\n" +"\n" +"def echo(phrase: str) -> None:\n" +" \"\"\"A dummy wrapper around print.\"\"\"\n" +" # for demonstration purposes, you can imagine that there is some\n" +" # valuable and reusable logic inside this function\n" +" print(phrase)\n" +"\n" +"def main() -> int:\n" +" \"\"\"Echo the input arguments to standard output\"\"\"\n" +" phrase = shlex.join(sys.argv)\n" +" echo(phrase)\n" +" return 0\n" +"\n" +"if __name__ == '__main__':\n" +" sys.exit(main()) # next section explains the use of sys.exit" +msgstr "" + #: library/__main__.rst:151 msgid "" "Note that if the module didn't encapsulate code inside the ``main`` function " @@ -183,6 +265,10 @@ msgid "" "return value of ``main`` is passed into :func:`sys.exit`. For example::" msgstr "" +#: library/__main__.rst:173 +msgid "sys.exit(main())" +msgstr "" + #: library/__main__.rst:175 msgid "" "Since the call to ``main`` is wrapped in :func:`sys.exit`, the expectation " @@ -228,12 +314,24 @@ msgid "" "hypothetical package, \"bandclass\":" msgstr "" +#: library/__main__.rst:206 +msgid "" +"bandclass\n" +" ├── __init__.py\n" +" ├── __main__.py\n" +" └── student.py" +msgstr "" + #: library/__main__.rst:213 msgid "" "``__main__.py`` will be executed when the package itself is invoked directly " "from the command line using the :option:`-m` flag. For example:" msgstr "" +#: library/__main__.rst:216 +msgid "$ python -m bandclass" +msgstr "" + #: library/__main__.rst:220 msgid "" "This command will cause ``__main__.py`` to run. How you utilize this " @@ -242,6 +340,17 @@ msgid "" "for students::" msgstr "" +#: library/__main__.rst:225 +msgid "" +"# bandclass/__main__.py\n" +"\n" +"import sys\n" +"from .student import search_students\n" +"\n" +"student_name = sys.argv[1] if len(sys.argv) >= 2 else ''\n" +"print(f'Found student: {search_students(student_name)}')" +msgstr "" + #: library/__main__.rst:233 msgid "" "Note that ``from .student import search_students`` is an example of a " @@ -265,6 +374,13 @@ msgid "" "attribute will include the package's path if imported::" msgstr "" +#: library/__main__.rst:250 +msgid "" +">>> import asyncio.__main__\n" +">>> asyncio.__main__.__name__\n" +"'asyncio.__main__'" +msgstr "" + #: library/__main__.rst:254 msgid "" "This won't work for ``__main__.py`` files in the root directory of a ``." @@ -309,14 +425,59 @@ msgstr "" msgid "Here is an example module that consumes the ``__main__`` namespace::" msgstr "" +#: library/__main__.rst:284 +msgid "" +"# namely.py\n" +"\n" +"import __main__\n" +"\n" +"def did_user_define_their_name():\n" +" return 'my_name' in dir(__main__)\n" +"\n" +"def print_user_name():\n" +" if not did_user_define_their_name():\n" +" raise ValueError('Define the variable `my_name`!')\n" +"\n" +" if '__file__' in dir(__main__):\n" +" print(__main__.my_name, \"found in file\", __main__.__file__)\n" +" else:\n" +" print(__main__.my_name)" +msgstr "" + #: library/__main__.rst:300 msgid "Example usage of this module could be as follows::" msgstr "" +#: library/__main__.rst:302 +msgid "" +"# start.py\n" +"\n" +"import sys\n" +"\n" +"from namely import print_user_name\n" +"\n" +"# my_name = \"Dinsdale\"\n" +"\n" +"def main():\n" +" try:\n" +" print_user_name()\n" +" except ValueError as ve:\n" +" return str(ve)\n" +"\n" +"if __name__ == \"__main__\":\n" +" sys.exit(main())" +msgstr "" + #: library/__main__.rst:319 msgid "Now, if we started our program, the result would look like this:" msgstr "" +#: library/__main__.rst:321 +msgid "" +"$ python start.py\n" +"Define the variable `my_name`!" +msgstr "" + #: library/__main__.rst:326 msgid "" "The exit code of the program would be 1, indicating an error. Uncommenting " @@ -324,6 +485,12 @@ msgid "" "with status code 0, indicating success:" msgstr "" +#: library/__main__.rst:330 +msgid "" +"$ python start.py\n" +"Dinsdale found in file /path/to/start.py" +msgstr "" + #: library/__main__.rst:335 msgid "" "Note that importing ``__main__`` doesn't cause any issues with " @@ -351,6 +518,22 @@ msgid "" "anything defined in the REPL becomes part of the ``__main__`` scope::" msgstr "" +#: library/__main__.rst:351 +msgid "" +">>> import namely\n" +">>> namely.did_user_define_their_name()\n" +"False\n" +">>> namely.print_user_name()\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: Define the variable `my_name`!\n" +">>> my_name = 'Jabberwocky'\n" +">>> namely.did_user_define_their_name()\n" +"True\n" +">>> namely.print_user_name()\n" +"Jabberwocky" +msgstr "" + #: library/__main__.rst:364 msgid "" "Note that in this case the ``__main__`` scope doesn't contain a ``__file__`` " diff --git a/library/_thread.po b/library/_thread.po index 0a5403f00..e4b2dce69 100644 --- a/library/_thread.po +++ b/library/_thread.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -77,8 +77,8 @@ msgstr "" #: library/_thread.rst:60 msgid "" -"Raises an auditing event _thread.start_new_thread with arguments function, " -"args, kwargs." +"Raises an :ref:`auditing event ` ``_thread.start_new_thread`` with " +"arguments ``function``, ``args``, ``kwargs``." msgstr "" #: library/_thread.rst:62 @@ -144,10 +144,8 @@ msgid "" "after which the value may be recycled by the OS)." msgstr "" -#: library/_thread.rst:123 -msgid "" -":ref:`Availability `: Windows, FreeBSD, Linux, macOS, OpenBSD, " -"NetBSD, AIX, DragonFlyBSD." +#: library/_thread.rst:145 +msgid "Availability" msgstr "" #: library/_thread.rst:130 @@ -169,10 +167,6 @@ msgid "" "information)." msgstr "" -#: library/_thread.rst:145 -msgid ":ref:`Availability `: Windows, pthreads." -msgstr "" - #: library/_thread.rst:147 msgid "Unix platforms with POSIX threads support." msgstr "" @@ -244,44 +238,48 @@ msgid "" "`with` statement, e.g.::" msgstr "" +#: library/_thread.rst:202 +msgid "" +"import _thread\n" +"\n" +"a_lock = _thread.allocate_lock()\n" +"\n" +"with a_lock:\n" +" print(\"a_lock is locked while this executes\")" +msgstr "" + #: library/_thread.rst:209 msgid "**Caveats:**" msgstr "" #: library/_thread.rst:213 msgid "" -"Threads interact strangely with interrupts: the :exc:`KeyboardInterrupt` " -"exception will be received by an arbitrary thread. (When the :mod:`signal` " -"module is available, interrupts always go to the main thread.)" +"Interrupts always go to the main thread (the :exc:`KeyboardInterrupt` " +"exception will be received by that thread.)" msgstr "" -#: library/_thread.rst:217 +#: library/_thread.rst:216 msgid "" "Calling :func:`sys.exit` or raising the :exc:`SystemExit` exception is " "equivalent to calling :func:`_thread.exit`." msgstr "" -#: library/_thread.rst:220 +#: library/_thread.rst:219 msgid "" -"It is not possible to interrupt the :meth:`~threading.Lock.acquire` method " -"on a lock --- the :exc:`KeyboardInterrupt` exception will happen after the " -"lock has been acquired." +"It is platform-dependent whether the :meth:`~threading.Lock.acquire` method " +"on a lock can be interrupted (so that the :exc:`KeyboardInterrupt` exception " +"will happen immediately, rather than only after the lock has been acquired " +"or the operation has timed out). It can be interrupted on POSIX, but not on " +"Windows." msgstr "" -#: library/_thread.rst:224 +#: library/_thread.rst:225 msgid "" "When the main thread exits, it is system defined whether the other threads " "survive. On most systems, they are killed without executing :keyword:" "`try` ... :keyword:`finally` clauses or executing object destructors." msgstr "" -#: library/_thread.rst:229 -msgid "" -"When the main thread exits, it does not do any of its usual cleanup (except " -"that :keyword:`try` ... :keyword:`finally` clauses are honored), and the " -"standard I/O files are not flushed." -msgstr "" - #: library/_thread.rst:7 msgid "light-weight processes" msgstr "" diff --git a/library/abc.po b/library/abc.po index 69bf4db3b..7ac2299ec 100644 --- a/library/abc.po +++ b/library/abc.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -54,6 +54,14 @@ msgid "" "avoiding sometimes confusing metaclass usage, for example::" msgstr "" +#: library/abc.rst:36 +msgid "" +"from abc import ABC\n" +"\n" +"class MyABC(ABC):\n" +" pass" +msgstr "" + #: library/abc.rst:41 msgid "" "Note that the type of :class:`!ABC` is still :class:`ABCMeta`, therefore " @@ -63,6 +71,14 @@ msgid "" "and using :class:`!ABCMeta` directly, for example::" msgstr "" +#: library/abc.rst:47 +msgid "" +"from abc import ABCMeta\n" +"\n" +"class MyABC(metaclass=ABCMeta):\n" +" pass" +msgstr "" + #: library/abc.rst:57 msgid "Metaclass for defining Abstract Base Classes (ABCs)." msgstr "" @@ -90,6 +106,19 @@ msgid "" "Register *subclass* as a \"virtual subclass\" of this ABC. For example::" msgstr "" +#: library/abc.rst:75 +msgid "" +"from abc import ABC\n" +"\n" +"class MyABC(ABC):\n" +" pass\n" +"\n" +"MyABC.register(tuple)\n" +"\n" +"assert issubclass(tuple, MyABC)\n" +"assert isinstance((), MyABC)" +msgstr "" + #: library/abc.rst:85 msgid "Returns the registered subclass, to allow usage as a class decorator." msgstr "" @@ -113,7 +142,7 @@ msgid "" "Check whether *subclass* is considered a subclass of this ABC. This means " "that you can customize the behavior of :func:`issubclass` further without " "the need to call :meth:`register` on every class you want to consider a " -"subclass of the ABC. (This class method is called from the :meth:`~class." +"subclass of the ABC. (This class method is called from the :meth:`~type." "__subclasscheck__` method of the ABC.)" msgstr "" @@ -131,6 +160,36 @@ msgid "" "For a demonstration of these concepts, look at this example ABC definition::" msgstr "" +#: library/abc.rst:116 +msgid "" +"class Foo:\n" +" def __getitem__(self, index):\n" +" ...\n" +" def __len__(self):\n" +" ...\n" +" def get_iterator(self):\n" +" return iter(self)\n" +"\n" +"class MyIterable(ABC):\n" +"\n" +" @abstractmethod\n" +" def __iter__(self):\n" +" while False:\n" +" yield None\n" +"\n" +" def get_iterator(self):\n" +" return self.__iter__()\n" +"\n" +" @classmethod\n" +" def __subclasshook__(cls, C):\n" +" if cls is MyIterable:\n" +" if any(\"__iter__\" in B.__dict__ for B in C.__mro__):\n" +" return True\n" +" return NotImplemented\n" +"\n" +"MyIterable.register(Foo)" +msgstr "" + #: library/abc.rst:143 msgid "" "The ABC ``MyIterable`` defines the standard iterable method, :meth:" @@ -145,7 +204,7 @@ msgid "" "The :meth:`__subclasshook__` class method defined here says that any class " "that has an :meth:`~iterator.__iter__` method in its :attr:`~object." "__dict__` (or in that of one of its base classes, accessed via the :attr:" -"`~class.__mro__` list) is considered a ``MyIterable`` too." +"`~type.__mro__` list) is considered a ``MyIterable`` too." msgstr "" #: library/abc.rst:154 @@ -193,6 +252,39 @@ msgid "" "the following usage examples::" msgstr "" +#: library/abc.rst:187 +msgid "" +"class C(ABC):\n" +" @abstractmethod\n" +" def my_abstract_method(self, arg1):\n" +" ...\n" +" @classmethod\n" +" @abstractmethod\n" +" def my_abstract_classmethod(cls, arg2):\n" +" ...\n" +" @staticmethod\n" +" @abstractmethod\n" +" def my_abstract_staticmethod(arg3):\n" +" ...\n" +"\n" +" @property\n" +" @abstractmethod\n" +" def my_abstract_property(self):\n" +" ...\n" +" @my_abstract_property.setter\n" +" @abstractmethod\n" +" def my_abstract_property(self, val):\n" +" ...\n" +"\n" +" @abstractmethod\n" +" def _get_x(self):\n" +" ...\n" +" @abstractmethod\n" +" def _set_x(self, val):\n" +" ...\n" +" x = property(_get_x, _set_x)" +msgstr "" + #: library/abc.rst:217 msgid "" "In order to correctly interoperate with the abstract base class machinery, " @@ -202,6 +294,16 @@ msgid "" "Python's built-in :class:`property` does the equivalent of::" msgstr "" +#: library/abc.rst:223 +msgid "" +"class Descriptor:\n" +" ...\n" +" @property\n" +" def __isabstractmethod__(self):\n" +" return any(getattr(f, '__isabstractmethod__', False) for\n" +" f in (self._fget, self._fset, self._fdel))" +msgstr "" + #: library/abc.rst:232 msgid "" "Unlike Java abstract methods, these abstract methods may have an " @@ -233,6 +335,15 @@ msgid "" "correctly identified as abstract when applied to an abstract method::" msgstr "" +#: library/abc.rst:255 +msgid "" +"class C(ABC):\n" +" @classmethod\n" +" @abstractmethod\n" +" def my_abstract_classmethod(cls, arg):\n" +" ..." +msgstr "" + #: library/abc.rst:265 msgid "" "It is now possible to use :class:`staticmethod` with :func:`abstractmethod`, " @@ -251,6 +362,15 @@ msgid "" "now correctly identified as abstract when applied to an abstract method::" msgstr "" +#: library/abc.rst:276 +msgid "" +"class C(ABC):\n" +" @staticmethod\n" +" @abstractmethod\n" +" def my_abstract_staticmethod(arg):\n" +" ..." +msgstr "" + #: library/abc.rst:285 msgid "" "It is now possible to use :class:`property`, :meth:`property.getter`, :meth:" @@ -269,6 +389,15 @@ msgid "" "correctly identified as abstract when applied to an abstract method::" msgstr "" +#: library/abc.rst:297 +msgid "" +"class C(ABC):\n" +" @property\n" +" @abstractmethod\n" +" def my_abstract_property(self):\n" +" ..." +msgstr "" + #: library/abc.rst:303 msgid "" "The above example defines a read-only property; you can also define a read-" @@ -276,12 +405,33 @@ msgid "" "underlying methods as abstract::" msgstr "" +#: library/abc.rst:307 +msgid "" +"class C(ABC):\n" +" @property\n" +" def x(self):\n" +" ...\n" +"\n" +" @x.setter\n" +" @abstractmethod\n" +" def x(self, val):\n" +" ..." +msgstr "" + #: library/abc.rst:317 msgid "" "If only some components are abstract, only those components need to be " "updated to create a concrete property in a subclass::" msgstr "" +#: library/abc.rst:320 +msgid "" +"class D(C):\n" +" @C.x.setter\n" +" def x(self, val):\n" +" ..." +msgstr "" + #: library/abc.rst:326 msgid "The :mod:`!abc` module also provides the following functions:" msgstr "" diff --git a/library/argparse.po b/library/argparse.po index 6452d125f..970fe6452 100644 --- a/library/argparse.po +++ b/library/argparse.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -18,8 +18,8 @@ msgstr "" #: library/argparse.rst:2 msgid "" -":mod:`!argparse` --- Parser for command-line options, arguments and sub-" -"commands" +":mod:`!argparse` --- Parser for command-line options, arguments and " +"subcommands" msgstr "" #: library/argparse.rst:12 @@ -39,449 +39,321 @@ msgstr "" #: library/argparse.rst:22 msgid "" -"The :mod:`argparse` module makes it easy to write user-friendly command-line " -"interfaces. The program defines what arguments it requires, and :mod:" -"`argparse` will figure out how to parse those out of :data:`sys.argv`. The :" -"mod:`argparse` module also automatically generates help and usage messages. " -"The module will also issue errors when users give the program invalid " -"arguments." +"The :mod:`!argparse` module makes it easy to write user-friendly command-" +"line interfaces. The program defines what arguments it requires, and :mod:`!" +"argparse` will figure out how to parse those out of :data:`sys.argv`. The :" +"mod:`!argparse` module also automatically generates help and usage " +"messages. The module will also issue errors when users give the program " +"invalid arguments." msgstr "" -#: library/argparse.rst:30 -msgid "Core Functionality" -msgstr "" - -#: library/argparse.rst:32 +#: library/argparse.rst:28 msgid "" -"The :mod:`argparse` module's support for command-line interfaces is built " +"The :mod:`!argparse` module's support for command-line interfaces is built " "around an instance of :class:`argparse.ArgumentParser`. It is a container " "for argument specifications and has options that apply to the parser as " "whole::" msgstr "" -#: library/argparse.rst:41 -msgid "" -"The :meth:`ArgumentParser.add_argument` method attaches individual argument " -"specifications to the parser. It supports positional arguments, options " -"that accept values, and on/off flags::" -msgstr "" - -#: library/argparse.rst:50 -msgid "" -"The :meth:`ArgumentParser.parse_args` method runs the parser and places the " -"extracted data in a :class:`argparse.Namespace` object::" -msgstr "" - -#: library/argparse.rst:58 -msgid "Quick Links for add_argument()" -msgstr "" - -#: library/argparse.rst:61 -msgid "Name" -msgstr "" - -#: library/argparse.rst:61 -msgid "Description" -msgstr "" - -#: library/argparse.rst:61 -msgid "Values" -msgstr "" - -#: library/argparse.rst:63 -msgid "action_" -msgstr "" - -#: library/argparse.rst:63 -msgid "Specify how an argument should be handled" -msgstr "" - -#: library/argparse.rst:63 -msgid "" -"``'store'``, ``'store_const'``, ``'store_true'``, ``'append'``, " -"``'append_const'``, ``'count'``, ``'help'``, ``'version'``" -msgstr "" - -#: library/argparse.rst:64 -msgid "choices_" -msgstr "" - -#: library/argparse.rst:64 -msgid "Limit values to a specific set of choices" -msgstr "" - -#: library/argparse.rst:64 -msgid "" -"``['foo', 'bar']``, ``range(1, 10)``, or :class:`~collections.abc.Container` " -"instance" -msgstr "" - -#: library/argparse.rst:65 -msgid "const_" -msgstr "" - -#: library/argparse.rst:65 -msgid "Store a constant value" -msgstr "" - -#: library/argparse.rst:66 -msgid "default_" -msgstr "" - -#: library/argparse.rst:66 -msgid "Default value used when an argument is not provided" -msgstr "" - -#: library/argparse.rst:66 -msgid "Defaults to ``None``" -msgstr "" - -#: library/argparse.rst:67 -msgid "dest_" -msgstr "" - -#: library/argparse.rst:67 -msgid "Specify the attribute name used in the result namespace" -msgstr "" - -#: library/argparse.rst:68 -msgid "help_" -msgstr "" - -#: library/argparse.rst:68 -msgid "Help message for an argument" -msgstr "" - -#: library/argparse.rst:69 -msgid "metavar_" -msgstr "" - -#: library/argparse.rst:69 -msgid "Alternate display name for the argument as shown in help" -msgstr "" - -#: library/argparse.rst:70 -msgid "nargs_" -msgstr "" - -#: library/argparse.rst:70 -msgid "Number of times the argument can be used" -msgstr "" - -#: library/argparse.rst:70 -msgid ":class:`int`, ``'?'``, ``'*'``, or ``'+'``" -msgstr "" - -#: library/argparse.rst:71 -msgid "required_" -msgstr "" - -#: library/argparse.rst:71 -msgid "Indicate whether an argument is required or optional" -msgstr "" - -#: library/argparse.rst:71 -msgid "``True`` or ``False``" -msgstr "" - -#: library/argparse.rst:72 -msgid ":ref:`type `" -msgstr "" - -#: library/argparse.rst:72 -msgid "Automatically convert an argument to the given type" -msgstr "" - -#: library/argparse.rst:72 -msgid "" -":class:`int`, :class:`float`, ``argparse.FileType('w')``, or callable " -"function" -msgstr "" - -#: library/argparse.rst:77 -msgid "Example" -msgstr "" - -#: library/argparse.rst:79 -msgid "" -"The following code is a Python program that takes a list of integers and " -"produces either the sum or the max::" -msgstr "" - -#: library/argparse.rst:94 -msgid "" -"Assuming the above Python code is saved into a file called ``prog.py``, it " -"can be run at the command line and it provides useful help messages:" -msgstr "" - -#: library/argparse.rst:111 -msgid "" -"When run with the appropriate arguments, it prints either the sum or the max " -"of the command-line integers:" -msgstr "" - -#: library/argparse.rst:122 -msgid "If invalid arguments are passed in, an error will be displayed:" -msgstr "" - -#: library/argparse.rst:130 -msgid "The following sections walk you through this example." -msgstr "" - -#: library/argparse.rst:134 -msgid "Creating a parser" -msgstr "" - -#: library/argparse.rst:136 +#: library/argparse.rst:32 msgid "" -"The first step in using the :mod:`argparse` is creating an :class:" -"`ArgumentParser` object::" +"parser = argparse.ArgumentParser(\n" +" prog='ProgramName',\n" +" description='What the program does',\n" +" epilog='Text at the bottom of help')" msgstr "" -#: library/argparse.rst:141 +#: library/argparse.rst:37 msgid "" -"The :class:`ArgumentParser` object will hold all the information necessary " -"to parse the command line into Python data types." -msgstr "" - -#: library/argparse.rst:146 -msgid "Adding arguments" +"The :meth:`ArgumentParser.add_argument` method attaches individual argument " +"specifications to the parser. It supports positional arguments, options " +"that accept values, and on/off flags::" msgstr "" -#: library/argparse.rst:148 +#: library/argparse.rst:41 msgid "" -"Filling an :class:`ArgumentParser` with information about program arguments " -"is done by making calls to the :meth:`~ArgumentParser.add_argument` method. " -"Generally, these calls tell the :class:`ArgumentParser` how to take the " -"strings on the command line and turn them into objects. This information is " -"stored and used when :meth:`~ArgumentParser.parse_args` is called. For " -"example::" +"parser.add_argument('filename') # positional argument\n" +"parser.add_argument('-c', '--count') # option that takes a value\n" +"parser.add_argument('-v', '--verbose',\n" +" action='store_true') # on/off flag" msgstr "" -#: library/argparse.rst:160 +#: library/argparse.rst:46 msgid "" -"Later, calling :meth:`~ArgumentParser.parse_args` will return an object with " -"two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute " -"will be a list of one or more integers, and the ``accumulate`` attribute " -"will be either the :func:`sum` function, if ``--sum`` was specified at the " -"command line, or the :func:`max` function if it was not." -msgstr "" - -#: library/argparse.rst:168 -msgid "Parsing arguments" +"The :meth:`ArgumentParser.parse_args` method runs the parser and places the " +"extracted data in a :class:`argparse.Namespace` object::" msgstr "" -#: library/argparse.rst:170 +#: library/argparse.rst:49 msgid "" -":class:`ArgumentParser` parses arguments through the :meth:`~ArgumentParser." -"parse_args` method. This will inspect the command line, convert each " -"argument to the appropriate type and then invoke the appropriate action. In " -"most cases, this means a simple :class:`Namespace` object will be built up " -"from attributes parsed out of the command line::" +"args = parser.parse_args()\n" +"print(args.filename, args.count, args.verbose)" msgstr "" -#: library/argparse.rst:179 +#: library/argparse.rst:53 msgid "" -"In a script, :meth:`~ArgumentParser.parse_args` will typically be called " -"with no arguments, and the :class:`ArgumentParser` will automatically " -"determine the command-line arguments from :data:`sys.argv`." +"If you're looking for a guide about how to upgrade :mod:`optparse` code to :" +"mod:`!argparse`, see :ref:`Upgrading Optparse Code `." msgstr "" -#: library/argparse.rst:185 +#: library/argparse.rst:57 msgid "ArgumentParser objects" msgstr "" -#: library/argparse.rst:194 +#: library/argparse.rst:66 msgid "" "Create a new :class:`ArgumentParser` object. All parameters should be passed " "as keyword arguments. Each parameter has its own more detailed description " "below, but in short they are:" msgstr "" -#: library/argparse.rst:198 +#: library/argparse.rst:70 msgid "" "prog_ - The name of the program (default: ``os.path.basename(sys.argv[0])``)" msgstr "" -#: library/argparse.rst:201 +#: library/argparse.rst:73 msgid "" "usage_ - The string describing the program usage (default: generated from " "arguments added to parser)" msgstr "" -#: library/argparse.rst:204 +#: library/argparse.rst:76 msgid "" "description_ - Text to display before the argument help (by default, no text)" msgstr "" -#: library/argparse.rst:207 +#: library/argparse.rst:79 msgid "epilog_ - Text to display after the argument help (by default, no text)" msgstr "" -#: library/argparse.rst:209 +#: library/argparse.rst:81 msgid "" "parents_ - A list of :class:`ArgumentParser` objects whose arguments should " "also be included" msgstr "" -#: library/argparse.rst:212 +#: library/argparse.rst:84 msgid "formatter_class_ - A class for customizing the help output" msgstr "" -#: library/argparse.rst:214 +#: library/argparse.rst:86 msgid "" "prefix_chars_ - The set of characters that prefix optional arguments " "(default: '-')" msgstr "" -#: library/argparse.rst:217 +#: library/argparse.rst:89 msgid "" "fromfile_prefix_chars_ - The set of characters that prefix files from which " "additional arguments should be read (default: ``None``)" msgstr "" -#: library/argparse.rst:220 +#: library/argparse.rst:92 msgid "" "argument_default_ - The global default value for arguments (default: " "``None``)" msgstr "" -#: library/argparse.rst:223 +#: library/argparse.rst:95 msgid "" "conflict_handler_ - The strategy for resolving conflicting optionals " "(usually unnecessary)" msgstr "" -#: library/argparse.rst:226 +#: library/argparse.rst:98 msgid "" "add_help_ - Add a ``-h/--help`` option to the parser (default: ``True``)" msgstr "" -#: library/argparse.rst:228 +#: library/argparse.rst:100 msgid "" "allow_abbrev_ - Allows long options to be abbreviated if the abbreviation is " "unambiguous. (default: ``True``)" msgstr "" -#: library/argparse.rst:231 +#: library/argparse.rst:103 msgid "" -"exit_on_error_ - Determines whether or not ArgumentParser exits with error " -"info when an error occurs. (default: ``True``)" +"exit_on_error_ - Determines whether or not :class:`!ArgumentParser` exits " +"with error info when an error occurs. (default: ``True``)" msgstr "" -#: library/argparse.rst:234 +#: library/argparse.rst:106 msgid "*allow_abbrev* parameter was added." msgstr "" -#: library/argparse.rst:237 +#: library/argparse.rst:109 msgid "" "In previous versions, *allow_abbrev* also disabled grouping of short flags " "such as ``-vv`` to mean ``-v -v``." msgstr "" -#: library/argparse.rst:241 +#: library/argparse.rst:113 msgid "*exit_on_error* parameter was added." msgstr "" -#: library/argparse.rst:780 +#: library/argparse.rst:596 msgid "The following sections describe how each of these are used." msgstr "" -#: library/argparse.rst:250 +#: library/argparse.rst:122 msgid "prog" msgstr "" -#: library/argparse.rst:252 +#: library/argparse.rst:125 msgid "" -"By default, :class:`ArgumentParser` objects use ``sys.argv[0]`` to determine " -"how to display the name of the program in help messages. This default is " -"almost always desirable because it will make the help messages match how the " -"program was invoked on the command line. For example, consider a file named " -"``myprogram.py`` with the following code::" +"By default, :class:`ArgumentParser` calculates the name of the program to " +"display in help messages depending on the way the Python interpreter was run:" msgstr "" -#: library/argparse.rst:263 +#: library/argparse.rst:128 +msgid "" +"The :func:`base name ` of ``sys.argv[0]`` if a file was " +"passed as argument." +msgstr "" + +#: library/argparse.rst:130 +msgid "" +"The Python interpreter name followed by ``sys.argv[0]`` if a directory or a " +"zipfile was passed as argument." +msgstr "" + +#: library/argparse.rst:132 msgid "" -"The help for this program will display ``myprogram.py`` as the program name " -"(regardless of where the program was invoked from):" +"The Python interpreter name followed by ``-m`` followed by the module or " +"package name if the :option:`-m` option was used." msgstr "" -#: library/argparse.rst:282 +#: library/argparse.rst:135 msgid "" -"To change this default behavior, another value can be supplied using the " -"``prog=`` argument to :class:`ArgumentParser`::" +"This default is almost always desirable because it will make the help " +"messages match the string that was used to invoke the program on the command " +"line. However, to change this default behavior, another value can be " +"supplied using the ``prog=`` argument to :class:`ArgumentParser`::" msgstr "" -#: library/argparse.rst:292 +#: library/argparse.rst:140 +msgid "" +">>> parser = argparse.ArgumentParser(prog='myprogram')\n" +">>> parser.print_help()\n" +"usage: myprogram [-h]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit" +msgstr "" + +#: library/argparse.rst:147 msgid "" "Note that the program name, whether determined from ``sys.argv[0]`` or from " "the ``prog=`` argument, is available to help messages using the ``%(prog)s`` " "format specifier." msgstr "" -#: library/argparse.rst:309 +#: library/argparse.rst:153 +msgid "" +">>> parser = argparse.ArgumentParser(prog='myprogram')\n" +">>> parser.add_argument('--foo', help='foo of the %(prog)s program')\n" +">>> parser.print_help()\n" +"usage: myprogram [-h] [--foo FOO]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo FOO foo of the myprogram program" +msgstr "" + +#: library/argparse.rst:164 msgid "usage" msgstr "" -#: library/argparse.rst:311 +#: library/argparse.rst:166 msgid "" "By default, :class:`ArgumentParser` calculates the usage message from the " -"arguments it contains::" +"arguments it contains. The default message can be overridden with the " +"``usage=`` keyword argument::" msgstr "" -#: library/argparse.rst:327 +#: library/argparse.rst:170 msgid "" -"The default message can be overridden with the ``usage=`` keyword argument::" +">>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s " +"[options]')\n" +">>> parser.add_argument('--foo', nargs='?', help='foo help')\n" +">>> parser.add_argument('bar', nargs='+', help='bar help')\n" +">>> parser.print_help()\n" +"usage: PROG [options]\n" +"\n" +"positional arguments:\n" +" bar bar help\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo [FOO] foo help" msgstr "" -#: library/argparse.rst:342 +#: library/argparse.rst:183 msgid "" "The ``%(prog)s`` format specifier is available to fill in the program name " "in your usage messages." msgstr "" -#: library/argparse.rst:349 +#: library/argparse.rst:190 msgid "description" msgstr "" -#: library/argparse.rst:351 +#: library/argparse.rst:192 msgid "" "Most calls to the :class:`ArgumentParser` constructor will use the " "``description=`` keyword argument. This argument gives a brief description " "of what the program does and how it works. In help messages, the " "description is displayed between the command-line usage string and the help " -"messages for the various arguments::" +"messages for the various arguments." msgstr "" -#: library/argparse.rst:366 +#: library/argparse.rst:198 msgid "" "By default, the description will be line-wrapped so that it fits within the " "given space. To change this behavior, see the formatter_class_ argument." msgstr "" -#: library/argparse.rst:371 +#: library/argparse.rst:203 msgid "epilog" msgstr "" -#: library/argparse.rst:373 +#: library/argparse.rst:205 msgid "" "Some programs like to display additional description of the program after " "the description of the arguments. Such text can be specified using the " "``epilog=`` argument to :class:`ArgumentParser`::" msgstr "" -#: library/argparse.rst:390 +#: library/argparse.rst:209 +msgid "" +">>> parser = argparse.ArgumentParser(\n" +"... description='A foo that bars',\n" +"... epilog=\"And that's how you'd foo a bar\")\n" +">>> parser.print_help()\n" +"usage: argparse.py [-h]\n" +"\n" +"A foo that bars\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"\n" +"And that's how you'd foo a bar" +msgstr "" + +#: library/argparse.rst:222 msgid "" "As with the description_ argument, the ``epilog=`` text is by default line-" "wrapped, but this behavior can be adjusted with the formatter_class_ " "argument to :class:`ArgumentParser`." msgstr "" -#: library/argparse.rst:396 +#: library/argparse.rst:228 msgid "parents" msgstr "" -#: library/argparse.rst:398 +#: library/argparse.rst:230 msgid "" "Sometimes, several parsers share a common set of arguments. Rather than " "repeating the definitions of these arguments, a single parser with all the " @@ -492,32 +364,48 @@ msgid "" "object being constructed::" msgstr "" -#: library/argparse.rst:418 +#: library/argparse.rst:237 +msgid "" +">>> parent_parser = argparse.ArgumentParser(add_help=False)\n" +">>> parent_parser.add_argument('--parent', type=int)\n" +"\n" +">>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])\n" +">>> foo_parser.add_argument('foo')\n" +">>> foo_parser.parse_args(['--parent', '2', 'XXX'])\n" +"Namespace(foo='XXX', parent=2)\n" +"\n" +">>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])\n" +">>> bar_parser.add_argument('--bar')\n" +">>> bar_parser.parse_args(['--bar', 'YYY'])\n" +"Namespace(bar='YYY', parent=None)" +msgstr "" + +#: library/argparse.rst:250 msgid "" "Note that most parent parsers will specify ``add_help=False``. Otherwise, " "the :class:`ArgumentParser` will see two ``-h/--help`` options (one in the " "parent and one in the child) and raise an error." msgstr "" -#: library/argparse.rst:423 +#: library/argparse.rst:255 msgid "" "You must fully initialize the parsers before passing them via ``parents=``. " "If you change the parent parsers after the child parser, those changes will " "not be reflected in the child." msgstr "" -#: library/argparse.rst:431 +#: library/argparse.rst:263 msgid "formatter_class" msgstr "" -#: library/argparse.rst:433 +#: library/argparse.rst:265 msgid "" ":class:`ArgumentParser` objects allow the help formatting to be customized " "by specifying an alternate formatting class. Currently, there are four such " "classes:" msgstr "" -#: library/argparse.rst:442 +#: library/argparse.rst:274 msgid "" ":class:`RawDescriptionHelpFormatter` and :class:`RawTextHelpFormatter` give " "more control over how textual descriptions are displayed. By default, :class:" @@ -525,58 +413,152 @@ msgid "" "command-line help messages::" msgstr "" -#: library/argparse.rst:467 +#: library/argparse.rst:279 +msgid "" +">>> parser = argparse.ArgumentParser(\n" +"... prog='PROG',\n" +"... description='''this description\n" +"... was indented weird\n" +"... but that is okay''',\n" +"... epilog='''\n" +"... likewise for this epilog whose whitespace will\n" +"... be cleaned up and whose words will be wrapped\n" +"... across a couple lines''')\n" +">>> parser.print_help()\n" +"usage: PROG [-h]\n" +"\n" +"this description was indented weird but that is okay\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"\n" +"likewise for this epilog whose whitespace will be cleaned up and whose " +"words\n" +"will be wrapped across a couple lines" +msgstr "" + +#: library/argparse.rst:299 msgid "" "Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=`` " "indicates that description_ and epilog_ are already correctly formatted and " "should not be line-wrapped::" msgstr "" -#: library/argparse.rst:493 +#: library/argparse.rst:303 +msgid "" +">>> parser = argparse.ArgumentParser(\n" +"... prog='PROG',\n" +"... formatter_class=argparse.RawDescriptionHelpFormatter,\n" +"... description=textwrap.dedent('''\\\n" +"... Please do not mess up this text!\n" +"... --------------------------------\n" +"... I have indented it\n" +"... exactly the way\n" +"... I want it\n" +"... '''))\n" +">>> parser.print_help()\n" +"usage: PROG [-h]\n" +"\n" +"Please do not mess up this text!\n" +"--------------------------------\n" +" I have indented it\n" +" exactly the way\n" +" I want it\n" +"\n" +"options:\n" +" -h, --help show this help message and exit" +msgstr "" + +#: library/argparse.rst:325 msgid "" ":class:`RawTextHelpFormatter` maintains whitespace for all sorts of help " -"text, including argument descriptions. However, multiple new lines are " +"text, including argument descriptions. However, multiple newlines are " "replaced with one. If you wish to preserve multiple blank lines, add spaces " "between the newlines." msgstr "" -#: library/argparse.rst:498 +#: library/argparse.rst:330 msgid "" ":class:`ArgumentDefaultsHelpFormatter` automatically adds information about " "default values to each of the argument help messages::" msgstr "" -#: library/argparse.rst:516 +#: library/argparse.rst:333 +msgid "" +">>> parser = argparse.ArgumentParser(\n" +"... prog='PROG',\n" +"... formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n" +">>> parser.add_argument('--foo', type=int, default=42, help='FOO!')\n" +">>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')\n" +">>> parser.print_help()\n" +"usage: PROG [-h] [--foo FOO] [bar ...]\n" +"\n" +"positional arguments:\n" +" bar BAR! (default: [1, 2, 3])\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo FOO FOO! (default: 42)" +msgstr "" + +#: library/argparse.rst:348 msgid "" ":class:`MetavarTypeHelpFormatter` uses the name of the type_ argument for " "each argument as the display name for its values (rather than using the " "dest_ as the regular formatter does)::" msgstr "" -#: library/argparse.rst:537 +#: library/argparse.rst:352 +msgid "" +">>> parser = argparse.ArgumentParser(\n" +"... prog='PROG',\n" +"... formatter_class=argparse.MetavarTypeHelpFormatter)\n" +">>> parser.add_argument('--foo', type=int)\n" +">>> parser.add_argument('bar', type=float)\n" +">>> parser.print_help()\n" +"usage: PROG [-h] [--foo int] float\n" +"\n" +"positional arguments:\n" +" float\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo int" +msgstr "" + +#: library/argparse.rst:369 msgid "prefix_chars" msgstr "" -#: library/argparse.rst:539 +#: library/argparse.rst:371 msgid "" "Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``. " "Parsers that need to support different or additional prefix characters, e.g. " "for options like ``+f`` or ``/foo``, may specify them using the " -"``prefix_chars=`` argument to the ArgumentParser constructor::" +"``prefix_chars=`` argument to the :class:`ArgumentParser` constructor::" msgstr "" -#: library/argparse.rst:551 +#: library/argparse.rst:377 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')\n" +">>> parser.add_argument('+f')\n" +">>> parser.add_argument('++bar')\n" +">>> parser.parse_args('+f X ++bar Y'.split())\n" +"Namespace(bar='Y', f='X')" +msgstr "" + +#: library/argparse.rst:383 msgid "" "The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of " "characters that does not include ``-`` will cause ``-f/--foo`` options to be " "disallowed." msgstr "" -#: library/argparse.rst:557 +#: library/argparse.rst:389 msgid "fromfile_prefix_chars" msgstr "" -#: library/argparse.rst:559 +#: library/argparse.rst:391 msgid "" "Sometimes, when dealing with a particularly long argument list, it may make " "sense to keep the list of arguments in a file rather than typing it out at " @@ -586,7 +568,18 @@ msgid "" "by the arguments they contain. For example::" msgstr "" -#: library/argparse.rst:574 +#: library/argparse.rst:398 +msgid "" +">>> with open('args.txt', 'w', encoding=sys.getfilesystemencoding()) as fp:\n" +"... fp.write('-f\\nbar')\n" +"...\n" +">>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')\n" +">>> parser.add_argument('-f')\n" +">>> parser.parse_args(['-f', 'foo', '@args.txt'])\n" +"Namespace(f='bar')" +msgstr "" + +#: library/argparse.rst:406 msgid "" "Arguments read from a file must by default be one per line (but see also :" "meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they " @@ -596,32 +589,32 @@ msgid "" "f', 'bar']``." msgstr "" -#: library/argparse.rst:580 +#: library/argparse.rst:412 msgid "" ":class:`ArgumentParser` uses :term:`filesystem encoding and error handler` " "to read the file containing arguments." msgstr "" -#: library/argparse.rst:583 +#: library/argparse.rst:415 msgid "" "The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that " "arguments will never be treated as file references." msgstr "" -#: library/argparse.rst:586 +#: library/argparse.rst:418 msgid "" ":class:`ArgumentParser` changed encoding and errors to read arguments files " "from default (e.g. :func:`locale.getpreferredencoding(False) ` and ``\"strict\"``) to :term:`filesystem encoding and " -"error handler`. Arguments file should be encoded in UTF-8 instead of ANSI " -"Codepage on Windows." +"getpreferredencoding>` and ``\"strict\"``) to the :term:`filesystem encoding " +"and error handler`. Arguments file should be encoded in UTF-8 instead of " +"ANSI Codepage on Windows." msgstr "" -#: library/argparse.rst:594 +#: library/argparse.rst:426 msgid "argument_default" msgstr "" -#: library/argparse.rst:596 +#: library/argparse.rst:428 msgid "" "Generally, argument defaults are specified either by passing a default to :" "meth:`~ArgumentParser.add_argument` or by calling the :meth:`~ArgumentParser." @@ -633,26 +626,47 @@ msgid "" "supply ``argument_default=SUPPRESS``::" msgstr "" -#: library/argparse.rst:616 +#: library/argparse.rst:437 +msgid "" +">>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)\n" +">>> parser.add_argument('--foo')\n" +">>> parser.add_argument('bar', nargs='?')\n" +">>> parser.parse_args(['--foo', '1', 'BAR'])\n" +"Namespace(bar='BAR', foo='1')\n" +">>> parser.parse_args([])\n" +"Namespace()" +msgstr "" + +#: library/argparse.rst:448 msgid "allow_abbrev" msgstr "" -#: library/argparse.rst:618 +#: library/argparse.rst:450 msgid "" "Normally, when you pass an argument list to the :meth:`~ArgumentParser." "parse_args` method of an :class:`ArgumentParser`, it :ref:`recognizes " "abbreviations ` of long options." msgstr "" -#: library/argparse.rst:622 +#: library/argparse.rst:454 msgid "This feature can be disabled by setting ``allow_abbrev`` to ``False``::" msgstr "" -#: library/argparse.rst:635 +#: library/argparse.rst:456 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)\n" +">>> parser.add_argument('--foobar', action='store_true')\n" +">>> parser.add_argument('--foonley', action='store_false')\n" +">>> parser.parse_args(['--foon'])\n" +"usage: PROG [-h] [--foobar] [--foonley]\n" +"PROG: error: unrecognized arguments: --foon" +msgstr "" + +#: library/argparse.rst:467 msgid "conflict_handler" msgstr "" -#: library/argparse.rst:637 +#: library/argparse.rst:469 msgid "" ":class:`ArgumentParser` objects do not allow two actions with the same " "option string. By default, :class:`ArgumentParser` objects raise an " @@ -660,7 +674,17 @@ msgid "" "that is already in use::" msgstr "" -#: library/argparse.rst:649 +#: library/argparse.rst:474 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-f', '--foo', help='old foo help')\n" +">>> parser.add_argument('--foo', help='new foo help')\n" +"Traceback (most recent call last):\n" +" ..\n" +"ArgumentError: argument --foo: conflicting option string(s): --foo" +msgstr "" + +#: library/argparse.rst:481 msgid "" "Sometimes (e.g. when using parents_) it may be useful to simply override any " "older arguments with the same option string. To get this behavior, the " @@ -668,7 +692,22 @@ msgid "" "of :class:`ArgumentParser`::" msgstr "" -#: library/argparse.rst:665 +#: library/argparse.rst:486 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG', " +"conflict_handler='resolve')\n" +">>> parser.add_argument('-f', '--foo', help='old foo help')\n" +">>> parser.add_argument('--foo', help='new foo help')\n" +">>> parser.print_help()\n" +"usage: PROG [-h] [-f FOO] [--foo FOO]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -f FOO old foo help\n" +" --foo FOO new foo help" +msgstr "" + +#: library/argparse.rst:497 msgid "" "Note that :class:`ArgumentParser` objects only remove an action if all of " "its option strings are overridden. So, in the example above, the old ``-f/--" @@ -676,31 +715,36 @@ msgid "" "option string was overridden." msgstr "" -#: library/argparse.rst:672 +#: library/argparse.rst:504 msgid "add_help" msgstr "" -#: library/argparse.rst:674 +#: library/argparse.rst:506 msgid "" -"By default, ArgumentParser objects add an option which simply displays the " -"parser's help message. For example, consider a file named ``myprogram.py`` " -"containing the following code::" +"By default, :class:`ArgumentParser` objects add an option which simply " +"displays the parser's help message. If ``-h`` or ``--help`` is supplied at " +"the command line, the :class:`!ArgumentParser` help will be printed." msgstr "" -#: library/argparse.rst:683 -msgid "" -"If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser " -"help will be printed:" -msgstr "" - -#: library/argparse.rst:695 +#: library/argparse.rst:510 msgid "" "Occasionally, it may be useful to disable the addition of this help option. " "This can be achieved by passing ``False`` as the ``add_help=`` argument to :" "class:`ArgumentParser`::" msgstr "" -#: library/argparse.rst:707 +#: library/argparse.rst:514 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)\n" +">>> parser.add_argument('--foo', help='foo help')\n" +">>> parser.print_help()\n" +"usage: PROG [--foo FOO]\n" +"\n" +"options:\n" +" --foo FOO foo help" +msgstr "" + +#: library/argparse.rst:522 msgid "" "The help option is typically ``-h/--help``. The exception to this is if the " "``prefix_chars=`` is specified and does not include ``-``, in which case ``-" @@ -708,94 +752,119 @@ msgid "" "in ``prefix_chars`` is used to prefix the help options::" msgstr "" -#: library/argparse.rst:722 +#: library/argparse.rst:528 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')\n" +">>> parser.print_help()\n" +"usage: PROG [+h]\n" +"\n" +"options:\n" +" +h, ++help show this help message and exit" +msgstr "" + +#: library/argparse.rst:537 msgid "exit_on_error" msgstr "" -#: library/argparse.rst:724 +#: library/argparse.rst:539 msgid "" "Normally, when you pass an invalid argument list to the :meth:" "`~ArgumentParser.parse_args` method of an :class:`ArgumentParser`, it will " -"exit with error info." +"print a *message* to :data:`sys.stderr` and exit with a status code of 2." msgstr "" -#: library/argparse.rst:727 +#: library/argparse.rst:543 msgid "" "If the user would like to catch errors manually, the feature can be enabled " "by setting ``exit_on_error`` to ``False``::" msgstr "" -#: library/argparse.rst:744 +#: library/argparse.rst:546 +msgid "" +">>> parser = argparse.ArgumentParser(exit_on_error=False)\n" +">>> parser.add_argument('--integers', type=int)\n" +"_StoreAction(option_strings=['--integers'], dest='integers', nargs=None, " +"const=None, default=None, type=, choices=None, help=None, " +"metavar=None)\n" +">>> try:\n" +"... parser.parse_args('--integers a'.split())\n" +"... except argparse.ArgumentError:\n" +"... print('Catching an argumentError')\n" +"...\n" +"Catching an argumentError" +msgstr "" + +#: library/argparse.rst:560 msgid "The add_argument() method" msgstr "" -#: library/argparse.rst:750 +#: library/argparse.rst:566 msgid "" "Define how a single command-line argument should be parsed. Each parameter " "has its own more detailed description below, but in short they are:" msgstr "" -#: library/argparse.rst:753 +#: library/argparse.rst:569 msgid "" -"`name or flags`_ - Either a name or a list of option strings, e.g. ``foo`` " -"or ``-f, --foo``." +"`name or flags`_ - Either a name or a list of option strings, e.g. ``'foo'`` " +"or ``'-f', '--foo'``." msgstr "" -#: library/argparse.rst:756 +#: library/argparse.rst:572 msgid "" "action_ - The basic type of action to be taken when this argument is " "encountered at the command line." msgstr "" -#: library/argparse.rst:759 +#: library/argparse.rst:575 msgid "nargs_ - The number of command-line arguments that should be consumed." msgstr "" -#: library/argparse.rst:761 +#: library/argparse.rst:577 msgid "" "const_ - A constant value required by some action_ and nargs_ selections." msgstr "" -#: library/argparse.rst:763 +#: library/argparse.rst:579 msgid "" "default_ - The value produced if the argument is absent from the command " "line and if it is absent from the namespace object." msgstr "" -#: library/argparse.rst:766 +#: library/argparse.rst:582 msgid "" "type_ - The type to which the command-line argument should be converted." msgstr "" -#: library/argparse.rst:768 +#: library/argparse.rst:584 msgid "choices_ - A sequence of the allowable values for the argument." msgstr "" -#: library/argparse.rst:770 +#: library/argparse.rst:586 msgid "" "required_ - Whether or not the command-line option may be omitted (optionals " "only)." msgstr "" -#: library/argparse.rst:773 +#: library/argparse.rst:589 msgid "help_ - A brief description of what the argument does." msgstr "" -#: library/argparse.rst:775 +#: library/argparse.rst:591 msgid "metavar_ - A name for the argument in usage messages." msgstr "" -#: library/argparse.rst:777 +#: library/argparse.rst:593 msgid "" "dest_ - The name of the attribute to be added to the object returned by :" "meth:`parse_args`." msgstr "" -#: library/argparse.rst:786 +#: library/argparse.rst:602 msgid "name or flags" msgstr "" -#: library/argparse.rst:788 +#: library/argparse.rst:604 msgid "" "The :meth:`~ArgumentParser.add_argument` method must know whether an " "optional argument, like ``-f`` or ``--foo``, or a positional argument, like " @@ -804,26 +873,48 @@ msgid "" "or a simple argument name." msgstr "" -#: library/argparse.rst:794 +#: library/argparse.rst:610 msgid "For example, an optional argument could be created like::" msgstr "" -#: library/argparse.rst:798 +#: library/argparse.rst:612 +msgid ">>> parser.add_argument('-f', '--foo')" +msgstr "" + +#: library/argparse.rst:614 msgid "while a positional argument could be created like::" msgstr "" -#: library/argparse.rst:802 +#: library/argparse.rst:616 +msgid ">>> parser.add_argument('bar')" +msgstr "" + +#: library/argparse.rst:618 msgid "" "When :meth:`~ArgumentParser.parse_args` is called, optional arguments will " "be identified by the ``-`` prefix, and the remaining arguments will be " "assumed to be positional::" msgstr "" -#: library/argparse.rst:821 +#: library/argparse.rst:622 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-f', '--foo')\n" +">>> parser.add_argument('bar')\n" +">>> parser.parse_args(['BAR'])\n" +"Namespace(bar='BAR', foo=None)\n" +">>> parser.parse_args(['BAR', '--foo', 'FOO'])\n" +"Namespace(bar='BAR', foo='FOO')\n" +">>> parser.parse_args(['--foo', 'FOO'])\n" +"usage: PROG [-h] [-f FOO] bar\n" +"PROG: error: the following arguments are required: bar" +msgstr "" + +#: library/argparse.rst:637 msgid "action" msgstr "" -#: library/argparse.rst:823 +#: library/argparse.rst:639 msgid "" ":class:`ArgumentParser` objects associate command-line arguments with " "actions. These actions can do just about anything with the command-line " @@ -833,13 +924,13 @@ msgid "" "be handled. The supplied actions are:" msgstr "" -#: library/argparse.rst:829 +#: library/argparse.rst:645 msgid "" "``'store'`` - This just stores the argument's value. This is the default " -"action. For example::" +"action." msgstr "" -#: library/argparse.rst:837 +#: library/argparse.rst:648 msgid "" "``'store_const'`` - This stores the value specified by the const_ keyword " "argument; note that the const_ keyword argument defaults to ``None``. The " @@ -847,15 +938,33 @@ msgid "" "specify some sort of flag. For example::" msgstr "" -#: library/argparse.rst:847 +#: library/argparse.rst:653 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action='store_const', const=42)\n" +">>> parser.parse_args(['--foo'])\n" +"Namespace(foo=42)" +msgstr "" + +#: library/argparse.rst:658 msgid "" "``'store_true'`` and ``'store_false'`` - These are special cases of " "``'store_const'`` used for storing the values ``True`` and ``False`` " "respectively. In addition, they create default values of ``False`` and " -"``True`` respectively. For example::" +"``True`` respectively::" +msgstr "" + +#: library/argparse.rst:663 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action='store_true')\n" +">>> parser.add_argument('--bar', action='store_false')\n" +">>> parser.add_argument('--baz', action='store_false')\n" +">>> parser.parse_args('--foo --bar'.split())\n" +"Namespace(foo=True, bar=False, baz=True)" msgstr "" -#: library/argparse.rst:859 +#: library/argparse.rst:670 msgid "" "``'append'`` - This stores a list, and appends each argument value to the " "list. It is useful to allow an option to be specified multiple times. If the " @@ -864,7 +973,15 @@ msgid "" "after those default values. Example usage::" msgstr "" -#: library/argparse.rst:870 +#: library/argparse.rst:676 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action='append')\n" +">>> parser.parse_args('--foo 1 --foo 2'.split())\n" +"Namespace(foo=['1', '2'])" +msgstr "" + +#: library/argparse.rst:681 msgid "" "``'append_const'`` - This stores a list, and appends the value specified by " "the const_ keyword argument to the list; note that the const_ keyword " @@ -873,17 +990,55 @@ msgid "" "example::" msgstr "" -#: library/argparse.rst:882 +#: library/argparse.rst:687 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--str', dest='types', action='append_const', " +"const=str)\n" +">>> parser.add_argument('--int', dest='types', action='append_const', " +"const=int)\n" +">>> parser.parse_args('--str --int'.split())\n" +"Namespace(types=[, ])" +msgstr "" + +#: library/argparse.rst:693 +msgid "" +"``'extend'`` - This stores a list and appends each item from the multi-value " +"argument list to it. The ``'extend'`` action is typically used with the " +"nargs_ keyword argument value ``'+'`` or ``'*'``. Note that when nargs_ is " +"``None`` (the default) or ``'?'``, each character of the argument string " +"will be appended to the list. Example usage::" +msgstr "" + +#: library/argparse.rst:701 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument(\"--foo\", action=\"extend\", nargs=\"+\", " +"type=str)\n" +">>> parser.parse_args([\"--foo\", \"f1\", \"--foo\", \"f2\", \"f3\", " +"\"f4\"])\n" +"Namespace(foo=['f1', 'f2', 'f3', 'f4'])" +msgstr "" + +#: library/argparse.rst:708 msgid "" "``'count'`` - This counts the number of times a keyword argument occurs. For " "example, this is useful for increasing verbosity levels::" msgstr "" -#: library/argparse.rst:890 +#: library/argparse.rst:711 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--verbose', '-v', action='count', default=0)\n" +">>> parser.parse_args(['-vvv'])\n" +"Namespace(verbose=3)" +msgstr "" + +#: library/argparse.rst:716 msgid "Note, the *default* will be ``None`` unless explicitly set to *0*." msgstr "" -#: library/argparse.rst:892 +#: library/argparse.rst:718 msgid "" "``'help'`` - This prints a complete help message for all the options in the " "current parser and then exits. By default a help action is automatically " @@ -891,67 +1046,117 @@ msgid "" "output is created." msgstr "" -#: library/argparse.rst:897 +#: library/argparse.rst:723 msgid "" "``'version'`` - This expects a ``version=`` keyword argument in the :meth:" "`~ArgumentParser.add_argument` call, and prints version information and " "exits when invoked::" msgstr "" -#: library/argparse.rst:907 +#: library/argparse.rst:727 msgid "" -"``'extend'`` - This stores a list, and extends each argument value to the " -"list. Example usage::" +">>> import argparse\n" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('--version', action='version', version='%(prog)s " +"2.0')\n" +">>> parser.parse_args(['--version'])\n" +"PROG 2.0" msgstr "" -#: library/argparse.rst:918 +#: library/argparse.rst:733 msgid "" -"You may also specify an arbitrary action by passing an Action subclass or " -"other object that implements the same interface. The " -"``BooleanOptionalAction`` is available in ``argparse`` and adds support for " +"Only actions that consume command-line arguments (e.g. ``'store'``, " +"``'append'`` or ``'extend'``) can be used with positional arguments." +msgstr "" + +#: library/argparse.rst:738 +msgid "" +"You may also specify an arbitrary action by passing an :class:`Action` " +"subclass or other object that implements the same interface. The :class:`!" +"BooleanOptionalAction` is available in :mod:`!argparse` and adds support for " "boolean actions such as ``--foo`` and ``--no-foo``::" msgstr "" -#: library/argparse.rst:931 +#: library/argparse.rst:743 +msgid "" +">>> import argparse\n" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)\n" +">>> parser.parse_args(['--no-foo'])\n" +"Namespace(foo=False)" +msgstr "" + +#: library/argparse.rst:751 msgid "" "The recommended way to create a custom action is to extend :class:`Action`, " -"overriding the ``__call__`` method and optionally the ``__init__`` and " -"``format_usage`` methods." +"overriding the :meth:`!__call__` method and optionally the :meth:`!__init__` " +"and :meth:`!format_usage` methods." msgstr "" -#: library/argparse.rst:935 +#: library/argparse.rst:755 msgid "An example of a custom action::" msgstr "" -#: library/argparse.rst:955 +#: library/argparse.rst:757 +msgid "" +">>> class FooAction(argparse.Action):\n" +"... def __init__(self, option_strings, dest, nargs=None, **kwargs):\n" +"... if nargs is not None:\n" +"... raise ValueError(\"nargs not allowed\")\n" +"... super().__init__(option_strings, dest, **kwargs)\n" +"... def __call__(self, parser, namespace, values, option_string=None):\n" +"... print('%r %r %r' % (namespace, values, option_string))\n" +"... setattr(namespace, self.dest, values)\n" +"...\n" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action=FooAction)\n" +">>> parser.add_argument('bar', action=FooAction)\n" +">>> args = parser.parse_args('1 --foo 2'.split())\n" +"Namespace(bar=None, foo=None) '1' None\n" +"Namespace(bar='1', foo=None) '2' '--foo'\n" +">>> args\n" +"Namespace(bar='1', foo='2')" +msgstr "" + +#: library/argparse.rst:775 msgid "For more details, see :class:`Action`." msgstr "" -#: library/argparse.rst:961 +#: library/argparse.rst:781 msgid "nargs" msgstr "" -#: library/argparse.rst:963 +#: library/argparse.rst:783 msgid "" -"ArgumentParser objects usually associate a single command-line argument with " -"a single action to be taken. The ``nargs`` keyword argument associates a " -"different number of command-line arguments with a single action. See also :" -"ref:`specifying-ambiguous-arguments`. The supported values are:" +":class:`ArgumentParser` objects usually associate a single command-line " +"argument with a single action to be taken. The ``nargs`` keyword argument " +"associates a different number of command-line arguments with a single " +"action. See also :ref:`specifying-ambiguous-arguments`. The supported values " +"are:" msgstr "" -#: library/argparse.rst:968 +#: library/argparse.rst:788 msgid "" "``N`` (an integer). ``N`` arguments from the command line will be gathered " "together into a list. For example::" msgstr "" -#: library/argparse.rst:977 +#: library/argparse.rst:791 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', nargs=2)\n" +">>> parser.add_argument('bar', nargs=1)\n" +">>> parser.parse_args('c --foo a b'.split())\n" +"Namespace(bar=['c'], foo=['a', 'b'])" +msgstr "" + +#: library/argparse.rst:797 msgid "" "Note that ``nargs=1`` produces a list of one item. This is different from " "the default, in which the item is produced by itself." msgstr "" -#: library/argparse.rst:982 +#: library/argparse.rst:802 msgid "" "``'?'``. One argument will be consumed from the command line if possible, " "and produced as a single item. If no command-line argument is present, the " @@ -961,13 +1166,41 @@ msgid "" "produced. Some examples to illustrate this::" msgstr "" -#: library/argparse.rst:999 +#: library/argparse.rst:809 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', nargs='?', const='c', default='d')\n" +">>> parser.add_argument('bar', nargs='?', default='d')\n" +">>> parser.parse_args(['XX', '--foo', 'YY'])\n" +"Namespace(bar='XX', foo='YY')\n" +">>> parser.parse_args(['XX', '--foo'])\n" +"Namespace(bar='XX', foo='c')\n" +">>> parser.parse_args([])\n" +"Namespace(bar='d', foo='d')" +msgstr "" + +#: library/argparse.rst:819 msgid "" "One of the more common uses of ``nargs='?'`` is to allow optional input and " "output files::" msgstr "" -#: library/argparse.rst:1016 +#: library/argparse.rst:822 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),\n" +"... default=sys.stdin)\n" +">>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),\n" +"... default=sys.stdout)\n" +">>> parser.parse_args(['input.txt', 'output.txt'])\n" +"Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,\n" +" outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)\n" +">>> parser.parse_args([])\n" +"Namespace(infile=<_io.TextIOWrapper name='' encoding='UTF-8'>,\n" +" outfile=<_io.TextIOWrapper name='' encoding='UTF-8'>)" +msgstr "" + +#: library/argparse.rst:836 msgid "" "``'*'``. All command-line arguments present are gathered into a list. Note " "that it generally doesn't make much sense to have more than one positional " @@ -975,26 +1208,48 @@ msgid "" "``nargs='*'`` is possible. For example::" msgstr "" -#: library/argparse.rst:1030 +#: library/argparse.rst:841 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', nargs='*')\n" +">>> parser.add_argument('--bar', nargs='*')\n" +">>> parser.add_argument('baz', nargs='*')\n" +">>> parser.parse_args('a b --foo x y --bar 1 2'.split())\n" +"Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])" +msgstr "" + +#: library/argparse.rst:850 msgid "" "``'+'``. Just like ``'*'``, all command-line args present are gathered into " "a list. Additionally, an error message will be generated if there wasn't at " "least one command-line argument present. For example::" msgstr "" -#: library/argparse.rst:1042 +#: library/argparse.rst:854 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('foo', nargs='+')\n" +">>> parser.parse_args(['a', 'b'])\n" +"Namespace(foo=['a', 'b'])\n" +">>> parser.parse_args([])\n" +"usage: PROG [-h] foo [foo ...]\n" +"PROG: error: the following arguments are required: foo" +msgstr "" + +#: library/argparse.rst:862 msgid "" "If the ``nargs`` keyword argument is not provided, the number of arguments " "consumed is determined by the action_. Generally this means a single " "command-line argument will be consumed and a single item (not a list) will " -"be produced." +"be produced. Actions that do not consume command-line arguments (e.g. " +"``'store_const'``) set ``nargs=0``." msgstr "" -#: library/argparse.rst:1050 +#: library/argparse.rst:872 msgid "const" msgstr "" -#: library/argparse.rst:1052 +#: library/argparse.rst:874 msgid "" "The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to " "hold constant values that are not read from the command line but are " @@ -1002,7 +1257,7 @@ msgid "" "common uses of it are:" msgstr "" -#: library/argparse.rst:1056 +#: library/argparse.rst:878 msgid "" "When :meth:`~ArgumentParser.add_argument` is called with " "``action='store_const'`` or ``action='append_const'``. These actions add " @@ -1012,7 +1267,7 @@ msgid "" "receive a default value of ``None``." msgstr "" -#: library/argparse.rst:1064 +#: library/argparse.rst:886 msgid "" "When :meth:`~ArgumentParser.add_argument` is called with option strings " "(like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional " @@ -1022,17 +1277,17 @@ msgid "" "to be ``None`` instead. See the nargs_ description for examples." msgstr "" -#: library/argparse.rst:1071 +#: library/argparse.rst:893 msgid "" "``const=None`` by default, including when ``action='append_const'`` or " "``action='store_const'``." msgstr "" -#: library/argparse.rst:1078 +#: library/argparse.rst:900 msgid "default" msgstr "" -#: library/argparse.rst:1080 +#: library/argparse.rst:902 msgid "" "All optional arguments and some positional arguments may be omitted at the " "command line. The ``default`` keyword argument of :meth:`~ArgumentParser." @@ -1042,13 +1297,31 @@ msgid "" "command line::" msgstr "" -#: library/argparse.rst:1094 +#: library/argparse.rst:909 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', default=42)\n" +">>> parser.parse_args(['--foo', '2'])\n" +"Namespace(foo='2')\n" +">>> parser.parse_args([])\n" +"Namespace(foo=42)" +msgstr "" + +#: library/argparse.rst:916 msgid "" "If the target namespace already has an attribute set, the action *default* " -"will not over write it::" +"will not overwrite it::" +msgstr "" + +#: library/argparse.rst:919 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', default=42)\n" +">>> parser.parse_args([], namespace=argparse.Namespace(foo=101))\n" +"Namespace(foo=101)" msgstr "" -#: library/argparse.rst:1102 +#: library/argparse.rst:924 msgid "" "If the ``default`` value is a string, the parser parses the value as if it " "were a command-line argument. In particular, the parser applies any type_ " @@ -1056,23 +1329,59 @@ msgid "" "`Namespace` return value. Otherwise, the parser uses the value as is::" msgstr "" -#: library/argparse.rst:1113 +#: library/argparse.rst:929 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--length', default='10', type=int)\n" +">>> parser.add_argument('--width', default=10.5, type=int)\n" +">>> parser.parse_args()\n" +"Namespace(length=10, width=10.5)" +msgstr "" + +#: library/argparse.rst:935 msgid "" "For positional arguments with nargs_ equal to ``?`` or ``*``, the " "``default`` value is used when no command-line argument was present::" msgstr "" -#: library/argparse.rst:1124 +#: library/argparse.rst:938 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('foo', nargs='?', default=42)\n" +">>> parser.parse_args(['a'])\n" +"Namespace(foo='a')\n" +">>> parser.parse_args([])\n" +"Namespace(foo=42)" +msgstr "" + +#: library/argparse.rst:945 +msgid "" +"For required_ arguments, the ``default`` value is ignored. For example, this " +"applies to positional arguments with nargs_ values other than ``?`` or " +"``*``, or optional arguments marked as ``required=True``." +msgstr "" + +#: library/argparse.rst:949 msgid "" "Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if " "the command-line argument was not present::" msgstr "" -#: library/argparse.rst:1138 +#: library/argparse.rst:952 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', default=argparse.SUPPRESS)\n" +">>> parser.parse_args([])\n" +"Namespace()\n" +">>> parser.parse_args(['--foo', '1'])\n" +"Namespace(foo='1')" +msgstr "" + +#: library/argparse.rst:963 msgid "type" msgstr "" -#: library/argparse.rst:1140 +#: library/argparse.rst:965 msgid "" "By default, the parser reads command-line arguments in as simple strings. " "However, quite often the command-line string should instead be interpreted " @@ -1081,13 +1390,13 @@ msgid "" "checking and type conversions to be performed." msgstr "" -#: library/argparse.rst:1146 +#: library/argparse.rst:971 msgid "" "If the type_ keyword is used with the default_ keyword, the type converter " "is only applied if the default is a string." msgstr "" -#: library/argparse.rst:1149 +#: library/argparse.rst:974 msgid "" "The argument to ``type`` can be any callable that accepts a single string. " "If the function raises :exc:`ArgumentTypeError`, :exc:`TypeError`, or :exc:" @@ -1095,22 +1404,48 @@ msgid "" "is displayed. No other exception types are handled." msgstr "" -#: library/argparse.rst:1154 +#: library/argparse.rst:979 msgid "Common built-in types and functions can be used as type converters:" msgstr "" -#: library/argparse.rst:1170 +#: library/argparse.rst:981 +msgid "" +"import argparse\n" +"import pathlib\n" +"\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument('count', type=int)\n" +"parser.add_argument('distance', type=float)\n" +"parser.add_argument('street', type=ascii)\n" +"parser.add_argument('code_point', type=ord)\n" +"parser.add_argument('dest_file', type=argparse.FileType('w', " +"encoding='latin-1'))\n" +"parser.add_argument('datapath', type=pathlib.Path)" +msgstr "" + +#: library/argparse.rst:994 msgid "User defined functions can be used as well:" msgstr "" -#: library/argparse.rst:1182 +#: library/argparse.rst:996 +msgid "" +">>> def hyphenated(string):\n" +"... return '-'.join([word[:4] for word in string.casefold().split()])\n" +"...\n" +">>> parser = argparse.ArgumentParser()\n" +">>> _ = parser.add_argument('short_title', type=hyphenated)\n" +">>> parser.parse_args(['\"The Tale of Two Cities\"'])\n" +"Namespace(short_title='\"the-tale-of-two-citi')" +msgstr "" + +#: library/argparse.rst:1006 msgid "" "The :func:`bool` function is not recommended as a type converter. All it " "does is convert empty strings to ``False`` and non-empty strings to " "``True``. This is usually not what is desired." msgstr "" -#: library/argparse.rst:1186 +#: library/argparse.rst:1010 msgid "" "In general, the ``type`` keyword is a convenience that should only be used " "for simple conversions that can only raise one of the three supported " @@ -1118,7 +1453,7 @@ msgid "" "management should be done downstream after the arguments are parsed." msgstr "" -#: library/argparse.rst:1191 +#: library/argparse.rst:1015 msgid "" "For example, JSON or YAML conversions have complex error cases that require " "better reporting than can be given by the ``type`` keyword. A :exc:`~json." @@ -1126,26 +1461,27 @@ msgid "" "exception would not be handled at all." msgstr "" -#: library/argparse.rst:1196 +#: library/argparse.rst:1020 msgid "" "Even :class:`~argparse.FileType` has its limitations for use with the " -"``type`` keyword. If one argument uses *FileType* and then a subsequent " -"argument fails, an error is reported but the file is not automatically " -"closed. In this case, it would be better to wait until after the parser has " -"run and then use the :keyword:`with`-statement to manage the files." +"``type`` keyword. If one argument uses :class:`~argparse.FileType` and then " +"a subsequent argument fails, an error is reported but the file is not " +"automatically closed. In this case, it would be better to wait until after " +"the parser has run and then use the :keyword:`with`-statement to manage the " +"files." msgstr "" -#: library/argparse.rst:1202 +#: library/argparse.rst:1027 msgid "" "For type checkers that simply check against a fixed set of values, consider " "using the choices_ keyword instead." msgstr "" -#: library/argparse.rst:1209 +#: library/argparse.rst:1034 msgid "choices" msgstr "" -#: library/argparse.rst:1211 +#: library/argparse.rst:1036 msgid "" "Some command-line arguments should be selected from a restricted set of " "values. These can be handled by passing a sequence object as the *choices* " @@ -1154,26 +1490,38 @@ msgid "" "be displayed if the argument was not one of the acceptable values::" msgstr "" -#: library/argparse.rst:1226 +#: library/argparse.rst:1042 +msgid "" +">>> parser = argparse.ArgumentParser(prog='game.py')\n" +">>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])\n" +">>> parser.parse_args(['rock'])\n" +"Namespace(move='rock')\n" +">>> parser.parse_args(['fire'])\n" +"usage: game.py [-h] {rock,paper,scissors}\n" +"game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',\n" +"'paper', 'scissors')" +msgstr "" + +#: library/argparse.rst:1051 msgid "" "Note that inclusion in the *choices* sequence is checked after any type_ " "conversions have been performed, so the type of the objects in the *choices* " -"sequence should match the type_ specified::" +"sequence should match the type_ specified." msgstr "" -#: library/argparse.rst:1238 +#: library/argparse.rst:1055 msgid "" "Any sequence can be passed as the *choices* value, so :class:`list` " "objects, :class:`tuple` objects, and custom sequences are all supported." msgstr "" -#: library/argparse.rst:1241 +#: library/argparse.rst:1058 msgid "" "Use of :class:`enum.Enum` is not recommended because it is difficult to " "control its appearance in usage, help, and error messages." msgstr "" -#: library/argparse.rst:1244 +#: library/argparse.rst:1061 msgid "" "Formatted choices override the default *metavar* which is normally derived " "from *dest*. This is usually what you want because the user never sees the " @@ -1181,44 +1529,55 @@ msgid "" "are many choices), just specify an explicit metavar_." msgstr "" -#: library/argparse.rst:1253 +#: library/argparse.rst:1070 msgid "required" msgstr "" -#: library/argparse.rst:1255 +#: library/argparse.rst:1072 msgid "" -"In general, the :mod:`argparse` module assumes that flags like ``-f`` and " +"In general, the :mod:`!argparse` module assumes that flags like ``-f`` and " "``--bar`` indicate *optional* arguments, which can always be omitted at the " "command line. To make an option *required*, ``True`` can be specified for " "the ``required=`` keyword argument to :meth:`~ArgumentParser.add_argument`::" msgstr "" -#: library/argparse.rst:1268 +#: library/argparse.rst:1077 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', required=True)\n" +">>> parser.parse_args(['--foo', 'BAR'])\n" +"Namespace(foo='BAR')\n" +">>> parser.parse_args([])\n" +"usage: [-h] --foo FOO\n" +": error: the following arguments are required: --foo" +msgstr "" + +#: library/argparse.rst:1085 msgid "" "As the example shows, if an option is marked as ``required``, :meth:" "`~ArgumentParser.parse_args` will report an error if that option is not " "present at the command line." msgstr "" -#: library/argparse.rst:1274 +#: library/argparse.rst:1091 msgid "" "Required options are generally considered bad form because users expect " "*options* to be *optional*, and thus they should be avoided when possible." msgstr "" -#: library/argparse.rst:1281 +#: library/argparse.rst:1098 msgid "help" msgstr "" -#: library/argparse.rst:1283 +#: library/argparse.rst:1100 msgid "" "The ``help`` value is a string containing a brief description of the " "argument. When a user requests help (usually by using ``-h`` or ``--help`` " "at the command line), these ``help`` descriptions will be displayed with " -"each argument::" +"each argument." msgstr "" -#: library/argparse.rst:1303 +#: library/argparse.rst:1105 msgid "" "The ``help`` strings can include various format specifiers to avoid " "repetition of things like the program name or the argument default_. The " @@ -1227,57 +1586,133 @@ msgid "" "``%(type)s``, etc.::" msgstr "" -#: library/argparse.rst:1320 +#: library/argparse.rst:1110 +msgid "" +">>> parser = argparse.ArgumentParser(prog='frobble')\n" +">>> parser.add_argument('bar', nargs='?', type=int, default=42,\n" +"... help='the bar to %(prog)s (default: %(default)s)')\n" +">>> parser.print_help()\n" +"usage: frobble [-h] [bar]\n" +"\n" +"positional arguments:\n" +" bar the bar to frobble (default: 42)\n" +"\n" +"options:\n" +" -h, --help show this help message and exit" +msgstr "" + +#: library/argparse.rst:1122 msgid "" "As the help string supports %-formatting, if you want a literal ``%`` to " "appear in the help string, you must escape it as ``%%``." msgstr "" -#: library/argparse.rst:1323 +#: library/argparse.rst:1125 msgid "" -":mod:`argparse` supports silencing the help entry for certain options, by " +":mod:`!argparse` supports silencing the help entry for certain options, by " "setting the ``help`` value to ``argparse.SUPPRESS``::" msgstr "" -#: library/argparse.rst:1338 +#: library/argparse.rst:1128 +msgid "" +">>> parser = argparse.ArgumentParser(prog='frobble')\n" +">>> parser.add_argument('--foo', help=argparse.SUPPRESS)\n" +">>> parser.print_help()\n" +"usage: frobble [-h]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit" +msgstr "" + +#: library/argparse.rst:1140 msgid "metavar" msgstr "" -#: library/argparse.rst:1340 +#: library/argparse.rst:1142 msgid "" "When :class:`ArgumentParser` generates help messages, it needs some way to " -"refer to each expected argument. By default, ArgumentParser objects use the " -"dest_ value as the \"name\" of each object. By default, for positional " -"argument actions, the dest_ value is used directly, and for optional " -"argument actions, the dest_ value is uppercased. So, a single positional " -"argument with ``dest='bar'`` will be referred to as ``bar``. A single " -"optional argument ``--foo`` that should be followed by a single command-line " -"argument will be referred to as ``FOO``. An example::" +"refer to each expected argument. By default, :class:`!ArgumentParser` " +"objects use the dest_ value as the \"name\" of each object. By default, for " +"positional argument actions, the dest_ value is used directly, and for " +"optional argument actions, the dest_ value is uppercased. So, a single " +"positional argument with ``dest='bar'`` will be referred to as ``bar``. A " +"single optional argument ``--foo`` that should be followed by a single " +"command-line argument will be referred to as ``FOO``. An example::" +msgstr "" + +#: library/argparse.rst:1151 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo')\n" +">>> parser.add_argument('bar')\n" +">>> parser.parse_args('X --foo Y'.split())\n" +"Namespace(bar='X', foo='Y')\n" +">>> parser.print_help()\n" +"usage: [-h] [--foo FOO] bar\n" +"\n" +"positional arguments:\n" +" bar\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo FOO" +msgstr "" + +#: library/argparse.rst:1166 +msgid "An alternative name can be specified with ``metavar``::" msgstr "" -#: library/argparse.rst:1364 -msgid "An alternative name can be specified with ``metavar``::" +#: library/argparse.rst:1168 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', metavar='YYY')\n" +">>> parser.add_argument('bar', metavar='XXX')\n" +">>> parser.parse_args('X --foo Y'.split())\n" +"Namespace(bar='X', foo='Y')\n" +">>> parser.print_help()\n" +"usage: [-h] [--foo YYY] XXX\n" +"\n" +"positional arguments:\n" +" XXX\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo YYY" msgstr "" -#: library/argparse.rst:1381 +#: library/argparse.rst:1183 msgid "" "Note that ``metavar`` only changes the *displayed* name - the name of the " "attribute on the :meth:`~ArgumentParser.parse_args` object is still " "determined by the dest_ value." msgstr "" -#: library/argparse.rst:1385 +#: library/argparse.rst:1187 msgid "" "Different values of ``nargs`` may cause the metavar to be used multiple " "times. Providing a tuple to ``metavar`` specifies a different display for " "each of the arguments::" msgstr "" -#: library/argparse.rst:1404 +#: library/argparse.rst:1191 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-x', nargs=2)\n" +">>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))\n" +">>> parser.print_help()\n" +"usage: PROG [-h] [-x X X] [--foo bar baz]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" -x X X\n" +" --foo bar baz" +msgstr "" + +#: library/argparse.rst:1206 msgid "dest" msgstr "" -#: library/argparse.rst:1406 +#: library/argparse.rst:1208 msgid "" "Most :class:`ArgumentParser` actions add some value as an attribute of the " "object returned by :meth:`~ArgumentParser.parse_args`. The name of this " @@ -1287,7 +1722,15 @@ msgid "" "add_argument`::" msgstr "" -#: library/argparse.rst:1418 +#: library/argparse.rst:1215 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('bar')\n" +">>> parser.parse_args(['XXX'])\n" +"Namespace(bar='XXX')" +msgstr "" + +#: library/argparse.rst:1220 msgid "" "For optional argument actions, the value of ``dest`` is normally inferred " "from the option strings. :class:`ArgumentParser` generates the value of " @@ -1299,147 +1742,203 @@ msgid "" "below illustrate this behavior::" msgstr "" -#: library/argparse.rst:1435 +#: library/argparse.rst:1229 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('-f', '--foo-bar', '--foo')\n" +">>> parser.add_argument('-x', '-y')\n" +">>> parser.parse_args('-f 1 -x 2'.split())\n" +"Namespace(foo_bar='1', x='2')\n" +">>> parser.parse_args('--foo 1 -y 2'.split())\n" +"Namespace(foo_bar='1', x='2')" +msgstr "" + +#: library/argparse.rst:1237 msgid "``dest`` allows a custom attribute name to be provided::" msgstr "" -#: library/argparse.rst:1443 +#: library/argparse.rst:1239 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', dest='bar')\n" +">>> parser.parse_args('--foo XXX'.split())\n" +"Namespace(bar='XXX')" +msgstr "" + +#: library/argparse.rst:1245 msgid "Action classes" msgstr "" -#: library/argparse.rst:1445 +#: library/argparse.rst:1247 msgid "" -"Action classes implement the Action API, a callable which returns a callable " -"which processes arguments from the command-line. Any object which follows " -"this API may be passed as the ``action`` parameter to :meth:`~ArgumentParser." -"add_argument`." +":class:`!Action` classes implement the Action API, a callable which returns " +"a callable which processes arguments from the command-line. Any object which " +"follows this API may be passed as the ``action`` parameter to :meth:" +"`~ArgumentParser.add_argument`." msgstr "" -#: library/argparse.rst:1454 +#: library/argparse.rst:1256 msgid "" -"Action objects are used by an ArgumentParser to represent the information " -"needed to parse a single argument from one or more strings from the command " -"line. The Action class must accept the two positional arguments plus any " -"keyword arguments passed to :meth:`ArgumentParser.add_argument` except for " -"the ``action`` itself." +":class:`!Action` objects are used by an :class:`ArgumentParser` to represent " +"the information needed to parse a single argument from one or more strings " +"from the command line. The :class:`!Action` class must accept the two " +"positional arguments plus any keyword arguments passed to :meth:" +"`ArgumentParser.add_argument` except for the ``action`` itself." msgstr "" -#: library/argparse.rst:1460 +#: library/argparse.rst:1262 msgid "" -"Instances of Action (or return value of any callable to the ``action`` " -"parameter) should have attributes \"dest\", \"option_strings\", \"default\", " -"\"type\", \"required\", \"help\", etc. defined. The easiest way to ensure " -"these attributes are defined is to call ``Action.__init__``." +"Instances of :class:`!Action` (or return value of any callable to the " +"``action`` parameter) should have attributes :attr:`!dest`, :attr:`!" +"option_strings`, :attr:`!default`, :attr:`!type`, :attr:`!required`, :attr:`!" +"help`, etc. defined. The easiest way to ensure these attributes are defined " +"is to call :meth:`!Action.__init__`." msgstr "" -#: library/argparse.rst:1465 +#: library/argparse.rst:1270 msgid "" -"Action instances should be callable, so subclasses must override the " -"``__call__`` method, which should accept four parameters:" +":class:`!Action` instances should be callable, so subclasses must override " +"the :meth:`!__call__` method, which should accept four parameters:" msgstr "" -#: library/argparse.rst:1468 -msgid "``parser`` - The ArgumentParser object which contains this action." +#: library/argparse.rst:1273 +msgid "" +"*parser* - The :class:`ArgumentParser` object which contains this action." msgstr "" -#: library/argparse.rst:1470 +#: library/argparse.rst:1275 msgid "" -"``namespace`` - The :class:`Namespace` object that will be returned by :meth:" +"*namespace* - The :class:`Namespace` object that will be returned by :meth:" "`~ArgumentParser.parse_args`. Most actions add an attribute to this object " "using :func:`setattr`." msgstr "" -#: library/argparse.rst:1474 +#: library/argparse.rst:1279 msgid "" -"``values`` - The associated command-line arguments, with any type " -"conversions applied. Type conversions are specified with the type_ keyword " -"argument to :meth:`~ArgumentParser.add_argument`." +"*values* - The associated command-line arguments, with any type conversions " +"applied. Type conversions are specified with the type_ keyword argument to :" +"meth:`~ArgumentParser.add_argument`." msgstr "" -#: library/argparse.rst:1478 +#: library/argparse.rst:1283 msgid "" -"``option_string`` - The option string that was used to invoke this action. " -"The ``option_string`` argument is optional, and will be absent if the action " -"is associated with a positional argument." +"*option_string* - The option string that was used to invoke this action. The " +"``option_string`` argument is optional, and will be absent if the action is " +"associated with a positional argument." msgstr "" -#: library/argparse.rst:1482 +#: library/argparse.rst:1287 msgid "" -"The ``__call__`` method may perform arbitrary actions, but will typically " -"set attributes on the ``namespace`` based on ``dest`` and ``values``." +"The :meth:`!__call__` method may perform arbitrary actions, but will " +"typically set attributes on the ``namespace`` based on ``dest`` and " +"``values``." msgstr "" -#: library/argparse.rst:1485 +#: library/argparse.rst:1292 msgid "" -"Action subclasses can define a ``format_usage`` method that takes no " -"argument and return a string which will be used when printing the usage of " -"the program. If such method is not provided, a sensible default will be used." +":class:`!Action` subclasses can define a :meth:`!format_usage` method that " +"takes no argument and return a string which will be used when printing the " +"usage of the program. If such method is not provided, a sensible default " +"will be used." msgstr "" -#: library/argparse.rst:1490 +#: library/argparse.rst:1298 msgid "The parse_args() method" msgstr "" -#: library/argparse.rst:1494 +#: library/argparse.rst:1302 msgid "" "Convert argument strings to objects and assign them as attributes of the " "namespace. Return the populated namespace." msgstr "" -#: library/argparse.rst:1497 +#: library/argparse.rst:1305 msgid "" "Previous calls to :meth:`add_argument` determine exactly what objects are " -"created and how they are assigned. See the documentation for :meth:" -"`add_argument` for details." +"created and how they are assigned. See the documentation for :meth:`!" +"add_argument` for details." msgstr "" -#: library/argparse.rst:1501 +#: library/argparse.rst:1309 msgid "" "args_ - List of strings to parse. The default is taken from :data:`sys." "argv`." msgstr "" -#: library/argparse.rst:1504 +#: library/argparse.rst:1312 msgid "" "namespace_ - An object to take the attributes. The default is a new empty :" "class:`Namespace` object." msgstr "" -#: library/argparse.rst:1509 +#: library/argparse.rst:1317 msgid "Option value syntax" msgstr "" -#: library/argparse.rst:1511 +#: library/argparse.rst:1319 msgid "" "The :meth:`~ArgumentParser.parse_args` method supports several ways of " "specifying the value of an option (if it takes one). In the simplest case, " "the option and its value are passed as two separate arguments::" msgstr "" -#: library/argparse.rst:1523 +#: library/argparse.rst:1323 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-x')\n" +">>> parser.add_argument('--foo')\n" +">>> parser.parse_args(['-x', 'X'])\n" +"Namespace(foo=None, x='X')\n" +">>> parser.parse_args(['--foo', 'FOO'])\n" +"Namespace(foo='FOO', x=None)" +msgstr "" + +#: library/argparse.rst:1331 msgid "" "For long options (options with names longer than a single character), the " "option and value can also be passed as a single command-line argument, using " "``=`` to separate them::" msgstr "" -#: library/argparse.rst:1530 +#: library/argparse.rst:1335 +msgid "" +">>> parser.parse_args(['--foo=FOO'])\n" +"Namespace(foo='FOO', x=None)" +msgstr "" + +#: library/argparse.rst:1338 msgid "" "For short options (options only one character long), the option and its " "value can be concatenated::" msgstr "" -#: library/argparse.rst:1536 +#: library/argparse.rst:1341 +msgid "" +">>> parser.parse_args(['-xX'])\n" +"Namespace(foo=None, x='X')" +msgstr "" + +#: library/argparse.rst:1344 msgid "" "Several short options can be joined together, using only a single ``-`` " "prefix, as long as only the last option (or none of them) requires a value::" msgstr "" -#: library/argparse.rst:1548 +#: library/argparse.rst:1347 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-x', action='store_true')\n" +">>> parser.add_argument('-y', action='store_true')\n" +">>> parser.add_argument('-z')\n" +">>> parser.parse_args(['-xyzZ'])\n" +"Namespace(x=True, y=True, z='Z')" +msgstr "" + +#: library/argparse.rst:1356 msgid "Invalid arguments" msgstr "" -#: library/argparse.rst:1550 +#: library/argparse.rst:1358 msgid "" "While parsing the command line, :meth:`~ArgumentParser.parse_args` checks " "for a variety of errors, including ambiguous options, invalid types, invalid " @@ -1447,11 +1946,33 @@ msgid "" "an error, it exits and prints the error along with a usage message::" msgstr "" -#: library/argparse.rst:1576 +#: library/argparse.rst:1363 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('--foo', type=int)\n" +">>> parser.add_argument('bar', nargs='?')\n" +"\n" +">>> # invalid type\n" +">>> parser.parse_args(['--foo', 'spam'])\n" +"usage: PROG [-h] [--foo FOO] [bar]\n" +"PROG: error: argument --foo: invalid int value: 'spam'\n" +"\n" +">>> # invalid option\n" +">>> parser.parse_args(['--bar'])\n" +"usage: PROG [-h] [--foo FOO] [bar]\n" +"PROG: error: no such option: --bar\n" +"\n" +">>> # wrong number of arguments\n" +">>> parser.parse_args(['spam', 'badger'])\n" +"usage: PROG [-h] [--foo FOO] [bar]\n" +"PROG: error: extra arguments found: badger" +msgstr "" + +#: library/argparse.rst:1384 msgid "Arguments containing ``-``" msgstr "" -#: library/argparse.rst:1578 +#: library/argparse.rst:1386 msgid "" "The :meth:`~ArgumentParser.parse_args` method attempts to give errors " "whenever the user has clearly made a mistake, but some situations are " @@ -1463,7 +1984,40 @@ msgid "" "negative numbers::" msgstr "" -#: library/argparse.rst:1616 +#: library/argparse.rst:1394 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-x')\n" +">>> parser.add_argument('foo', nargs='?')\n" +"\n" +">>> # no negative number options, so -1 is a positional argument\n" +">>> parser.parse_args(['-x', '-1'])\n" +"Namespace(foo=None, x='-1')\n" +"\n" +">>> # no negative number options, so -1 and -5 are positional arguments\n" +">>> parser.parse_args(['-x', '-1', '-5'])\n" +"Namespace(foo='-5', x='-1')\n" +"\n" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-1', dest='one')\n" +">>> parser.add_argument('foo', nargs='?')\n" +"\n" +">>> # negative number options present, so -1 is an option\n" +">>> parser.parse_args(['-1', 'X'])\n" +"Namespace(foo=None, one='X')\n" +"\n" +">>> # negative number options present, so -2 is an option\n" +">>> parser.parse_args(['-2'])\n" +"usage: PROG [-h] [-1 ONE] [foo]\n" +"PROG: error: no such option: -2\n" +"\n" +">>> # negative number options present, so both -1s are options\n" +">>> parser.parse_args(['-1', '-1'])\n" +"usage: PROG [-h] [-1 ONE] [foo]\n" +"PROG: error: argument -1: expected one argument" +msgstr "" + +#: library/argparse.rst:1424 msgid "" "If you have positional arguments that must begin with ``-`` and don't look " "like negative numbers, you can insert the pseudo-argument ``'--'`` which " @@ -1471,152 +2025,231 @@ msgid "" "positional argument::" msgstr "" -#: library/argparse.rst:1624 +#: library/argparse.rst:1429 +msgid "" +">>> parser.parse_args(['--', '-f'])\n" +"Namespace(foo='-f', one=None)" +msgstr "" + +#: library/argparse.rst:1432 msgid "" "See also :ref:`the argparse howto on ambiguous arguments ` for more details." msgstr "" -#: library/argparse.rst:1630 +#: library/argparse.rst:1438 msgid "Argument abbreviations (prefix matching)" msgstr "" -#: library/argparse.rst:1632 +#: library/argparse.rst:1440 msgid "" "The :meth:`~ArgumentParser.parse_args` method :ref:`by default " "` allows long options to be abbreviated to a prefix, if the " "abbreviation is unambiguous (the prefix matches a unique option)::" msgstr "" -#: library/argparse.rst:1647 +#: library/argparse.rst:1444 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('-bacon')\n" +">>> parser.add_argument('-badger')\n" +">>> parser.parse_args('-bac MMM'.split())\n" +"Namespace(bacon='MMM', badger=None)\n" +">>> parser.parse_args('-bad WOOD'.split())\n" +"Namespace(bacon=None, badger='WOOD')\n" +">>> parser.parse_args('-ba BA'.split())\n" +"usage: PROG [-h] [-bacon BACON] [-badger BADGER]\n" +"PROG: error: ambiguous option: -ba could match -badger, -bacon" +msgstr "" + +#: library/argparse.rst:1455 msgid "" "An error is produced for arguments that could produce more than one options. " "This feature can be disabled by setting :ref:`allow_abbrev` to ``False``." msgstr "" -#: library/argparse.rst:1653 +#: library/argparse.rst:1461 msgid "Beyond ``sys.argv``" msgstr "" -#: library/argparse.rst:1655 +#: library/argparse.rst:1463 +msgid "" +"Sometimes it may be useful to have an :class:`ArgumentParser` parse " +"arguments other than those of :data:`sys.argv`. This can be accomplished by " +"passing a list of strings to :meth:`~ArgumentParser.parse_args`. This is " +"useful for testing at the interactive prompt::" +msgstr "" + +#: library/argparse.rst:1468 msgid "" -"Sometimes it may be useful to have an ArgumentParser parse arguments other " -"than those of :data:`sys.argv`. This can be accomplished by passing a list " -"of strings to :meth:`~ArgumentParser.parse_args`. This is useful for " -"testing at the interactive prompt::" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument(\n" +"... 'integers', metavar='int', type=int, choices=range(10),\n" +"... nargs='+', help='an integer in the range 0..9')\n" +">>> parser.add_argument(\n" +"... '--sum', dest='accumulate', action='store_const', const=sum,\n" +"... default=max, help='sum the integers (default: find the max)')\n" +">>> parser.parse_args(['1', '2', '3', '4'])\n" +"Namespace(accumulate=, integers=[1, 2, 3, 4])\n" +">>> parser.parse_args(['1', '2', '3', '4', '--sum'])\n" +"Namespace(accumulate=, integers=[1, 2, 3, 4])" msgstr "" -#: library/argparse.rst:1675 +#: library/argparse.rst:1483 msgid "The Namespace object" msgstr "" -#: library/argparse.rst:1679 +#: library/argparse.rst:1487 msgid "" "Simple class used by default by :meth:`~ArgumentParser.parse_args` to create " "an object holding attributes and return it." msgstr "" -#: library/argparse.rst:1682 +#: library/argparse.rst:1490 msgid "" "This class is deliberately simple, just an :class:`object` subclass with a " "readable string representation. If you prefer to have dict-like view of the " "attributes, you can use the standard Python idiom, :func:`vars`::" msgstr "" -#: library/argparse.rst:1692 +#: library/argparse.rst:1494 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo')\n" +">>> args = parser.parse_args(['--foo', 'BAR'])\n" +">>> vars(args)\n" +"{'foo': 'BAR'}" +msgstr "" + +#: library/argparse.rst:1500 msgid "" "It may also be useful to have an :class:`ArgumentParser` assign attributes " "to an already existing object, rather than a new :class:`Namespace` object. " "This can be achieved by specifying the ``namespace=`` keyword argument::" msgstr "" -#: library/argparse.rst:1708 +#: library/argparse.rst:1504 +msgid "" +">>> class C:\n" +"... pass\n" +"...\n" +">>> c = C()\n" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo')\n" +">>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)\n" +">>> c.foo\n" +"'BAR'" +msgstr "" + +#: library/argparse.rst:1516 msgid "Other utilities" msgstr "" -#: library/argparse.rst:1711 +#: library/argparse.rst:1519 msgid "Sub-commands" msgstr "" -#: library/argparse.rst:1718 +#: library/argparse.rst:1526 msgid "" -"Many programs split up their functionality into a number of sub-commands, " -"for example, the ``svn`` program can invoke sub-commands like ``svn " -"checkout``, ``svn update``, and ``svn commit``. Splitting up functionality " -"this way can be a particularly good idea when a program performs several " -"different functions which require different kinds of command-line " -"arguments. :class:`ArgumentParser` supports the creation of such sub-" -"commands with the :meth:`add_subparsers` method. The :meth:`add_subparsers` " -"method is normally called with no arguments and returns a special action " -"object. This object has a single method, :meth:`~_SubParsersAction." -"add_parser`, which takes a command name and any :class:`ArgumentParser` " -"constructor arguments, and returns an :class:`ArgumentParser` object that " -"can be modified as usual." +"Many programs split up their functionality into a number of subcommands, for " +"example, the ``svn`` program can invoke subcommands like ``svn checkout``, " +"``svn update``, and ``svn commit``. Splitting up functionality this way can " +"be a particularly good idea when a program performs several different " +"functions which require different kinds of command-line arguments. :class:" +"`ArgumentParser` supports the creation of such subcommands with the :meth:`!" +"add_subparsers` method. The :meth:`!add_subparsers` method is normally " +"called with no arguments and returns a special action object. This object " +"has a single method, :meth:`~_SubParsersAction.add_parser`, which takes a " +"command name and any :class:`!ArgumentParser` constructor arguments, and " +"returns an :class:`!ArgumentParser` object that can be modified as usual." msgstr "" -#: library/argparse.rst:1730 +#: library/argparse.rst:1538 msgid "Description of parameters:" msgstr "" -#: library/argparse.rst:1732 +#: library/argparse.rst:1540 msgid "" -"title - title for the sub-parser group in help output; by default " +"*title* - title for the sub-parser group in help output; by default " "\"subcommands\" if description is provided, otherwise uses title for " "positional arguments" msgstr "" -#: library/argparse.rst:1736 +#: library/argparse.rst:1544 msgid "" -"description - description for the sub-parser group in help output, by " +"*description* - description for the sub-parser group in help output, by " "default ``None``" msgstr "" -#: library/argparse.rst:1739 +#: library/argparse.rst:1547 msgid "" -"prog - usage information that will be displayed with sub-command help, by " +"*prog* - usage information that will be displayed with sub-command help, by " "default the name of the program and any positional arguments before the " "subparser argument" msgstr "" -#: library/argparse.rst:1743 +#: library/argparse.rst:1551 msgid "" -"parser_class - class which will be used to create sub-parser instances, by " -"default the class of the current parser (e.g. ArgumentParser)" +"*parser_class* - class which will be used to create sub-parser instances, by " +"default the class of the current parser (e.g. :class:`ArgumentParser`)" msgstr "" -#: library/argparse.rst:1746 +#: library/argparse.rst:1554 msgid "" "action_ - the basic type of action to be taken when this argument is " "encountered at the command line" msgstr "" -#: library/argparse.rst:1749 +#: library/argparse.rst:1557 msgid "" "dest_ - name of the attribute under which sub-command name will be stored; " "by default ``None`` and no value is stored" msgstr "" -#: library/argparse.rst:1752 +#: library/argparse.rst:1560 msgid "" "required_ - Whether or not a subcommand must be provided, by default " "``False`` (added in 3.7)" msgstr "" -#: library/argparse.rst:1755 +#: library/argparse.rst:1563 msgid "help_ - help for sub-parser group in help output, by default ``None``" msgstr "" -#: library/argparse.rst:1757 +#: library/argparse.rst:1565 msgid "" -"metavar_ - string presenting available sub-commands in help; by default it " -"is ``None`` and presents sub-commands in form {cmd1, cmd2, ..}" +"metavar_ - string presenting available subcommands in help; by default it is " +"``None`` and presents subcommands in form {cmd1, cmd2, ..}" msgstr "" -#: library/argparse.rst:1760 +#: library/argparse.rst:1568 msgid "Some example usage::" msgstr "" -#: library/argparse.rst:1781 +#: library/argparse.rst:1570 +msgid "" +">>> # create the top-level parser\n" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> parser.add_argument('--foo', action='store_true', help='foo help')\n" +">>> subparsers = parser.add_subparsers(help='subcommand help')\n" +">>>\n" +">>> # create the parser for the \"a\" command\n" +">>> parser_a = subparsers.add_parser('a', help='a help')\n" +">>> parser_a.add_argument('bar', type=int, help='bar help')\n" +">>>\n" +">>> # create the parser for the \"b\" command\n" +">>> parser_b = subparsers.add_parser('b', help='b help')\n" +">>> parser_b.add_argument('--baz', choices=('X', 'Y', 'Z'), help='baz " +"help')\n" +">>>\n" +">>> # parse some argument lists\n" +">>> parser.parse_args(['a', '12'])\n" +"Namespace(bar=12, foo=False)\n" +">>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])\n" +"Namespace(baz='Z', foo=True)" +msgstr "" + +#: library/argparse.rst:1589 msgid "" "Note that the object returned by :meth:`parse_args` will only contain " "attributes for the main parser and the subparser that was selected by the " @@ -1626,7 +2259,7 @@ msgid "" "``baz`` attributes are present." msgstr "" -#: library/argparse.rst:1788 +#: library/argparse.rst:1596 msgid "" "Similarly, when a help message is requested from a subparser, only the help " "for that particular parser will be printed. The help message will not " @@ -1635,21 +2268,82 @@ msgid "" "to :meth:`~_SubParsersAction.add_parser` as above.)" msgstr "" -#: library/argparse.rst:1824 +#: library/argparse.rst:1604 +msgid "" +">>> parser.parse_args(['--help'])\n" +"usage: PROG [-h] [--foo] {a,b} ...\n" +"\n" +"positional arguments:\n" +" {a,b} subcommand help\n" +" a a help\n" +" b b help\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --foo foo help\n" +"\n" +">>> parser.parse_args(['a', '--help'])\n" +"usage: PROG a [-h] bar\n" +"\n" +"positional arguments:\n" +" bar bar help\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"\n" +">>> parser.parse_args(['b', '--help'])\n" +"usage: PROG b [-h] [--baz {X,Y,Z}]\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +" --baz {X,Y,Z} baz help" +msgstr "" + +#: library/argparse.rst:1632 msgid "" "The :meth:`add_subparsers` method also supports ``title`` and " "``description`` keyword arguments. When either is present, the subparser's " "commands will appear in their own group in the help output. For example::" msgstr "" -#: library/argparse.rst:1845 +#: library/argparse.rst:1636 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> subparsers = parser.add_subparsers(title='subcommands',\n" +"... description='valid subcommands',\n" +"... help='additional help')\n" +">>> subparsers.add_parser('foo')\n" +">>> subparsers.add_parser('bar')\n" +">>> parser.parse_args(['-h'])\n" +"usage: [-h] {foo,bar} ...\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"\n" +"subcommands:\n" +" valid subcommands\n" +"\n" +" {foo,bar} additional help" +msgstr "" + +#: library/argparse.rst:1653 msgid "" "Furthermore, ``add_parser`` supports an additional ``aliases`` argument, " "which allows multiple strings to refer to the same subparser. This example, " "like ``svn``, aliases ``co`` as a shorthand for ``checkout``::" msgstr "" -#: library/argparse.rst:1856 +#: library/argparse.rst:1657 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> subparsers = parser.add_subparsers()\n" +">>> checkout = subparsers.add_parser('checkout', aliases=['co'])\n" +">>> checkout.add_argument('foo')\n" +">>> parser.parse_args(['co', 'bar'])\n" +"Namespace(foo='bar')" +msgstr "" + +#: library/argparse.rst:1664 msgid "" "One particularly effective way of handling sub-commands is to combine the " "use of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` " @@ -1657,7 +2351,42 @@ msgid "" "example::" msgstr "" -#: library/argparse.rst:1893 +#: library/argparse.rst:1669 +msgid "" +">>> # subcommand functions\n" +">>> def foo(args):\n" +"... print(args.x * args.y)\n" +"...\n" +">>> def bar(args):\n" +"... print('((%s))' % args.z)\n" +"...\n" +">>> # create the top-level parser\n" +">>> parser = argparse.ArgumentParser()\n" +">>> subparsers = parser.add_subparsers(required=True)\n" +">>>\n" +">>> # create the parser for the \"foo\" command\n" +">>> parser_foo = subparsers.add_parser('foo')\n" +">>> parser_foo.add_argument('-x', type=int, default=1)\n" +">>> parser_foo.add_argument('y', type=float)\n" +">>> parser_foo.set_defaults(func=foo)\n" +">>>\n" +">>> # create the parser for the \"bar\" command\n" +">>> parser_bar = subparsers.add_parser('bar')\n" +">>> parser_bar.add_argument('z')\n" +">>> parser_bar.set_defaults(func=bar)\n" +">>>\n" +">>> # parse the args and call whatever function was selected\n" +">>> args = parser.parse_args('foo 1 -x 2'.split())\n" +">>> args.func(args)\n" +"2.0\n" +">>>\n" +">>> # parse the args and call whatever function was selected\n" +">>> args = parser.parse_args('bar XYZYX'.split())\n" +">>> args.func(args)\n" +"((XYZYX))" +msgstr "" + +#: library/argparse.rst:1701 msgid "" "This way, you can let :meth:`parse_args` do the job of calling the " "appropriate function after argument parsing is complete. Associating " @@ -1667,15 +2396,27 @@ msgid "" "argument to the :meth:`add_subparsers` call will work::" msgstr "" -#: library/argparse.rst:1909 -msgid "New *required* keyword argument." +#: library/argparse.rst:1708 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> subparsers = parser.add_subparsers(dest='subparser_name')\n" +">>> subparser1 = subparsers.add_parser('1')\n" +">>> subparser1.add_argument('-x')\n" +">>> subparser2 = subparsers.add_parser('2')\n" +">>> subparser2.add_argument('y')\n" +">>> parser.parse_args(['2', 'frobble'])\n" +"Namespace(subparser_name='2', y='frobble')" msgstr "" -#: library/argparse.rst:1914 +#: library/argparse.rst:1717 +msgid "New *required* keyword-only parameter." +msgstr "" + +#: library/argparse.rst:1722 msgid "FileType objects" msgstr "" -#: library/argparse.rst:1918 +#: library/argparse.rst:1726 msgid "" "The :class:`FileType` factory creates objects that can be passed to the type " "argument of :meth:`ArgumentParser.add_argument`. Arguments that have :class:" @@ -1684,48 +2425,111 @@ msgid "" "the :func:`open` function for more details)::" msgstr "" -#: library/argparse.rst:1930 +#: library/argparse.rst:1732 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))\n" +">>> parser.add_argument('out', type=argparse.FileType('w', " +"encoding='UTF-8'))\n" +">>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])\n" +"Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, " +"raw=<_io.FileIO name='raw.dat' mode='wb'>)" +msgstr "" + +#: library/argparse.rst:1738 msgid "" "FileType objects understand the pseudo-argument ``'-'`` and automatically " "convert this into :data:`sys.stdin` for readable :class:`FileType` objects " "and :data:`sys.stdout` for writable :class:`FileType` objects::" msgstr "" -#: library/argparse.rst:1939 +#: library/argparse.rst:1742 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('infile', type=argparse.FileType('r'))\n" +">>> parser.parse_args(['-'])\n" +"Namespace(infile=<_io.TextIOWrapper name='' encoding='UTF-8'>)" +msgstr "" + +#: library/argparse.rst:1747 msgid "Added the *encodings* and *errors* parameters." msgstr "" -#: library/argparse.rst:1944 +#: library/argparse.rst:1752 msgid "Argument groups" msgstr "" -#: library/argparse.rst:1948 +#: library/argparse.rst:1757 msgid "" "By default, :class:`ArgumentParser` groups command-line arguments into " "\"positional arguments\" and \"options\" when displaying help messages. When " "there is a better conceptual grouping of arguments than this default one, " -"appropriate groups can be created using the :meth:`add_argument_group` " +"appropriate groups can be created using the :meth:`!add_argument_group` " "method::" msgstr "" -#: library/argparse.rst:1965 +#: library/argparse.rst:1763 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)\n" +">>> group = parser.add_argument_group('group')\n" +">>> group.add_argument('--foo', help='foo help')\n" +">>> group.add_argument('bar', help='bar help')\n" +">>> parser.print_help()\n" +"usage: PROG [--foo FOO] bar\n" +"\n" +"group:\n" +" bar bar help\n" +" --foo FOO foo help" +msgstr "" + +#: library/argparse.rst:1774 msgid "" "The :meth:`add_argument_group` method returns an argument group object which " "has an :meth:`~ArgumentParser.add_argument` method just like a regular :" "class:`ArgumentParser`. When an argument is added to the group, the parser " "treats it just like a normal argument, but displays the argument in a " -"separate group for help messages. The :meth:`add_argument_group` method " +"separate group for help messages. The :meth:`!add_argument_group` method " "accepts *title* and *description* arguments which can be used to customize " "this display::" msgstr "" -#: library/argparse.rst:1991 +#: library/argparse.rst:1782 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)\n" +">>> group1 = parser.add_argument_group('group1', 'group1 description')\n" +">>> group1.add_argument('foo', help='foo help')\n" +">>> group2 = parser.add_argument_group('group2', 'group2 description')\n" +">>> group2.add_argument('--bar', help='bar help')\n" +">>> parser.print_help()\n" +"usage: PROG [--bar BAR] foo\n" +"\n" +"group1:\n" +" group1 description\n" +"\n" +" foo foo help\n" +"\n" +"group2:\n" +" group2 description\n" +"\n" +" --bar BAR bar help" +msgstr "" + +#: library/argparse.rst:1800 +msgid "" +"The optional, keyword-only parameters argument_default_ and " +"conflict_handler_ allow for finer-grained control of the behavior of the " +"argument group. These parameters have the same meaning as in the :class:" +"`ArgumentParser` constructor, but apply specifically to the argument group " +"rather than the entire parser." +msgstr "" + +#: library/argparse.rst:1805 msgid "" "Note that any arguments not in your user-defined groups will end up back in " "the usual \"positional arguments\" and \"optional arguments\" sections." msgstr "" -#: library/argparse.rst:1994 +#: library/argparse.rst:1808 msgid "" "Calling :meth:`add_argument_group` on an argument group is deprecated. This " "feature was never supported and does not always work correctly. The function " @@ -1733,25 +2537,51 @@ msgid "" "future." msgstr "" -#: library/argparse.rst:2002 +#: library/argparse.rst:1816 msgid "Mutual exclusion" msgstr "" -#: library/argparse.rst:2006 +#: library/argparse.rst:1820 msgid "" -"Create a mutually exclusive group. :mod:`argparse` will make sure that only " +"Create a mutually exclusive group. :mod:`!argparse` will make sure that only " "one of the arguments in the mutually exclusive group was present on the " "command line::" msgstr "" -#: library/argparse.rst:2022 +#: library/argparse.rst:1824 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> group = parser.add_mutually_exclusive_group()\n" +">>> group.add_argument('--foo', action='store_true')\n" +">>> group.add_argument('--bar', action='store_false')\n" +">>> parser.parse_args(['--foo'])\n" +"Namespace(bar=True, foo=True)\n" +">>> parser.parse_args(['--bar'])\n" +"Namespace(bar=False, foo=False)\n" +">>> parser.parse_args(['--foo', '--bar'])\n" +"usage: PROG [-h] [--foo | --bar]\n" +"PROG: error: argument --bar: not allowed with argument --foo" +msgstr "" + +#: library/argparse.rst:1836 msgid "" "The :meth:`add_mutually_exclusive_group` method also accepts a *required* " "argument, to indicate that at least one of the mutually exclusive arguments " "is required::" msgstr "" -#: library/argparse.rst:2034 +#: library/argparse.rst:1840 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> group = parser.add_mutually_exclusive_group(required=True)\n" +">>> group.add_argument('--foo', action='store_true')\n" +">>> group.add_argument('--bar', action='store_false')\n" +">>> parser.parse_args([])\n" +"usage: PROG [-h] (--foo | --bar)\n" +"PROG: error: one of the arguments --foo --bar is required" +msgstr "" + +#: library/argparse.rst:1848 msgid "" "Note that currently mutually exclusive argument groups do not support the " "*title* and *description* arguments of :meth:`~ArgumentParser." @@ -1759,7 +2589,27 @@ msgid "" "argument group that has a title and description. For example::" msgstr "" -#: library/argparse.rst:2057 +#: library/argparse.rst:1854 +msgid "" +">>> parser = argparse.ArgumentParser(prog='PROG')\n" +">>> group = parser.add_argument_group('Group title', 'Group description')\n" +">>> exclusive_group = group.add_mutually_exclusive_group(required=True)\n" +">>> exclusive_group.add_argument('--foo', help='foo help')\n" +">>> exclusive_group.add_argument('--bar', help='bar help')\n" +">>> parser.print_help()\n" +"usage: PROG [-h] (--foo FOO | --bar BAR)\n" +"\n" +"options:\n" +" -h, --help show this help message and exit\n" +"\n" +"Group title:\n" +" Group description\n" +"\n" +" --foo FOO foo help\n" +" --bar BAR bar help" +msgstr "" + +#: library/argparse.rst:1871 msgid "" "Calling :meth:`add_argument_group` or :meth:`add_mutually_exclusive_group` " "on a mutually exclusive group is deprecated. These features were never " @@ -1767,11 +2617,11 @@ msgid "" "by accident through inheritance and will be removed in the future." msgstr "" -#: library/argparse.rst:2065 +#: library/argparse.rst:1879 msgid "Parser defaults" msgstr "" -#: library/argparse.rst:2069 +#: library/argparse.rst:1883 msgid "" "Most of the time, the attributes of the object returned by :meth:" "`parse_args` will be fully determined by inspecting the command-line " @@ -1780,72 +2630,98 @@ msgid "" "command line to be added::" msgstr "" -#: library/argparse.rst:2081 +#: library/argparse.rst:1889 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('foo', type=int)\n" +">>> parser.set_defaults(bar=42, baz='badger')\n" +">>> parser.parse_args(['736'])\n" +"Namespace(bar=42, baz='badger', foo=736)" +msgstr "" + +#: library/argparse.rst:1895 msgid "" "Note that parser-level defaults always override argument-level defaults::" msgstr "" -#: library/argparse.rst:2089 +#: library/argparse.rst:1897 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', default='bar')\n" +">>> parser.set_defaults(foo='spam')\n" +">>> parser.parse_args([])\n" +"Namespace(foo='spam')" +msgstr "" + +#: library/argparse.rst:1903 msgid "" "Parser-level defaults can be particularly useful when working with multiple " "parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an " "example of this type." msgstr "" -#: library/argparse.rst:2095 +#: library/argparse.rst:1909 msgid "" "Get the default value for a namespace attribute, as set by either :meth:" "`~ArgumentParser.add_argument` or by :meth:`~ArgumentParser.set_defaults`::" msgstr "" -#: library/argparse.rst:2106 +#: library/argparse.rst:1913 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', default='badger')\n" +">>> parser.get_default('foo')\n" +"'badger'" +msgstr "" + +#: library/argparse.rst:1920 msgid "Printing help" msgstr "" -#: library/argparse.rst:2108 +#: library/argparse.rst:1922 msgid "" "In most typical applications, :meth:`~ArgumentParser.parse_args` will take " "care of formatting and printing any usage or error messages. However, " "several formatting methods are available:" msgstr "" -#: library/argparse.rst:2114 +#: library/argparse.rst:1928 msgid "" "Print a brief description of how the :class:`ArgumentParser` should be " "invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is " "assumed." msgstr "" -#: library/argparse.rst:2120 +#: library/argparse.rst:1934 msgid "" "Print a help message, including the program usage and information about the " "arguments registered with the :class:`ArgumentParser`. If *file* is " "``None``, :data:`sys.stdout` is assumed." msgstr "" -#: library/argparse.rst:2124 +#: library/argparse.rst:1938 msgid "" "There are also variants of these methods that simply return a string instead " "of printing it:" msgstr "" -#: library/argparse.rst:2129 +#: library/argparse.rst:1943 msgid "" "Return a string containing a brief description of how the :class:" "`ArgumentParser` should be invoked on the command line." msgstr "" -#: library/argparse.rst:2134 +#: library/argparse.rst:1948 msgid "" "Return a string containing a help message, including the program usage and " "information about the arguments registered with the :class:`ArgumentParser`." msgstr "" -#: library/argparse.rst:2139 +#: library/argparse.rst:1953 msgid "Partial parsing" msgstr "" -#: library/argparse.rst:2143 +#: library/argparse.rst:1957 msgid "" "Sometimes a script may only parse a few of the command-line arguments, " "passing the remaining arguments on to another script or program. In these " @@ -1856,7 +2732,16 @@ msgid "" "remaining argument strings." msgstr "" -#: library/argparse.rst:2159 +#: library/argparse.rst:1966 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo', action='store_true')\n" +">>> parser.add_argument('bar')\n" +">>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])\n" +"(Namespace(bar='BAR', foo=True), ['--badger', 'spam'])" +msgstr "" + +#: library/argparse.rst:1973 msgid "" ":ref:`Prefix matching ` rules apply to :meth:" "`~ArgumentParser.parse_known_args`. The parser may consume an option even if " @@ -1864,11 +2749,11 @@ msgid "" "remaining arguments list." msgstr "" -#: library/argparse.rst:2166 +#: library/argparse.rst:1980 msgid "Customizing file parsing" msgstr "" -#: library/argparse.rst:2170 +#: library/argparse.rst:1984 msgid "" "Arguments that are read from a file (see the *fromfile_prefix_chars* keyword " "argument to the :class:`ArgumentParser` constructor) are read one argument " @@ -1876,41 +2761,57 @@ msgid "" "reading." msgstr "" -#: library/argparse.rst:2175 +#: library/argparse.rst:1989 msgid "" "This method takes a single argument *arg_line* which is a string read from " "the argument file. It returns a list of arguments parsed from this string. " "The method is called once per line read from the argument file, in order." msgstr "" -#: library/argparse.rst:2179 +#: library/argparse.rst:1993 msgid "" "A useful override of this method is one that treats each space-separated " "word as an argument. The following example demonstrates how to do this::" msgstr "" -#: library/argparse.rst:2188 +#: library/argparse.rst:1996 +msgid "" +"class MyArgumentParser(argparse.ArgumentParser):\n" +" def convert_arg_line_to_args(self, arg_line):\n" +" return arg_line.split()" +msgstr "" + +#: library/argparse.rst:2002 msgid "Exiting methods" msgstr "" -#: library/argparse.rst:2192 +#: library/argparse.rst:2006 msgid "" "This method terminates the program, exiting with the specified *status* and, " -"if given, it prints a *message* before that. The user can override this " -"method to handle these steps differently::" +"if given, it prints a *message* to :data:`sys.stderr` before that. The user " +"can override this method to handle these steps differently::" +msgstr "" + +#: library/argparse.rst:2010 +msgid "" +"class ErrorCatchingArgumentParser(argparse.ArgumentParser):\n" +" def exit(self, status=0, message=None):\n" +" if status:\n" +" raise Exception(f'Exiting because of an error: {message}')\n" +" exit(status)" msgstr "" -#: library/argparse.rst:2204 +#: library/argparse.rst:2018 msgid "" -"This method prints a usage message including the *message* to the standard " -"error and terminates the program with a status code of 2." +"This method prints a usage message, including the *message*, to :data:`sys." +"stderr` and terminates the program with a status code of 2." msgstr "" -#: library/argparse.rst:2209 +#: library/argparse.rst:2023 msgid "Intermixed parsing" msgstr "" -#: library/argparse.rst:2214 +#: library/argparse.rst:2028 msgid "" "A number of Unix commands allow the user to intermix optional arguments with " "positional arguments. The :meth:`~ArgumentParser.parse_intermixed_args` " @@ -1918,15 +2819,15 @@ msgid "" "parsing style." msgstr "" -#: library/argparse.rst:2219 +#: library/argparse.rst:2033 msgid "" -"These parsers do not support all the argparse features, and will raise " -"exceptions if unsupported features are used. In particular, subparsers, and " -"mutually exclusive groups that include both optionals and positionals are " -"not supported." +"These parsers do not support all the :mod:`!argparse` features, and will " +"raise exceptions if unsupported features are used. In particular, " +"subparsers, and mutually exclusive groups that include both optionals and " +"positionals are not supported." msgstr "" -#: library/argparse.rst:2224 +#: library/argparse.rst:2038 msgid "" "The following example shows the difference between :meth:`~ArgumentParser." "parse_known_args` and :meth:`~ArgumentParser.parse_intermixed_args`: the " @@ -1934,7 +2835,19 @@ msgid "" "collects all the positionals into ``rest``. ::" msgstr "" -#: library/argparse.rst:2239 +#: library/argparse.rst:2044 +msgid "" +">>> parser = argparse.ArgumentParser()\n" +">>> parser.add_argument('--foo')\n" +">>> parser.add_argument('cmd')\n" +">>> parser.add_argument('rest', nargs='*', type=int)\n" +">>> parser.parse_known_args('doit 1 --foo bar 2 3'.split())\n" +"(Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3'])\n" +">>> parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split())\n" +"Namespace(cmd='doit', foo='bar', rest=[1, 2, 3])" +msgstr "" + +#: library/argparse.rst:2053 msgid "" ":meth:`~ArgumentParser.parse_known_intermixed_args` returns a two item tuple " "containing the populated namespace and the list of remaining argument " @@ -1942,139 +2855,41 @@ msgid "" "there are any remaining unparsed argument strings." msgstr "" -#: library/argparse.rst:2249 -msgid "Upgrading optparse code" -msgstr "" - -#: library/argparse.rst:2251 -msgid "" -"Originally, the :mod:`argparse` module had attempted to maintain " -"compatibility with :mod:`optparse`. However, :mod:`optparse` was difficult " -"to extend transparently, particularly with the changes required to support " -"the new ``nargs=`` specifiers and better usage messages. When most " -"everything in :mod:`optparse` had either been copy-pasted over or monkey-" -"patched, it no longer seemed practical to try to maintain the backwards " -"compatibility." -msgstr "" - -#: library/argparse.rst:2258 -msgid "" -"The :mod:`argparse` module improves on the standard library :mod:`optparse` " -"module in a number of ways including:" -msgstr "" - -#: library/argparse.rst:2261 -msgid "Handling positional arguments." -msgstr "" - -#: library/argparse.rst:2262 -msgid "Supporting sub-commands." -msgstr "" - -#: library/argparse.rst:2263 -msgid "Allowing alternative option prefixes like ``+`` and ``/``." -msgstr "" - -#: library/argparse.rst:2264 -msgid "Handling zero-or-more and one-or-more style arguments." -msgstr "" - -#: library/argparse.rst:2265 -msgid "Producing more informative usage messages." -msgstr "" - -#: library/argparse.rst:2266 -msgid "Providing a much simpler interface for custom ``type`` and ``action``." -msgstr "" - -#: library/argparse.rst:2268 -msgid "A partial upgrade path from :mod:`optparse` to :mod:`argparse`:" -msgstr "" - -#: library/argparse.rst:2270 -msgid "" -"Replace all :meth:`optparse.OptionParser.add_option` calls with :meth:" -"`ArgumentParser.add_argument` calls." -msgstr "" - -#: library/argparse.rst:2273 -msgid "" -"Replace ``(options, args) = parser.parse_args()`` with ``args = parser." -"parse_args()`` and add additional :meth:`ArgumentParser.add_argument` calls " -"for the positional arguments. Keep in mind that what was previously called " -"``options``, now in the :mod:`argparse` context is called ``args``." -msgstr "" - -#: library/argparse.rst:2278 -msgid "" -"Replace :meth:`optparse.OptionParser.disable_interspersed_args` by using :" -"meth:`~ArgumentParser.parse_intermixed_args` instead of :meth:" -"`~ArgumentParser.parse_args`." -msgstr "" - -#: library/argparse.rst:2282 -msgid "" -"Replace callback actions and the ``callback_*`` keyword arguments with " -"``type`` or ``action`` arguments." -msgstr "" - -#: library/argparse.rst:2285 -msgid "" -"Replace string names for ``type`` keyword arguments with the corresponding " -"type objects (e.g. int, float, complex, etc)." -msgstr "" - -#: library/argparse.rst:2288 -msgid "" -"Replace :class:`optparse.Values` with :class:`Namespace` and :exc:`optparse." -"OptionError` and :exc:`optparse.OptionValueError` with :exc:`ArgumentError`." -msgstr "" - -#: library/argparse.rst:2292 -msgid "" -"Replace strings with implicit arguments such as ``%default`` or ``%prog`` " -"with the standard Python syntax to use dictionaries to format strings, that " -"is, ``%(default)s`` and ``%(prog)s``." -msgstr "" - -#: library/argparse.rst:2296 -msgid "" -"Replace the OptionParser constructor ``version`` argument with a call to " -"``parser.add_argument('--version', action='version', version='')``." -msgstr "" - -#: library/argparse.rst:2300 +#: library/argparse.rst:2062 msgid "Exceptions" msgstr "" -#: library/argparse.rst:2304 +#: library/argparse.rst:2066 msgid "An error from creating or using an argument (optional or positional)." msgstr "" -#: library/argparse.rst:2306 +#: library/argparse.rst:2068 msgid "" "The string value of this exception is the message, augmented with " "information about the argument that caused it." msgstr "" -#: library/argparse.rst:2311 +#: library/argparse.rst:2073 msgid "" "Raised when something goes wrong converting a command line string to a type." msgstr "" -#: library/argparse.rst:980 +#: library/argparse.rst:2077 +msgid "Guides and Tutorials" +msgstr "" + +#: library/argparse.rst:800 msgid "? (question mark)" msgstr "" -#: library/argparse.rst:1014 library/argparse.rst:1028 +#: library/argparse.rst:834 library/argparse.rst:848 msgid "in argparse module" msgstr "" -#: library/argparse.rst:1014 +#: library/argparse.rst:834 msgid "* (asterisk)" msgstr "" -#: library/argparse.rst:1028 +#: library/argparse.rst:848 msgid "+ (plus)" msgstr "" diff --git a/library/array.po b/library/array.po index 0722a3441..b6a014d68 100644 --- a/library/array.po +++ b/library/array.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -246,7 +246,8 @@ msgstr "" #: library/array.rst:96 msgid "" -"Raises an auditing event array.__new__ with arguments typecode, initializer." +"Raises an :ref:`auditing event ` ``array.__new__`` with arguments " +"``typecode``, ``initializer``." msgstr "" #: library/array.rst:101 @@ -406,6 +407,14 @@ msgid "" "defined if it contains corresponding floating-point values. Examples::" msgstr "" +#: library/array.rst:259 +msgid "" +"array('l')\n" +"array('u', 'hello \\u2641')\n" +"array('l', [1, 2, 3, 4, 5])\n" +"array('d', [1.0, 2.0, 3.14, -inf, nan])" +msgstr "" + #: library/array.rst:267 msgid "Module :mod:`struct`" msgstr "" diff --git a/library/ast.po b/library/ast.po index 9f2b2cef3..82a8f5b2b 100644 --- a/library/ast.po +++ b/library/ast.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -50,6 +50,180 @@ msgstr "" msgid "The abstract grammar is currently defined as follows:" msgstr "" +#: library/ast.rst:37 +msgid "" +"-- ASDL's 4 builtin types are:\n" +"-- identifier, int, string, constant\n" +"\n" +"module Python\n" +"{\n" +" mod = Module(stmt* body, type_ignore* type_ignores)\n" +" | Interactive(stmt* body)\n" +" | Expression(expr body)\n" +" | FunctionType(expr* argtypes, expr returns)\n" +"\n" +" stmt = FunctionDef(identifier name, arguments args,\n" +" stmt* body, expr* decorator_list, expr? returns,\n" +" string? type_comment, type_param* type_params)\n" +" | AsyncFunctionDef(identifier name, arguments args,\n" +" stmt* body, expr* decorator_list, expr? " +"returns,\n" +" string? type_comment, type_param* type_params)\n" +"\n" +" | ClassDef(identifier name,\n" +" expr* bases,\n" +" keyword* keywords,\n" +" stmt* body,\n" +" expr* decorator_list,\n" +" type_param* type_params)\n" +" | Return(expr? value)\n" +"\n" +" | Delete(expr* targets)\n" +" | Assign(expr* targets, expr value, string? type_comment)\n" +" | TypeAlias(expr name, type_param* type_params, expr value)\n" +" | AugAssign(expr target, operator op, expr value)\n" +" -- 'simple' indicates that we annotate simple name without parens\n" +" | AnnAssign(expr target, expr annotation, expr? value, int " +"simple)\n" +"\n" +" -- use 'orelse' because else is a keyword in target languages\n" +" | For(expr target, expr iter, stmt* body, stmt* orelse, string? " +"type_comment)\n" +" | AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, " +"string? type_comment)\n" +" | While(expr test, stmt* body, stmt* orelse)\n" +" | If(expr test, stmt* body, stmt* orelse)\n" +" | With(withitem* items, stmt* body, string? type_comment)\n" +" | AsyncWith(withitem* items, stmt* body, string? type_comment)\n" +"\n" +" | Match(expr subject, match_case* cases)\n" +"\n" +" | Raise(expr? exc, expr? cause)\n" +" | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* " +"finalbody)\n" +" | TryStar(stmt* body, excepthandler* handlers, stmt* orelse, stmt* " +"finalbody)\n" +" | Assert(expr test, expr? msg)\n" +"\n" +" | Import(alias* names)\n" +" | ImportFrom(identifier? module, alias* names, int? level)\n" +"\n" +" | Global(identifier* names)\n" +" | Nonlocal(identifier* names)\n" +" | Expr(expr value)\n" +" | Pass | Break | Continue\n" +"\n" +" -- col_offset is the byte offset in the utf8 string the parser " +"uses\n" +" attributes (int lineno, int col_offset, int? end_lineno, int? " +"end_col_offset)\n" +"\n" +" -- BoolOp() can use left & right?\n" +" expr = BoolOp(boolop op, expr* values)\n" +" | NamedExpr(expr target, expr value)\n" +" | BinOp(expr left, operator op, expr right)\n" +" | UnaryOp(unaryop op, expr operand)\n" +" | Lambda(arguments args, expr body)\n" +" | IfExp(expr test, expr body, expr orelse)\n" +" | Dict(expr* keys, expr* values)\n" +" | Set(expr* elts)\n" +" | ListComp(expr elt, comprehension* generators)\n" +" | SetComp(expr elt, comprehension* generators)\n" +" | DictComp(expr key, expr value, comprehension* generators)\n" +" | GeneratorExp(expr elt, comprehension* generators)\n" +" -- the grammar constrains where yield expressions can occur\n" +" | Await(expr value)\n" +" | Yield(expr? value)\n" +" | YieldFrom(expr value)\n" +" -- need sequences for compare to distinguish between\n" +" -- x < 4 < 3 and (x < 4) < 3\n" +" | Compare(expr left, cmpop* ops, expr* comparators)\n" +" | Call(expr func, expr* args, keyword* keywords)\n" +" | FormattedValue(expr value, int conversion, expr? format_spec)\n" +" | JoinedStr(expr* values)\n" +" | Constant(constant value, string? kind)\n" +"\n" +" -- the following expression can appear in assignment context\n" +" | Attribute(expr value, identifier attr, expr_context ctx)\n" +" | Subscript(expr value, expr slice, expr_context ctx)\n" +" | Starred(expr value, expr_context ctx)\n" +" | Name(identifier id, expr_context ctx)\n" +" | List(expr* elts, expr_context ctx)\n" +" | Tuple(expr* elts, expr_context ctx)\n" +"\n" +" -- can appear only in Subscript\n" +" | Slice(expr? lower, expr? upper, expr? step)\n" +"\n" +" -- col_offset is the byte offset in the utf8 string the parser " +"uses\n" +" attributes (int lineno, int col_offset, int? end_lineno, int? " +"end_col_offset)\n" +"\n" +" expr_context = Load | Store | Del\n" +"\n" +" boolop = And | Or\n" +"\n" +" operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift\n" +" | RShift | BitOr | BitXor | BitAnd | FloorDiv\n" +"\n" +" unaryop = Invert | Not | UAdd | USub\n" +"\n" +" cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn\n" +"\n" +" comprehension = (expr target, expr iter, expr* ifs, int is_async)\n" +"\n" +" excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)\n" +" attributes (int lineno, int col_offset, int? end_lineno, " +"int? end_col_offset)\n" +"\n" +" arguments = (arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs,\n" +" expr* kw_defaults, arg? kwarg, expr* defaults)\n" +"\n" +" arg = (identifier arg, expr? annotation, string? type_comment)\n" +" attributes (int lineno, int col_offset, int? end_lineno, int? " +"end_col_offset)\n" +"\n" +" -- keyword arguments supplied to call (NULL identifier for **kwargs)\n" +" keyword = (identifier? arg, expr value)\n" +" attributes (int lineno, int col_offset, int? end_lineno, int? " +"end_col_offset)\n" +"\n" +" -- import name with optional 'as' alias.\n" +" alias = (identifier name, identifier? asname)\n" +" attributes (int lineno, int col_offset, int? end_lineno, int? " +"end_col_offset)\n" +"\n" +" withitem = (expr context_expr, expr? optional_vars)\n" +"\n" +" match_case = (pattern pattern, expr? guard, stmt* body)\n" +"\n" +" pattern = MatchValue(expr value)\n" +" | MatchSingleton(constant value)\n" +" | MatchSequence(pattern* patterns)\n" +" | MatchMapping(expr* keys, pattern* patterns, identifier? rest)\n" +" | MatchClass(expr cls, pattern* patterns, identifier* kwd_attrs, " +"pattern* kwd_patterns)\n" +"\n" +" | MatchStar(identifier? name)\n" +" -- The optional \"rest\" MatchMapping parameter handles " +"capturing extra mapping keys\n" +"\n" +" | MatchAs(pattern? pattern, identifier? name)\n" +" | MatchOr(pattern* patterns)\n" +"\n" +" attributes (int lineno, int col_offset, int end_lineno, int " +"end_col_offset)\n" +"\n" +" type_ignore = TypeIgnore(int lineno, string tag)\n" +"\n" +" type_param = TypeVar(identifier name, expr? bound)\n" +" | ParamSpec(identifier name)\n" +" | TypeVarTuple(identifier name)\n" +" attributes (int lineno, int col_offset, int end_lineno, int " +"end_col_offset)\n" +"}\n" +msgstr "" + #: library/ast.rst:42 msgid "Node classes" msgstr "" @@ -138,10 +312,28 @@ msgid "" "use ::" msgstr "" +#: library/ast.rst:106 +msgid "" +"node = ast.UnaryOp()\n" +"node.op = ast.USub()\n" +"node.operand = ast.Constant()\n" +"node.operand.value = 5\n" +"node.operand.lineno = 0\n" +"node.operand.col_offset = 0\n" +"node.lineno = 0\n" +"node.col_offset = 0" +msgstr "" + #: library/ast.rst:115 msgid "or the more compact ::" msgstr "" +#: library/ast.rst:117 +msgid "" +"node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),\n" +" lineno=0, col_offset=0)" +msgstr "" + #: library/ast.rst:122 msgid "Class :class:`ast.Constant` is now used for all constants." msgstr "" @@ -185,13 +377,25 @@ msgid "" msgstr "" #: library/ast.rst:160 -msgid "*body* is a :class:`list` of the module's :ref:`ast-statements`." +msgid "``body`` is a :class:`list` of the module's :ref:`ast-statements`." msgstr "" #: library/ast.rst:162 msgid "" -"*type_ignores* is a :class:`list` of the module's type ignore comments; see :" -"func:`ast.parse` for more details." +"``type_ignores`` is a :class:`list` of the module's type ignore comments; " +"see :func:`ast.parse` for more details." +msgstr "" + +#: library/ast.rst:165 +msgid "" +">>> print(ast.dump(ast.parse('x = 1'), indent=4))\n" +"Module(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Name(id='x', ctx=Store())],\n" +" value=Constant(value=1))],\n" +" type_ignores=[])" msgstr "" #: library/ast.rst:179 @@ -202,10 +406,17 @@ msgstr "" #: library/ast.rst:182 msgid "" -"*body* is a single node, one of the :ref:`expression types `." msgstr "" +#: library/ast.rst:255 +msgid "" +">>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Constant(value=123))" +msgstr "" + #: library/ast.rst:194 msgid "" "A single :ref:`interactive input `, like in :ref:`tut-interac`. " @@ -213,7 +424,22 @@ msgid "" msgstr "" #: library/ast.rst:197 -msgid "*body* is a :class:`list` of :ref:`statement nodes `." +msgid "``body`` is a :class:`list` of :ref:`statement nodes `." +msgstr "" + +#: library/ast.rst:199 +msgid "" +">>> print(ast.dump(ast.parse('x = 1; y = 2', mode='single'), indent=4))\n" +"Interactive(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Name(id='x', ctx=Store())],\n" +" value=Constant(value=1)),\n" +" Assign(\n" +" targets=[\n" +" Name(id='y', ctx=Store())],\n" +" value=Constant(value=2))])" msgstr "" #: library/ast.rst:216 @@ -227,13 +453,34 @@ msgstr "" msgid "Such type comments would look like this::" msgstr "" +#: library/ast.rst:222 +msgid "" +"def sum_two_number(a, b):\n" +" # type: (int, int) -> int\n" +" return a + b" +msgstr "" + #: library/ast.rst:226 msgid "" -"*argtypes* is a :class:`list` of :ref:`expression nodes `." +"``argtypes`` is a :class:`list` of :ref:`expression nodes `." msgstr "" #: library/ast.rst:228 -msgid "*returns* is a single :ref:`expression node `." +msgid "``returns`` is a single :ref:`expression node `." +msgstr "" + +#: library/ast.rst:230 +msgid "" +">>> print(ast.dump(ast.parse('(int, str) -> List[int]', mode='func_type'), " +"indent=4))\n" +"FunctionType(\n" +" argtypes=[\n" +" Name(id='int', ctx=Load()),\n" +" Name(id='str', ctx=Load())],\n" +" returns=Subscript(\n" +" value=Name(id='List', ctx=Load()),\n" +" slice=Name(id='int', ctx=Load()),\n" +" ctx=Load()))" msgstr "" #: library/ast.rst:246 @@ -295,6 +542,30 @@ msgid "" "`Constant` nodes." msgstr "" +#: library/ast.rst:287 +msgid "" +">>> print(ast.dump(ast.parse('f\"sin({a}) is {sin(a):.3}\"', mode='eval'), " +"indent=4))\n" +"Expression(\n" +" body=JoinedStr(\n" +" values=[\n" +" Constant(value='sin('),\n" +" FormattedValue(\n" +" value=Name(id='a', ctx=Load()),\n" +" conversion=-1),\n" +" Constant(value=') is '),\n" +" FormattedValue(\n" +" value=Call(\n" +" func=Name(id='sin', ctx=Load()),\n" +" args=[\n" +" Name(id='a', ctx=Load())],\n" +" keywords=[]),\n" +" conversion=-1,\n" +" format_spec=JoinedStr(\n" +" values=[\n" +" Constant(value='.3')]))]))" +msgstr "" + #: library/ast.rst:313 msgid "" "A list or tuple. ``elts`` holds a list of nodes representing the elements. " @@ -302,10 +573,41 @@ msgid "" "``(x,y)=something``), and :class:`Load` otherwise." msgstr "" +#: library/ast.rst:317 +msgid "" +">>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4))\n" +"Expression(\n" +" body=List(\n" +" elts=[\n" +" Constant(value=1),\n" +" Constant(value=2),\n" +" Constant(value=3)],\n" +" ctx=Load()))\n" +">>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Tuple(\n" +" elts=[\n" +" Constant(value=1),\n" +" Constant(value=2),\n" +" Constant(value=3)],\n" +" ctx=Load()))" +msgstr "" + #: library/ast.rst:339 msgid "A set. ``elts`` holds a list of nodes representing the set's elements." msgstr "" +#: library/ast.rst:341 +msgid "" +">>> print(ast.dump(ast.parse('{1, 2, 3}', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Set(\n" +" elts=[\n" +" Constant(value=1),\n" +" Constant(value=2),\n" +" Constant(value=3)]))" +msgstr "" + #: library/ast.rst:354 msgid "" "A dictionary. ``keys`` and ``values`` hold lists of nodes representing the " @@ -320,6 +622,19 @@ msgid "" "corresponding position in ``keys``." msgstr "" +#: library/ast.rst:362 +msgid "" +">>> print(ast.dump(ast.parse('{\"a\":1, **d}', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Dict(\n" +" keys=[\n" +" Constant(value='a'),\n" +" None],\n" +" values=[\n" +" Constant(value=1),\n" +" Name(id='d', ctx=Load())]))" +msgstr "" + #: library/ast.rst:376 msgid "Variables" msgstr "" @@ -337,6 +652,33 @@ msgid "" "distinguish these cases." msgstr "" +#: library/ast.rst:392 +msgid "" +">>> print(ast.dump(ast.parse('a'), indent=4))\n" +"Module(\n" +" body=[\n" +" Expr(\n" +" value=Name(id='a', ctx=Load()))],\n" +" type_ignores=[])\n" +"\n" +">>> print(ast.dump(ast.parse('a = 1'), indent=4))\n" +"Module(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Name(id='a', ctx=Store())],\n" +" value=Constant(value=1))],\n" +" type_ignores=[])\n" +"\n" +">>> print(ast.dump(ast.parse('del a'), indent=4))\n" +"Module(\n" +" body=[\n" +" Delete(\n" +" targets=[\n" +" Name(id='a', ctx=Del())])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:421 msgid "" "A ``*var`` variable reference. ``value`` holds the variable, typically a :" @@ -344,6 +686,24 @@ msgid "" "with ``*args``." msgstr "" +#: library/ast.rst:425 +msgid "" +">>> print(ast.dump(ast.parse('a, *b = it'), indent=4))\n" +"Module(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Tuple(\n" +" elts=[\n" +" Name(id='a', ctx=Store()),\n" +" Starred(\n" +" value=Name(id='b', ctx=Store()),\n" +" ctx=Store())],\n" +" ctx=Store())],\n" +" value=Name(id='it', ctx=Load()))],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:446 msgid "Expressions" msgstr "" @@ -357,6 +717,18 @@ msgid "" "`YieldFrom` node." msgstr "" +#: library/ast.rst:455 +msgid "" +">>> print(ast.dump(ast.parse('-a'), indent=4))\n" +"Module(\n" +" body=[\n" +" Expr(\n" +" value=UnaryOp(\n" +" op=USub(),\n" +" operand=Name(id='a', ctx=Load())))],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:469 msgid "" "A unary operation. ``op`` is the operator, and ``operand`` any expression " @@ -369,12 +741,31 @@ msgid "" "is the ``~`` operator." msgstr "" +#: library/ast.rst:481 +msgid "" +">>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))\n" +"Expression(\n" +" body=UnaryOp(\n" +" op=Not(),\n" +" operand=Name(id='x', ctx=Load())))" +msgstr "" + #: library/ast.rst:492 msgid "" "A binary operation (like addition or division). ``op`` is the operator, and " "``left`` and ``right`` are any expression nodes." msgstr "" +#: library/ast.rst:495 +msgid "" +">>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4))\n" +"Expression(\n" +" body=BinOp(\n" +" left=Name(id='x', ctx=Load()),\n" +" op=Add(),\n" +" right=Name(id='y', ctx=Load())))" +msgstr "" + #: library/ast.rst:519 msgid "Binary operator tokens." msgstr "" @@ -391,6 +782,17 @@ msgstr "" msgid "This doesn't include ``not``, which is a :class:`UnaryOp`." msgstr "" +#: library/ast.rst:531 +msgid "" +">>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4))\n" +"Expression(\n" +" body=BoolOp(\n" +" op=Or(),\n" +" values=[\n" +" Name(id='x', ctx=Load()),\n" +" Name(id='y', ctx=Load())]))" +msgstr "" + #: library/ast.rst:545 msgid "Boolean operator tokens." msgstr "" @@ -402,6 +804,20 @@ msgid "" "values after the first element in the comparison." msgstr "" +#: library/ast.rst:554 +msgid "" +">>> print(ast.dump(ast.parse('1 <= a < 10', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Compare(\n" +" left=Constant(value=1),\n" +" ops=[\n" +" LtE(),\n" +" Lt()],\n" +" comparators=[\n" +" Name(id='a', ctx=Load()),\n" +" Constant(value=10)]))" +msgstr "" + #: library/ast.rst:579 msgid "Comparison operator tokens." msgstr "" @@ -428,6 +844,26 @@ msgid "" "they can be empty lists." msgstr "" +#: library/ast.rst:594 +msgid "" +">>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), " +"indent=4))\n" +"Expression(\n" +" body=Call(\n" +" func=Name(id='func', ctx=Load()),\n" +" args=[\n" +" Name(id='a', ctx=Load()),\n" +" Starred(\n" +" value=Name(id='d', ctx=Load()),\n" +" ctx=Load())],\n" +" keywords=[\n" +" keyword(\n" +" arg='b',\n" +" value=Name(id='c', ctx=Load())),\n" +" keyword(\n" +" value=Name(id='e', ctx=Load()))]))" +msgstr "" + #: library/ast.rst:615 msgid "" "A keyword argument to a function call or class definition. ``arg`` is a raw " @@ -440,6 +876,16 @@ msgid "" "in the following example, all three are :class:`Name` nodes." msgstr "" +#: library/ast.rst:624 +msgid "" +">>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4))\n" +"Expression(\n" +" body=IfExp(\n" +" test=Name(id='b', ctx=Load()),\n" +" body=Name(id='a', ctx=Load()),\n" +" orelse=Name(id='c', ctx=Load())))" +msgstr "" + #: library/ast.rst:636 msgid "" "Attribute access, e.g. ``d.keys``. ``value`` is a node, typically a :class:" @@ -448,6 +894,16 @@ msgid "" "the attribute is acted on." msgstr "" +#: library/ast.rst:641 +msgid "" +">>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Attribute(\n" +" value=Name(id='snake', ctx=Load()),\n" +" attr='colour',\n" +" ctx=Load()))" +msgstr "" + #: library/ast.rst:653 msgid "" "A named expression. This AST node is produced by the assignment expressions " @@ -456,6 +912,15 @@ msgid "" "case both ``target`` and ``value`` must be single nodes." msgstr "" +#: library/ast.rst:658 +msgid "" +">>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4))\n" +"Expression(\n" +" body=NamedExpr(\n" +" target=Name(id='x', ctx=Store()),\n" +" value=Constant(value=4)))" +msgstr "" + #: library/ast.rst:669 msgid "Subscripting" msgstr "" @@ -468,6 +933,22 @@ msgid "" "`Store` or :class:`Del` according to the action performed with the subscript." msgstr "" +#: library/ast.rst:679 +msgid "" +">>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Subscript(\n" +" value=Name(id='l', ctx=Load()),\n" +" slice=Tuple(\n" +" elts=[\n" +" Slice(\n" +" lower=Constant(value=1),\n" +" upper=Constant(value=2)),\n" +" Constant(value=3)],\n" +" ctx=Load()),\n" +" ctx=Load()))" +msgstr "" + #: library/ast.rst:697 msgid "" "Regular slicing (on the form ``lower:upper`` or ``lower:upper:step``). Can " @@ -475,6 +956,18 @@ msgid "" "or as an element of :class:`Tuple`." msgstr "" +#: library/ast.rst:701 +msgid "" +">>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4))\n" +"Expression(\n" +" body=Subscript(\n" +" value=Name(id='l', ctx=Load()),\n" +" slice=Slice(\n" +" lower=Constant(value=1),\n" +" upper=Constant(value=2)),\n" +" ctx=Load()))" +msgstr "" + #: library/ast.rst:714 msgid "Comprehensions" msgstr "" @@ -490,6 +983,47 @@ msgstr "" msgid "``generators`` is a list of :class:`comprehension` nodes." msgstr "" +#: library/ast.rst:727 +msgid "" +">>> print(ast.dump(ast.parse('[x for x in numbers]', mode='eval'), " +"indent=4))\n" +"Expression(\n" +" body=ListComp(\n" +" elt=Name(id='x', ctx=Load()),\n" +" generators=[\n" +" comprehension(\n" +" target=Name(id='x', ctx=Store()),\n" +" iter=Name(id='numbers', ctx=Load()),\n" +" ifs=[],\n" +" is_async=0)]))\n" +">>> print(ast.dump(ast.parse('{x: x**2 for x in numbers}', mode='eval'), " +"indent=4))\n" +"Expression(\n" +" body=DictComp(\n" +" key=Name(id='x', ctx=Load()),\n" +" value=BinOp(\n" +" left=Name(id='x', ctx=Load()),\n" +" op=Pow(),\n" +" right=Constant(value=2)),\n" +" generators=[\n" +" comprehension(\n" +" target=Name(id='x', ctx=Store()),\n" +" iter=Name(id='numbers', ctx=Load()),\n" +" ifs=[],\n" +" is_async=0)]))\n" +">>> print(ast.dump(ast.parse('{x for x in numbers}', mode='eval'), " +"indent=4))\n" +"Expression(\n" +" body=SetComp(\n" +" elt=Name(id='x', ctx=Load()),\n" +" generators=[\n" +" comprehension(\n" +" target=Name(id='x', ctx=Store()),\n" +" iter=Name(id='numbers', ctx=Load()),\n" +" ifs=[],\n" +" is_async=0)]))" +msgstr "" + #: library/ast.rst:767 msgid "" "One ``for`` clause in a comprehension. ``target`` is the reference to use " @@ -504,6 +1038,71 @@ msgid "" "for`` instead of ``for``). The value is an integer (0 or 1)." msgstr "" +#: library/ast.rst:775 +msgid "" +">>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', " +"mode='eval'),\n" +"... indent=4)) # Multiple comprehensions in one.\n" +"Expression(\n" +" body=ListComp(\n" +" elt=Call(\n" +" func=Name(id='ord', ctx=Load()),\n" +" args=[\n" +" Name(id='c', ctx=Load())],\n" +" keywords=[]),\n" +" generators=[\n" +" comprehension(\n" +" target=Name(id='line', ctx=Store()),\n" +" iter=Name(id='file', ctx=Load()),\n" +" ifs=[],\n" +" is_async=0),\n" +" comprehension(\n" +" target=Name(id='c', ctx=Store()),\n" +" iter=Name(id='line', ctx=Load()),\n" +" ifs=[],\n" +" is_async=0)]))\n" +"\n" +">>> print(ast.dump(ast.parse('(n**2 for n in it if n>5 if n<10)', " +"mode='eval'),\n" +"... indent=4)) # generator comprehension\n" +"Expression(\n" +" body=GeneratorExp(\n" +" elt=BinOp(\n" +" left=Name(id='n', ctx=Load()),\n" +" op=Pow(),\n" +" right=Constant(value=2)),\n" +" generators=[\n" +" comprehension(\n" +" target=Name(id='n', ctx=Store()),\n" +" iter=Name(id='it', ctx=Load()),\n" +" ifs=[\n" +" Compare(\n" +" left=Name(id='n', ctx=Load()),\n" +" ops=[\n" +" Gt()],\n" +" comparators=[\n" +" Constant(value=5)]),\n" +" Compare(\n" +" left=Name(id='n', ctx=Load()),\n" +" ops=[\n" +" Lt()],\n" +" comparators=[\n" +" Constant(value=10)])],\n" +" is_async=0)]))\n" +"\n" +">>> print(ast.dump(ast.parse('[i async for i in soc]', mode='eval'),\n" +"... indent=4)) # Async comprehension\n" +"Expression(\n" +" body=ListComp(\n" +" elt=Name(id='i', ctx=Load()),\n" +" generators=[\n" +" comprehension(\n" +" target=Name(id='i', ctx=Store()),\n" +" iter=Name(id='soc', ctx=Load()),\n" +" ifs=[],\n" +" is_async=1)]))" +msgstr "" + #: library/ast.rst:841 msgid "Statements" msgstr "" @@ -526,6 +1125,32 @@ msgid "" "``type_comment`` is an optional string with the type annotation as a comment." msgstr "" +#: library/ast.rst:855 +msgid "" +">>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Multiple assignment\n" +"Module(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Name(id='a', ctx=Store()),\n" +" Name(id='b', ctx=Store())],\n" +" value=Constant(value=1))],\n" +" type_ignores=[])\n" +"\n" +">>> print(ast.dump(ast.parse('a,b = c'), indent=4)) # Unpacking\n" +"Module(\n" +" body=[\n" +" Assign(\n" +" targets=[\n" +" Tuple(\n" +" elts=[\n" +" Name(id='a', ctx=Store()),\n" +" Name(id='b', ctx=Store())],\n" +" ctx=Store())],\n" +" value=Name(id='c', ctx=Load()))],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:883 msgid "" "An assignment with a type annotation. ``target`` is a single node and can be " @@ -540,7 +1165,55 @@ msgid "" "(indicating a \"simple\" target). A \"simple\" target consists solely of a :" "class:`Name` node that does not appear between parentheses; all other " "targets are considered complex. Only simple targets appear in the :attr:" -"`__annotations__` dictionary of modules and classes." +"`~object.__annotations__` dictionary of modules and classes." +msgstr "" + +#: library/ast.rst:894 +msgid "" +">>> print(ast.dump(ast.parse('c: int'), indent=4))\n" +"Module(\n" +" body=[\n" +" AnnAssign(\n" +" target=Name(id='c', ctx=Store()),\n" +" annotation=Name(id='int', ctx=Load()),\n" +" simple=1)],\n" +" type_ignores=[])\n" +"\n" +">>> print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Annotation with " +"parenthesis\n" +"Module(\n" +" body=[\n" +" AnnAssign(\n" +" target=Name(id='a', ctx=Store()),\n" +" annotation=Name(id='int', ctx=Load()),\n" +" value=Constant(value=1),\n" +" simple=0)],\n" +" type_ignores=[])\n" +"\n" +">>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation\n" +"Module(\n" +" body=[\n" +" AnnAssign(\n" +" target=Attribute(\n" +" value=Name(id='a', ctx=Load()),\n" +" attr='b',\n" +" ctx=Store()),\n" +" annotation=Name(id='int', ctx=Load()),\n" +" simple=0)],\n" +" type_ignores=[])\n" +"\n" +">>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript " +"annotation\n" +"Module(\n" +" body=[\n" +" AnnAssign(\n" +" target=Subscript(\n" +" value=Name(id='a', ctx=Load()),\n" +" slice=Constant(value=1),\n" +" ctx=Store()),\n" +" annotation=Name(id='int', ctx=Load()),\n" +" simple=0)],\n" +" type_ignores=[])" msgstr "" #: library/ast.rst:942 @@ -557,6 +1230,18 @@ msgid "" "unlike the targets of :class:`Assign`." msgstr "" +#: library/ast.rst:950 +msgid "" +">>> print(ast.dump(ast.parse('x += 2'), indent=4))\n" +"Module(\n" +" body=[\n" +" AugAssign(\n" +" target=Name(id='x', ctx=Store()),\n" +" op=Add(),\n" +" value=Constant(value=2))],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:964 msgid "" "A ``raise`` statement. ``exc`` is the exception object to be raised, " @@ -564,22 +1249,66 @@ msgid "" "``raise``. ``cause`` is the optional part for ``y`` in ``raise x from y``." msgstr "" +#: library/ast.rst:968 +msgid "" +">>> print(ast.dump(ast.parse('raise x from y'), indent=4))\n" +"Module(\n" +" body=[\n" +" Raise(\n" +" exc=Name(id='x', ctx=Load()),\n" +" cause=Name(id='y', ctx=Load()))],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:981 msgid "" "An assertion. ``test`` holds the condition, such as a :class:`Compare` node. " "``msg`` holds the failure message." msgstr "" +#: library/ast.rst:984 +msgid "" +">>> print(ast.dump(ast.parse('assert x,y'), indent=4))\n" +"Module(\n" +" body=[\n" +" Assert(\n" +" test=Name(id='x', ctx=Load()),\n" +" msg=Name(id='y', ctx=Load()))],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:997 msgid "" "Represents a ``del`` statement. ``targets`` is a list of nodes, such as :" "class:`Name`, :class:`Attribute` or :class:`Subscript` nodes." msgstr "" +#: library/ast.rst:1000 +msgid "" +">>> print(ast.dump(ast.parse('del x,y,z'), indent=4))\n" +"Module(\n" +" body=[\n" +" Delete(\n" +" targets=[\n" +" Name(id='x', ctx=Del()),\n" +" Name(id='y', ctx=Del()),\n" +" Name(id='z', ctx=Del())])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1015 msgid "A ``pass`` statement." msgstr "" +#: library/ast.rst:1017 +msgid "" +">>> print(ast.dump(ast.parse('pass'), indent=4))\n" +"Module(\n" +" body=[\n" +" Pass()],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1028 msgid "" "A :ref:`type alias ` created through the :keyword:`type` " @@ -588,6 +1317,18 @@ msgid "" "type alias." msgstr "" +#: library/ast.rst:1033 +msgid "" +">>> print(ast.dump(ast.parse('type Alias = int'), indent=4))\n" +"Module(\n" +" body=[\n" +" TypeAlias(\n" +" name=Name(id='Alias', ctx=Store()),\n" +" type_params=[],\n" +" value=Name(id='int', ctx=Load()))],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1046 msgid "" "Other statements which are only applicable inside functions or loops are " @@ -602,6 +1343,19 @@ msgstr "" msgid "An import statement. ``names`` is a list of :class:`alias` nodes." msgstr "" +#: library/ast.rst:1056 +msgid "" +">>> print(ast.dump(ast.parse('import x,y,z'), indent=4))\n" +"Module(\n" +" body=[\n" +" Import(\n" +" names=[\n" +" alias(name='x'),\n" +" alias(name='y'),\n" +" alias(name='z')])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1071 msgid "" "Represents ``from x import y``. ``module`` is a raw string of the 'from' " @@ -610,12 +1364,41 @@ msgid "" "import (0 means absolute import)." msgstr "" +#: library/ast.rst:1076 +msgid "" +">>> print(ast.dump(ast.parse('from y import x,y,z'), indent=4))\n" +"Module(\n" +" body=[\n" +" ImportFrom(\n" +" module='y',\n" +" names=[\n" +" alias(name='x'),\n" +" alias(name='y'),\n" +" alias(name='z')],\n" +" level=0)],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1093 msgid "" "Both parameters are raw strings of the names. ``asname`` can be ``None`` if " "the regular name is to be used." msgstr "" +#: library/ast.rst:1096 +msgid "" +">>> print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4))\n" +"Module(\n" +" body=[\n" +" ImportFrom(\n" +" module='foo.bar',\n" +" names=[\n" +" alias(name='a', asname='b'),\n" +" alias(name='c')],\n" +" level=2)],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1110 msgid "Control flow" msgstr "" @@ -639,6 +1422,35 @@ msgid "" "previous one." msgstr "" +#: library/ast.rst:1125 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... if x:\n" +"... ...\n" +"... elif y:\n" +"... ...\n" +"... else:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" If(\n" +" test=Name(id='x', ctx=Load()),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" orelse=[\n" +" If(\n" +" test=Name(id='y', ctx=Load()),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" orelse=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1156 msgid "" "A ``for`` loop. ``target`` holds the variable(s) the loop assigns to, as a " @@ -649,22 +1461,137 @@ msgid "" "via a ``break`` statement." msgstr "" +#: library/ast.rst:1167 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... for x in y:\n" +"... ...\n" +"... else:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" For(\n" +" target=Name(id='x', ctx=Store()),\n" +" iter=Name(id='y', ctx=Load()),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" orelse=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1191 msgid "" "A ``while`` loop. ``test`` holds the condition, such as a :class:`Compare` " "node." msgstr "" +#: library/ast.rst:1194 +msgid "" +">> print(ast.dump(ast.parse(\"\"\"\n" +"... while x:\n" +"... ...\n" +"... else:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" While(\n" +" test=Name(id='x', ctx=Load()),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" orelse=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1218 msgid "The ``break`` and ``continue`` statements." msgstr "" +#: library/ast.rst:1220 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... for a in b:\n" +"... if a > 5:\n" +"... break\n" +"... else:\n" +"... continue\n" +"...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" For(\n" +" target=Name(id='a', ctx=Store()),\n" +" iter=Name(id='b', ctx=Load()),\n" +" body=[\n" +" If(\n" +" test=Compare(\n" +" left=Name(id='a', ctx=Load()),\n" +" ops=[\n" +" Gt()],\n" +" comparators=[\n" +" Constant(value=5)]),\n" +" body=[\n" +" Break()],\n" +" orelse=[\n" +" Continue()])],\n" +" orelse=[])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1253 msgid "" "``try`` blocks. All attributes are list of nodes to execute, except for " "``handlers``, which is a list of :class:`ExceptHandler` nodes." msgstr "" +#: library/ast.rst:1256 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... try:\n" +"... ...\n" +"... except Exception:\n" +"... ...\n" +"... except OtherException as e:\n" +"... ...\n" +"... else:\n" +"... ...\n" +"... finally:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Try(\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" handlers=[\n" +" ExceptHandler(\n" +" type=Name(id='Exception', ctx=Load()),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))]),\n" +" ExceptHandler(\n" +" type=Name(id='OtherException', ctx=Load()),\n" +" name='e',\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])],\n" +" orelse=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" finalbody=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1299 msgid "" "``try`` blocks which are followed by ``except*`` clauses. The attributes are " @@ -672,6 +1599,31 @@ msgid "" "``handlers`` are interpreted as ``except*`` blocks rather then ``except``." msgstr "" +#: library/ast.rst:1303 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... try:\n" +"... ...\n" +"... except* Exception:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" TryStar(\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))],\n" +" handlers=[\n" +" ExceptHandler(\n" +" type=Name(id='Exception', ctx=Load()),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])],\n" +" orelse=[],\n" +" finalbody=[])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1331 msgid "" "A single ``except`` clause. ``type`` is the exception type it will match, " @@ -680,6 +1632,33 @@ msgid "" "``None`` if the clause doesn't have ``as foo``. ``body`` is a list of nodes." msgstr "" +#: library/ast.rst:1336 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... try:\n" +"... a + 1\n" +"... except TypeError:\n" +"... pass\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Try(\n" +" body=[\n" +" Expr(\n" +" value=BinOp(\n" +" left=Name(id='a', ctx=Load()),\n" +" op=Add(),\n" +" right=Constant(value=1)))],\n" +" handlers=[\n" +" ExceptHandler(\n" +" type=Name(id='TypeError', ctx=Load()),\n" +" body=[\n" +" Pass()])],\n" +" orelse=[],\n" +" finalbody=[])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1365 msgid "" "A ``with`` block. ``items`` is a list of :class:`withitem` nodes " @@ -695,6 +1674,33 @@ msgid "" "if that isn't used." msgstr "" +#: library/ast.rst:1380 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... with a as b, c as d:\n" +"... something(b, d)\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" With(\n" +" items=[\n" +" withitem(\n" +" context_expr=Name(id='a', ctx=Load()),\n" +" optional_vars=Name(id='b', ctx=Store())),\n" +" withitem(\n" +" context_expr=Name(id='c', ctx=Load()),\n" +" optional_vars=Name(id='d', ctx=Store()))],\n" +" body=[\n" +" Expr(\n" +" value=Call(\n" +" func=Name(id='something', ctx=Load()),\n" +" args=[\n" +" Name(id='b', ctx=Load()),\n" +" Name(id='d', ctx=Load())],\n" +" keywords=[]))])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1408 msgid "Pattern matching" msgstr "" @@ -726,6 +1732,45 @@ msgid "" "result of evaluating the guard expression is true." msgstr "" +#: library/ast.rst:1432 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case [x] if x>0:\n" +"... ...\n" +"... case tuple():\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchSequence(\n" +" patterns=[\n" +" MatchAs(name='x')]),\n" +" guard=Compare(\n" +" left=Name(id='x', ctx=Load()),\n" +" ops=[\n" +" Gt()],\n" +" comparators=[\n" +" Constant(value=0)]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))]),\n" +" match_case(\n" +" pattern=MatchClass(\n" +" cls=Name(id='tuple', ctx=Load()),\n" +" patterns=[],\n" +" kwd_attrs=[],\n" +" kwd_patterns=[]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1474 msgid "" "A match literal or value pattern that compares by equality. ``value`` is an " @@ -734,6 +1779,27 @@ msgid "" "equal to the evaluated value." msgstr "" +#: library/ast.rst:1479 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case \"Relevant\":\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchValue(\n" +" value=Constant(value='Relevant')),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1503 msgid "" "A match literal pattern that compares by identity. ``value`` is the " @@ -741,6 +1807,26 @@ msgid "" "pattern succeeds if the match subject is the given constant." msgstr "" +#: library/ast.rst:1507 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case None:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchSingleton(value=None),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1530 msgid "" "A match sequence pattern. ``patterns`` contains the patterns to be matched " @@ -749,6 +1835,31 @@ msgid "" "otherwise matches a fixed length sequence." msgstr "" +#: library/ast.rst:1535 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case [1, 2]:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchSequence(\n" +" patterns=[\n" +" MatchValue(\n" +" value=Constant(value=1)),\n" +" MatchValue(\n" +" value=Constant(value=2))]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1563 msgid "" "Matches the rest of the sequence in a variable length match sequence " @@ -757,6 +1868,41 @@ msgid "" "successful." msgstr "" +#: library/ast.rst:1567 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case [1, 2, *rest]:\n" +"... ...\n" +"... case [*_]:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchSequence(\n" +" patterns=[\n" +" MatchValue(\n" +" value=Constant(value=1)),\n" +" MatchValue(\n" +" value=Constant(value=2)),\n" +" MatchStar(name='rest')]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))]),\n" +" match_case(\n" +" pattern=MatchSequence(\n" +" patterns=[\n" +" MatchStar()]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1605 msgid "" "A match mapping pattern. ``keys`` is a sequence of expression nodes. " @@ -775,6 +1921,40 @@ msgid "" "overall mapping pattern is successful." msgstr "" +#: library/ast.rst:1617 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case {1: _, 2: _}:\n" +"... ...\n" +"... case {**rest}:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchMapping(\n" +" keys=[\n" +" Constant(value=1),\n" +" Constant(value=2)],\n" +" patterns=[\n" +" MatchAs(),\n" +" MatchAs()]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))]),\n" +" match_case(\n" +" pattern=MatchMapping(keys=[], patterns=[], " +"rest='rest'),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1653 msgid "" "A match class pattern. ``cls`` is an expression giving the nominal class to " @@ -800,6 +1980,54 @@ msgid "" "also matched that way, as described in the match statement documentation." msgstr "" +#: library/ast.rst:1668 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case Point2D(0, 0):\n" +"... ...\n" +"... case Point3D(x=0, y=0, z=0):\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchClass(\n" +" cls=Name(id='Point2D', ctx=Load()),\n" +" patterns=[\n" +" MatchValue(\n" +" value=Constant(value=0)),\n" +" MatchValue(\n" +" value=Constant(value=0))],\n" +" kwd_attrs=[],\n" +" kwd_patterns=[]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))]),\n" +" match_case(\n" +" pattern=MatchClass(\n" +" cls=Name(id='Point3D', ctx=Load()),\n" +" patterns=[],\n" +" kwd_attrs=[\n" +" 'x',\n" +" 'y',\n" +" 'z'],\n" +" kwd_patterns=[\n" +" MatchValue(\n" +" value=Constant(value=0)),\n" +" MatchValue(\n" +" value=Constant(value=0)),\n" +" MatchValue(\n" +" value=Constant(value=0))]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1719 msgid "" "A match \"as-pattern\", capture pattern or wildcard pattern. ``pattern`` " @@ -815,6 +2043,37 @@ msgid "" "and the node represents the wildcard pattern." msgstr "" +#: library/ast.rst:1728 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case [x] as y:\n" +"... ...\n" +"... case _:\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchAs(\n" +" pattern=MatchSequence(\n" +" patterns=[\n" +" MatchAs(name='x')]),\n" +" name='y'),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))]),\n" +" match_case(\n" +" pattern=MatchAs(),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1762 msgid "" "A match \"or-pattern\". An or-pattern matches each of its subpatterns in " @@ -824,6 +2083,31 @@ msgid "" "matched against the subject." msgstr "" +#: library/ast.rst:1768 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\n" +"... match x:\n" +"... case [x] | (y):\n" +"... ...\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" Match(\n" +" subject=Name(id='x', ctx=Load()),\n" +" cases=[\n" +" match_case(\n" +" pattern=MatchOr(\n" +" patterns=[\n" +" MatchSequence(\n" +" patterns=[\n" +" MatchAs(name='x')]),\n" +" MatchAs(name='y')]),\n" +" body=[\n" +" Expr(\n" +" value=Constant(value=Ellipsis))])])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1797 msgid "Type parameters" msgstr "" @@ -841,18 +2125,78 @@ msgid "" "`Tuple`, it represents constraints; otherwise it represents the bound." msgstr "" +#: library/ast.rst:1808 +msgid "" +">>> print(ast.dump(ast.parse(\"type Alias[T: int] = list[T]\"), indent=4))\n" +"Module(\n" +" body=[\n" +" TypeAlias(\n" +" name=Name(id='Alias', ctx=Store()),\n" +" type_params=[\n" +" TypeVar(\n" +" name='T',\n" +" bound=Name(id='int', ctx=Load()))],\n" +" value=Subscript(\n" +" value=Name(id='list', ctx=Load()),\n" +" slice=Name(id='T', ctx=Load()),\n" +" ctx=Load()))],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1829 msgid "" "A :class:`typing.ParamSpec`. ``name`` is the name of the parameter " "specification." msgstr "" +#: library/ast.rst:1831 +msgid "" +">>> print(ast.dump(ast.parse(\"type Alias[**P] = Callable[P, int]\"), " +"indent=4))\n" +"Module(\n" +" body=[\n" +" TypeAlias(\n" +" name=Name(id='Alias', ctx=Store()),\n" +" type_params=[\n" +" ParamSpec(name='P')],\n" +" value=Subscript(\n" +" value=Name(id='Callable', ctx=Load()),\n" +" slice=Tuple(\n" +" elts=[\n" +" Name(id='P', ctx=Load()),\n" +" Name(id='int', ctx=Load())],\n" +" ctx=Load()),\n" +" ctx=Load()))],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1854 msgid "" "A :class:`typing.TypeVarTuple`. ``name`` is the name of the type variable " "tuple." msgstr "" +#: library/ast.rst:1856 +msgid "" +">>> print(ast.dump(ast.parse(\"type Alias[*Ts] = tuple[*Ts]\"), indent=4))\n" +"Module(\n" +" body=[\n" +" TypeAlias(\n" +" name=Name(id='Alias', ctx=Store()),\n" +" type_params=[\n" +" TypeVarTuple(name='Ts')],\n" +" value=Subscript(\n" +" value=Name(id='tuple', ctx=Load()),\n" +" slice=Tuple(\n" +" elts=[\n" +" Starred(\n" +" value=Name(id='Ts', ctx=Load()),\n" +" ctx=Load())],\n" +" ctx=Load()),\n" +" ctx=Load()))],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1879 msgid "Function and class definitions" msgstr "" @@ -883,11 +2227,11 @@ msgstr "" msgid "``returns`` is the return annotation." msgstr "" -#: library/ast.rst:2068 +#: library/ast.rst:2067 msgid "``type_params`` is a list of :ref:`type parameters `." msgstr "" -#: library/ast.rst:2097 library/ast.rst:2108 +#: library/ast.rst:2096 library/ast.rst:2107 msgid "Added ``type_params``." msgstr "" @@ -897,6 +2241,25 @@ msgid "" "expression. Unlike :class:`FunctionDef`, ``body`` holds a single node." msgstr "" +#: library/ast.rst:1906 +msgid "" +">>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4))\n" +"Module(\n" +" body=[\n" +" Expr(\n" +" value=Lambda(\n" +" args=arguments(\n" +" posonlyargs=[],\n" +" args=[\n" +" arg(arg='x'),\n" +" arg(arg='y')],\n" +" kwonlyargs=[],\n" +" kw_defaults=[],\n" +" defaults=[]),\n" +" body=Constant(value=Ellipsis)))],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1927 msgid "The arguments for a function." msgstr "" @@ -936,10 +2299,62 @@ msgid "" "``type_comment`` is an optional string with the type annotation as a comment" msgstr "" +#: library/ast.rst:1948 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... @decorator1\n" +"... @decorator2\n" +"... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return " +"annotation':\n" +"... pass\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" FunctionDef(\n" +" name='f',\n" +" args=arguments(\n" +" posonlyargs=[],\n" +" args=[\n" +" arg(\n" +" arg='a',\n" +" annotation=Constant(value='annotation')),\n" +" arg(arg='b'),\n" +" arg(arg='c')],\n" +" vararg=arg(arg='d'),\n" +" kwonlyargs=[\n" +" arg(arg='e'),\n" +" arg(arg='f')],\n" +" kw_defaults=[\n" +" None,\n" +" Constant(value=3)],\n" +" kwarg=arg(arg='g'),\n" +" defaults=[\n" +" Constant(value=1),\n" +" Constant(value=2)]),\n" +" body=[\n" +" Pass()],\n" +" decorator_list=[\n" +" Name(id='decorator1', ctx=Load()),\n" +" Name(id='decorator2', ctx=Load())],\n" +" returns=Constant(value='return annotation'),\n" +" type_params=[])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:1991 msgid "A ``return`` statement." msgstr "" +#: library/ast.rst:1993 +msgid "" +">>> print(ast.dump(ast.parse('return 4'), indent=4))\n" +"Module(\n" +" body=[\n" +" Return(\n" +" value=Constant(value=4))],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:2006 msgid "" "A ``yield`` or ``yield from`` expression. Because these are expressions, " @@ -947,11 +2362,53 @@ msgid "" "used." msgstr "" +#: library/ast.rst:2009 +msgid "" +">>> print(ast.dump(ast.parse('yield x'), indent=4))\n" +"Module(\n" +" body=[\n" +" Expr(\n" +" value=Yield(\n" +" value=Name(id='x', ctx=Load())))],\n" +" type_ignores=[])\n" +"\n" +">>> print(ast.dump(ast.parse('yield from x'), indent=4))\n" +"Module(\n" +" body=[\n" +" Expr(\n" +" value=YieldFrom(\n" +" value=Name(id='x', ctx=Load())))],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:2031 msgid "" "``global`` and ``nonlocal`` statements. ``names`` is a list of raw strings." msgstr "" +#: library/ast.rst:2033 +msgid "" +">>> print(ast.dump(ast.parse('global x,y,z'), indent=4))\n" +"Module(\n" +" body=[\n" +" Global(\n" +" names=[\n" +" 'x',\n" +" 'y',\n" +" 'z'])],\n" +" type_ignores=[])\n" +"\n" +">>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4))\n" +"Module(\n" +" body=[\n" +" Nonlocal(\n" +" names=[\n" +" 'x',\n" +" 'y',\n" +" 'z'])],\n" +" type_ignores=[])" +msgstr "" + #: library/ast.rst:2058 msgid "A class definition." msgstr "" @@ -967,44 +2424,100 @@ msgstr "" #: library/ast.rst:2062 msgid "" "``keywords`` is a list of :class:`.keyword` nodes, principally for " -"'metaclass'. Other keywords will be passed to the metaclass, as per " -"`PEP-3115 `_." +"'metaclass'. Other keywords will be passed to the metaclass, as per :pep:" +"`3115`." msgstr "" -#: library/ast.rst:2065 +#: library/ast.rst:2064 msgid "" "``body`` is a list of nodes representing the code within the class " "definition." msgstr "" -#: library/ast.rst:2067 +#: library/ast.rst:2066 msgid "``decorator_list`` is a list of nodes, as in :class:`FunctionDef`." msgstr "" -#: library/ast.rst:2101 +#: library/ast.rst:2069 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... @decorator1\n" +"... @decorator2\n" +"... class Foo(base1, base2, metaclass=meta):\n" +"... pass\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" ClassDef(\n" +" name='Foo',\n" +" bases=[\n" +" Name(id='base1', ctx=Load()),\n" +" Name(id='base2', ctx=Load())],\n" +" keywords=[\n" +" keyword(\n" +" arg='metaclass',\n" +" value=Name(id='meta', ctx=Load()))],\n" +" body=[\n" +" Pass()],\n" +" decorator_list=[\n" +" Name(id='decorator1', ctx=Load()),\n" +" Name(id='decorator2', ctx=Load())],\n" +" type_params=[])],\n" +" type_ignores=[])" +msgstr "" + +#: library/ast.rst:2100 msgid "Async and await" msgstr "" -#: library/ast.rst:2105 +#: library/ast.rst:2104 msgid "" "An ``async def`` function definition. Has the same fields as :class:" "`FunctionDef`." msgstr "" -#: library/ast.rst:2114 +#: library/ast.rst:2113 msgid "" "An ``await`` expression. ``value`` is what it waits for. Only valid in the " "body of an :class:`AsyncFunctionDef`." msgstr "" -#: library/ast.rst:2148 +#: library/ast.rst:2116 +msgid "" +">>> print(ast.dump(ast.parse(\"\"\"\\\n" +"... async def f():\n" +"... await other_func()\n" +"... \"\"\"), indent=4))\n" +"Module(\n" +" body=[\n" +" AsyncFunctionDef(\n" +" name='f',\n" +" args=arguments(\n" +" posonlyargs=[],\n" +" args=[],\n" +" kwonlyargs=[],\n" +" kw_defaults=[],\n" +" defaults=[]),\n" +" body=[\n" +" Expr(\n" +" value=Await(\n" +" value=Call(\n" +" func=Name(id='other_func', ctx=Load()),\n" +" args=[],\n" +" keywords=[])))],\n" +" decorator_list=[],\n" +" type_params=[])],\n" +" type_ignores=[])" +msgstr "" + +#: library/ast.rst:2147 msgid "" "``async for`` loops and ``async with`` context managers. They have the same " "fields as :class:`For` and :class:`With`, respectively. Only valid in the " "body of an :class:`AsyncFunctionDef`." msgstr "" -#: library/ast.rst:2153 +#: library/ast.rst:2152 msgid "" "When a string is parsed by :func:`ast.parse`, operator nodes (subclasses of :" "class:`ast.operator`, :class:`ast.unaryop`, :class:`ast.cmpop`, :class:`ast." @@ -1013,28 +2526,28 @@ msgid "" "same value (e.g. :class:`ast.Add`)." msgstr "" -#: library/ast.rst:2161 +#: library/ast.rst:2160 msgid ":mod:`ast` Helpers" msgstr "" -#: library/ast.rst:2163 +#: library/ast.rst:2162 msgid "" "Apart from the node classes, the :mod:`ast` module defines these utility " "functions and classes for traversing abstract syntax trees:" msgstr "" -#: library/ast.rst:2168 +#: library/ast.rst:2167 msgid "" "Parse the source into an AST node. Equivalent to ``compile(source, " "filename, mode, ast.PyCF_ONLY_AST)``." msgstr "" -#: library/ast.rst:2171 +#: library/ast.rst:2170 msgid "" "If ``type_comments=True`` is given, the parser is modified to check and " "return type comments as specified by :pep:`484` and :pep:`526`. This is " "equivalent to adding :data:`ast.PyCF_TYPE_COMMENTS` to the flags passed to :" -"func:`compile()`. This will report syntax errors for misplaced type " +"func:`compile`. This will report syntax errors for misplaced type " "comments. Without this flag, type comments will be ignored, and the " "``type_comment`` field on selected AST nodes will always be ``None``. In " "addition, the locations of ``# type: ignore`` comments will be returned as " @@ -1042,14 +2555,14 @@ msgid "" "empty list)." msgstr "" -#: library/ast.rst:2181 +#: library/ast.rst:2180 msgid "" "In addition, if ``mode`` is ``'func_type'``, the input syntax is modified to " "correspond to :pep:`484` \"signature type comments\", e.g. ``(str, int) -> " "List[str]``." msgstr "" -#: library/ast.rst:2185 +#: library/ast.rst:2184 msgid "" "Setting ``feature_version`` to a tuple ``(major, minor)`` will result in a " "\"best-effort\" attempt to parse using that Python version's grammar. For " @@ -1062,12 +2575,12 @@ msgid "" "``feature_version``." msgstr "" -#: library/ast.rst:2195 +#: library/ast.rst:2194 msgid "" "If source contains a null character (``\\0``), :exc:`ValueError` is raised." msgstr "" -#: library/ast.rst:2198 +#: library/ast.rst:2197 msgid "" "Note that successfully parsing source code into an AST object doesn't " "guarantee that the source code provided is valid Python code that can be " @@ -1077,43 +2590,43 @@ msgid "" "inside a function node)." msgstr "" -#: library/ast.rst:2205 +#: library/ast.rst:2204 msgid "" "In particular, :func:`ast.parse` won't do any scoping checks, which the " "compilation step does." msgstr "" -#: library/ast.rst:2209 +#: library/ast.rst:2208 msgid "" "It is possible to crash the Python interpreter with a sufficiently large/" "complex string due to stack depth limitations in Python's AST compiler." msgstr "" -#: library/ast.rst:2213 +#: library/ast.rst:2212 msgid "Added ``type_comments``, ``mode='func_type'`` and ``feature_version``." msgstr "" -#: library/ast.rst:2219 +#: library/ast.rst:2218 msgid "" "Unparse an :class:`ast.AST` object and generate a string with code that " "would produce an equivalent :class:`ast.AST` object if parsed back with :" "func:`ast.parse`." msgstr "" -#: library/ast.rst:2224 +#: library/ast.rst:2223 msgid "" "The produced code string will not necessarily be equal to the original code " "that generated the :class:`ast.AST` object (without any compiler " "optimizations, such as constant tuples/frozensets)." msgstr "" -#: library/ast.rst:2229 +#: library/ast.rst:2228 msgid "" "Trying to unparse a highly complex expression would result with :exc:" "`RecursionError`." msgstr "" -#: library/ast.rst:2237 +#: library/ast.rst:2236 msgid "" "Evaluate an expression node or a string containing only a Python literal or " "container display. The string or node provided may only consist of the " @@ -1121,14 +2634,14 @@ msgid "" "dicts, sets, booleans, ``None`` and ``Ellipsis``." msgstr "" -#: library/ast.rst:2242 +#: library/ast.rst:2241 msgid "" "This can be used for evaluating strings containing Python values without the " "need to parse the values oneself. It is not capable of evaluating " "arbitrarily complex expressions, for example involving operators or indexing." msgstr "" -#: library/ast.rst:2247 +#: library/ast.rst:2246 msgid "" "This function had been documented as \"safe\" in the past without defining " "what that meant. That was misleading. This is specifically designed not to " @@ -1140,31 +2653,31 @@ msgid "" "untrusted data is thus not recommended." msgstr "" -#: library/ast.rst:2257 +#: library/ast.rst:2256 msgid "" "It is possible to crash the Python interpreter due to stack depth " "limitations in Python's AST compiler." msgstr "" -#: library/ast.rst:2260 +#: library/ast.rst:2259 msgid "" "It can raise :exc:`ValueError`, :exc:`TypeError`, :exc:`SyntaxError`, :exc:" "`MemoryError` and :exc:`RecursionError` depending on the malformed input." msgstr "" -#: library/ast.rst:2264 +#: library/ast.rst:2263 msgid "Now allows bytes and set literals." msgstr "" -#: library/ast.rst:2267 +#: library/ast.rst:2266 msgid "Now supports creating empty sets with ``'set()'``." msgstr "" -#: library/ast.rst:2270 +#: library/ast.rst:2269 msgid "For string inputs, leading spaces and tabs are now stripped." msgstr "" -#: library/ast.rst:2276 +#: library/ast.rst:2275 msgid "" "Return the docstring of the given *node* (which must be a :class:" "`FunctionDef`, :class:`AsyncFunctionDef`, :class:`ClassDef`, or :class:" @@ -1172,11 +2685,11 @@ msgid "" "clean up the docstring's indentation with :func:`inspect.cleandoc`." msgstr "" -#: library/ast.rst:2282 +#: library/ast.rst:2281 msgid ":class:`AsyncFunctionDef` is now supported." msgstr "" -#: library/ast.rst:2288 +#: library/ast.rst:2287 msgid "" "Get source code segment of the *source* that generated *node*. If some " "location information (:attr:`~ast.AST.lineno`, :attr:`~ast.AST.end_lineno`, :" @@ -1184,13 +2697,13 @@ msgid "" "return ``None``." msgstr "" -#: library/ast.rst:2292 +#: library/ast.rst:2291 msgid "" "If *padded* is ``True``, the first line of a multi-line statement will be " "padded with spaces to match its original position." msgstr "" -#: library/ast.rst:2300 +#: library/ast.rst:2299 msgid "" "When you compile a node tree with :func:`compile`, the compiler expects :" "attr:`~ast.AST.lineno` and :attr:`~ast.AST.col_offset` attributes for every " @@ -1200,81 +2713,81 @@ msgid "" "starting at *node*." msgstr "" -#: library/ast.rst:2309 +#: library/ast.rst:2308 msgid "" "Increment the line number and end line number of each node in the tree " "starting at *node* by *n*. This is useful to \"move code\" to a different " "location in a file." msgstr "" -#: library/ast.rst:2316 +#: library/ast.rst:2315 msgid "" "Copy source location (:attr:`~ast.AST.lineno`, :attr:`~ast.AST.col_offset`, :" "attr:`~ast.AST.end_lineno`, and :attr:`~ast.AST.end_col_offset`) from " "*old_node* to *new_node* if possible, and return *new_node*." msgstr "" -#: library/ast.rst:2323 +#: library/ast.rst:2322 msgid "" "Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` " "that is present on *node*." msgstr "" -#: library/ast.rst:2329 +#: library/ast.rst:2328 msgid "" "Yield all direct child nodes of *node*, that is, all fields that are nodes " "and all items of fields that are lists of nodes." msgstr "" -#: library/ast.rst:2335 +#: library/ast.rst:2334 msgid "" "Recursively yield all descendant nodes in the tree starting at *node* " "(including *node* itself), in no specified order. This is useful if you " "only want to modify nodes in place and don't care about the context." msgstr "" -#: library/ast.rst:2342 +#: library/ast.rst:2341 msgid "" "A node visitor base class that walks the abstract syntax tree and calls a " "visitor function for every node found. This function may return a value " "which is forwarded by the :meth:`visit` method." msgstr "" -#: library/ast.rst:2346 +#: library/ast.rst:2345 msgid "" "This class is meant to be subclassed, with the subclass adding visitor " "methods." msgstr "" -#: library/ast.rst:2351 +#: library/ast.rst:2350 msgid "" "Visit a node. The default implementation calls the method called :samp:" "`self.visit_{classname}` where *classname* is the name of the node class, " "or :meth:`generic_visit` if that method doesn't exist." msgstr "" -#: library/ast.rst:2357 +#: library/ast.rst:2356 msgid "This visitor calls :meth:`visit` on all children of the node." msgstr "" -#: library/ast.rst:2359 +#: library/ast.rst:2358 msgid "" "Note that child nodes of nodes that have a custom visitor method won't be " "visited unless the visitor calls :meth:`generic_visit` or visits them itself." msgstr "" -#: library/ast.rst:2365 +#: library/ast.rst:2364 msgid "Handles all constant nodes." msgstr "" -#: library/ast.rst:2367 +#: library/ast.rst:2366 msgid "" "Don't use the :class:`NodeVisitor` if you want to apply changes to nodes " "during traversal. For this a special visitor exists (:class:" "`NodeTransformer`) that allows modifications." msgstr "" -#: library/ast.rst:2373 +#: library/ast.rst:2372 msgid "" "Methods :meth:`!visit_Num`, :meth:`!visit_Str`, :meth:`!visit_Bytes`, :meth:" "`!visit_NameConstant` and :meth:`!visit_Ellipsis` are deprecated now and " @@ -1282,13 +2795,13 @@ msgid "" "`visit_Constant` method to handle all constant nodes." msgstr "" -#: library/ast.rst:2381 +#: library/ast.rst:2380 msgid "" "A :class:`NodeVisitor` subclass that walks the abstract syntax tree and " "allows modification of nodes." msgstr "" -#: library/ast.rst:2384 +#: library/ast.rst:2383 msgid "" "The :class:`NodeTransformer` will walk the AST and use the return value of " "the visitor methods to replace or remove the old node. If the return value " @@ -1297,27 +2810,39 @@ msgid "" "may be the original node in which case no replacement takes place." msgstr "" -#: library/ast.rst:2390 +#: library/ast.rst:2389 msgid "" "Here is an example transformer that rewrites all occurrences of name lookups " "(``foo``) to ``data['foo']``::" msgstr "" -#: library/ast.rst:2402 +#: library/ast.rst:2392 +msgid "" +"class RewriteName(NodeTransformer):\n" +"\n" +" def visit_Name(self, node):\n" +" return Subscript(\n" +" value=Name(id='data', ctx=Load()),\n" +" slice=Constant(value=node.id),\n" +" ctx=node.ctx\n" +" )" +msgstr "" + +#: library/ast.rst:2401 msgid "" "Keep in mind that if the node you're operating on has child nodes you must " "either transform the child nodes yourself or call the :meth:`~ast." "NodeVisitor.generic_visit` method for the node first." msgstr "" -#: library/ast.rst:2406 +#: library/ast.rst:2405 msgid "" "For nodes that were part of a collection of statements (that applies to all " "statement nodes), the visitor may also return a list of nodes rather than " "just a single node." msgstr "" -#: library/ast.rst:2410 +#: library/ast.rst:2409 msgid "" "If :class:`NodeTransformer` introduces new nodes (that weren't part of " "original tree) without giving them location information (such as :attr:`~ast." @@ -1325,11 +2850,21 @@ msgid "" "sub-tree to recalculate the location information::" msgstr "" -#: library/ast.rst:2418 +#: library/ast.rst:2414 +msgid "" +"tree = ast.parse('foo', mode='eval')\n" +"new_tree = fix_missing_locations(RewriteName().visit(tree))" +msgstr "" + +#: library/ast.rst:2417 msgid "Usually you use the transformer like this::" msgstr "" -#: library/ast.rst:2425 +#: library/ast.rst:2419 +msgid "node = YourTransformer().visit(node)" +msgstr "" + +#: library/ast.rst:2424 msgid "" "Return a formatted dump of the tree in *node*. This is mainly useful for " "debugging purposes. If *annotate_fields* is true (by default), the returned " @@ -1340,7 +2875,7 @@ msgid "" "true." msgstr "" -#: library/ast.rst:2433 +#: library/ast.rst:2432 msgid "" "If *indent* is a non-negative integer or string, then the tree will be " "pretty-printed with that indent level. An indent level of 0, negative, or " @@ -1350,87 +2885,91 @@ msgid "" "string is used to indent each level." msgstr "" -#: library/ast.rst:2440 +#: library/ast.rst:2439 msgid "Added the *indent* option." msgstr "" -#: library/ast.rst:2447 +#: library/ast.rst:2446 msgid "Compiler Flags" msgstr "" -#: library/ast.rst:2449 +#: library/ast.rst:2448 msgid "" "The following flags may be passed to :func:`compile` in order to change " "effects on the compilation of a program:" msgstr "" -#: library/ast.rst:2454 +#: library/ast.rst:2453 msgid "" "Enables support for top-level ``await``, ``async for``, ``async with`` and " "async comprehensions." msgstr "" -#: library/ast.rst:2461 +#: library/ast.rst:2460 msgid "" "Generates and returns an abstract syntax tree instead of returning a " "compiled code object." msgstr "" -#: library/ast.rst:2466 +#: library/ast.rst:2465 msgid "" "Enables support for :pep:`484` and :pep:`526` style type comments (``# type: " "``, ``# type: ignore ``)." msgstr "" -#: library/ast.rst:2475 +#: library/ast.rst:2474 msgid "Command-Line Usage" msgstr "" -#: library/ast.rst:2479 +#: library/ast.rst:2478 msgid "" "The :mod:`ast` module can be executed as a script from the command line. It " "is as simple as:" msgstr "" -#: library/ast.rst:2486 +#: library/ast.rst:2481 +msgid "python -m ast [-m ] [-a] [infile]" +msgstr "" + +#: library/ast.rst:2485 msgid "The following options are accepted:" msgstr "" -#: library/ast.rst:2492 +#: library/ast.rst:2491 msgid "Show the help message and exit." msgstr "" -#: library/ast.rst:2497 +#: library/ast.rst:2496 msgid "" "Specify what kind of code must be compiled, like the *mode* argument in :" "func:`parse`." msgstr "" -#: library/ast.rst:2502 +#: library/ast.rst:2501 msgid "Don't parse type comments." msgstr "" -#: library/ast.rst:2506 +#: library/ast.rst:2505 msgid "Include attributes such as line numbers and column offsets." msgstr "" -#: library/ast.rst:2511 +#: library/ast.rst:2510 msgid "Indentation of nodes in AST (number of spaces)." msgstr "" -#: library/ast.rst:2513 +#: library/ast.rst:2512 msgid "" "If :file:`infile` is specified its contents are parsed to AST and dumped to " "stdout. Otherwise, the content is read from stdin." msgstr "" -#: library/ast.rst:2519 +#: library/ast.rst:2518 msgid "" "`Green Tree Snakes `_, an external " "documentation resource, has good details on working with Python ASTs." msgstr "" -#: library/ast.rst:2522 +#: library/ast.rst:2521 msgid "" "`ASTTokens `_ " "annotates Python ASTs with the positions of tokens and text in the source " @@ -1438,21 +2977,21 @@ msgid "" "transformations." msgstr "" -#: library/ast.rst:2527 +#: library/ast.rst:2526 msgid "" "`leoAst.py `_ unifies the token-based and parse-tree-based views of python programs " "by inserting two-way links between tokens and ast nodes." msgstr "" -#: library/ast.rst:2532 +#: library/ast.rst:2531 msgid "" "`LibCST `_ parses code as a Concrete Syntax " "Tree that looks like an ast tree and keeps all formatting details. It's " "useful for building automated refactoring (codemod) applications and linters." msgstr "" -#: library/ast.rst:2537 +#: library/ast.rst:2536 msgid "" "`Parso `_ is a Python parser that supports " "error recovery and round-trip parsing for different Python versions (in " diff --git a/library/asyncio-dev.po b/library/asyncio-dev.po index 0a8a2c15a..662bc5155 100644 --- a/library/asyncio-dev.po +++ b/library/asyncio-dev.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-09-18 19:05+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -72,6 +72,10 @@ msgid "" "at startup of the application::" msgstr "" +#: library/asyncio-dev.rst:40 +msgid "logging.basicConfig(level=logging.DEBUG)" +msgstr "" + #: library/asyncio-dev.rst:42 msgid "" "configuring the :mod:`warnings` module to display :exc:`ResourceWarning` " @@ -129,6 +133,10 @@ msgid "" "call_soon_threadsafe` method should be used. Example::" msgstr "" +#: library/asyncio-dev.rst:79 +msgid "loop.call_soon_threadsafe(callback, *args)" +msgstr "" + #: library/asyncio-dev.rst:81 msgid "" "Almost all asyncio objects are not thread safe, which is typically not a " @@ -137,6 +145,10 @@ msgid "" "API, the :meth:`loop.call_soon_threadsafe` method should be used, e.g.::" msgstr "" +#: library/asyncio-dev.rst:87 +msgid "loop.call_soon_threadsafe(fut.cancel)" +msgstr "" + #: library/asyncio-dev.rst:89 msgid "" "To schedule a coroutine object from a different OS thread, the :func:" @@ -144,6 +156,18 @@ msgid "" "`concurrent.futures.Future` to access the result::" msgstr "" +#: library/asyncio-dev.rst:93 +msgid "" +"async def coro_func():\n" +" return await asyncio.sleep(1, 42)\n" +"\n" +"# Later in another OS thread:\n" +"\n" +"future = asyncio.run_coroutine_threadsafe(coro_func(), loop)\n" +"# Wait for the result:\n" +"result = future.result()" +msgstr "" + #: library/asyncio-dev.rst:102 msgid "To handle signals the event loop must be run in the main thread." msgstr "" @@ -203,6 +227,10 @@ msgid "" "adjusted::" msgstr "" +#: library/asyncio-dev.rst:148 +msgid "logging.getLogger(\"asyncio\").setLevel(logging.WARNING)" +msgstr "" + #: library/asyncio-dev.rst:151 msgid "" "Network logging can block the event loop. It is recommended to use a " @@ -221,20 +249,59 @@ msgid "" "`asyncio.create_task`, asyncio will emit a :exc:`RuntimeWarning`::" msgstr "" +#: library/asyncio-dev.rst:166 +msgid "" +"import asyncio\n" +"\n" +"async def test():\n" +" print(\"never scheduled\")\n" +"\n" +"async def main():\n" +" test()\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: library/asyncio-dev.rst:221 msgid "Output::" msgstr "" +#: library/asyncio-dev.rst:178 +msgid "" +"test.py:7: RuntimeWarning: coroutine 'test' was never awaited\n" +" test()" +msgstr "" + #: library/asyncio-dev.rst:237 msgid "Output in debug mode::" msgstr "" +#: library/asyncio-dev.rst:183 +msgid "" +"test.py:7: RuntimeWarning: coroutine 'test' was never awaited\n" +"Coroutine created at (most recent call last)\n" +" File \"../t.py\", line 9, in \n" +" asyncio.run(main(), debug=True)\n" +"\n" +" < .. >\n" +"\n" +" File \"../t.py\", line 7, in main\n" +" test()\n" +" test()" +msgstr "" + #: library/asyncio-dev.rst:194 msgid "" "The usual fix is to either await the coroutine or call the :meth:`asyncio." "create_task` function::" msgstr "" +#: library/asyncio-dev.rst:197 +msgid "" +"async def main():\n" +" await test()" +msgstr "" + #: library/asyncio-dev.rst:202 msgid "Detect never-retrieved exceptions" msgstr "" @@ -251,8 +318,55 @@ msgstr "" msgid "Example of an unhandled exception::" msgstr "" +#: library/asyncio-dev.rst:211 +msgid "" +"import asyncio\n" +"\n" +"async def bug():\n" +" raise Exception(\"not consumed\")\n" +"\n" +"async def main():\n" +" asyncio.create_task(bug())\n" +"\n" +"asyncio.run(main())" +msgstr "" + +#: library/asyncio-dev.rst:223 +msgid "" +"Task exception was never retrieved\n" +"future: \n" +" exception=Exception('not consumed')>\n" +"\n" +"Traceback (most recent call last):\n" +" File \"test.py\", line 4, in bug\n" +" raise Exception(\"not consumed\")\n" +"Exception: not consumed" +msgstr "" + #: library/asyncio-dev.rst:232 msgid "" ":ref:`Enable the debug mode ` to get the traceback where " "the task was created::" msgstr "" + +#: library/asyncio-dev.rst:235 +msgid "asyncio.run(main(), debug=True)" +msgstr "" + +#: library/asyncio-dev.rst:239 +msgid "" +"Task exception was never retrieved\n" +"future: \n" +" exception=Exception('not consumed') created at asyncio/tasks.py:321>\n" +"\n" +"source_traceback: Object created at (most recent call last):\n" +" File \"../t.py\", line 9, in \n" +" asyncio.run(main(), debug=True)\n" +"\n" +"< .. >\n" +"\n" +"Traceback (most recent call last):\n" +" File \"../t.py\", line 4, in bug\n" +" raise Exception(\"not consumed\")\n" +"Exception: not consumed" +msgstr "" diff --git a/library/asyncio-eventloop.po b/library/asyncio-eventloop.po index 2c4f537d2..6bf4faa75 100644 --- a/library/asyncio-eventloop.po +++ b/library/asyncio-eventloop.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -189,7 +189,7 @@ msgstr "" #: library/asyncio-eventloop.rst:129 msgid "" -"If :meth:`stop` is called before :meth:`run_forever()` is called, the loop " +"If :meth:`stop` is called before :meth:`run_forever` is called, the loop " "will poll the I/O selector once with a timeout of zero, run all callbacks " "scheduled in response to I/O events (and those that were already scheduled), " "and then exit." @@ -241,7 +241,7 @@ msgstr "" #: library/asyncio-eventloop.rst:167 msgid "" "Schedule all currently open :term:`asynchronous generator` objects to close " -"with an :meth:`~agen.aclose()` call. After calling this method, the event " +"with an :meth:`~agen.aclose` call. After calling this method, the event " "loop will issue a warning if a new asynchronous generator is iterated. This " "should be used to reliably finalize all scheduled asynchronous generators." msgstr "" @@ -257,6 +257,15 @@ msgstr "" msgid "Example::" msgstr "" +#: library/asyncio-eventloop.rst:178 +msgid "" +"try:\n" +" loop.run_forever()\n" +"finally:\n" +" loop.run_until_complete(loop.shutdown_asyncgens())\n" +" loop.close()" +msgstr "" + #: library/asyncio-eventloop.rst:188 msgid "" "Schedule the closure of the default executor and wait for it to join all of " @@ -354,6 +363,13 @@ msgid "" "arguments. To do that, use :func:`functools.partial`::" msgstr "" +#: library/asyncio-eventloop.rst:257 +msgid "" +"# will schedule \"print(\"Hello\", flush=True)\"\n" +"loop.call_soon(\n" +" functools.partial(print, \"Hello\", flush=True))" +msgstr "" + #: library/asyncio-eventloop.rst:261 msgid "" "Using partial objects is usually more convenient than using lambdas, as " @@ -866,8 +882,9 @@ msgid "" msgstr "" #: library/asyncio-eventloop.rst:652 library/asyncio-eventloop.rst:794 -#: library/asyncio-eventloop.rst:1233 -msgid ":ref:`Availability `: Unix." +#: library/asyncio-eventloop.rst:1233 library/asyncio-eventloop.rst:1741 +#: library/asyncio-eventloop.rst:1748 +msgid "Availability" msgstr "" #: library/asyncio-eventloop.rst:654 @@ -1515,6 +1532,49 @@ msgid "" "and used by :func:`run_in_executor` if needed." msgstr "" +#: library/asyncio-eventloop.rst:1255 +msgid "" +"import asyncio\n" +"import concurrent.futures\n" +"\n" +"def blocking_io():\n" +" # File operations (such as logging) can block the\n" +" # event loop: run them in a thread pool.\n" +" with open('/dev/urandom', 'rb') as f:\n" +" return f.read(100)\n" +"\n" +"def cpu_bound():\n" +" # CPU-bound operations will block the event loop:\n" +" # in general it is preferable to run them in a\n" +" # process pool.\n" +" return sum(i * i for i in range(10 ** 7))\n" +"\n" +"async def main():\n" +" loop = asyncio.get_running_loop()\n" +"\n" +" ## Options:\n" +"\n" +" # 1. Run in the default loop's executor:\n" +" result = await loop.run_in_executor(\n" +" None, blocking_io)\n" +" print('default thread pool', result)\n" +"\n" +" # 2. Run in a custom thread pool:\n" +" with concurrent.futures.ThreadPoolExecutor() as pool:\n" +" result = await loop.run_in_executor(\n" +" pool, blocking_io)\n" +" print('custom thread pool', result)\n" +"\n" +" # 3. Run in a custom process pool:\n" +" with concurrent.futures.ProcessPoolExecutor() as pool:\n" +" result = await loop.run_in_executor(\n" +" pool, cpu_bound)\n" +" print('custom process pool', result)\n" +"\n" +"if __name__ == '__main__':\n" +" asyncio.run(main())" +msgstr "" + #: library/asyncio-eventloop.rst:1295 msgid "" "Note that the entry point guard (``if __name__ == '__main__'``) is required " @@ -1664,7 +1724,7 @@ msgstr "" #: library/asyncio-eventloop.rst:1387 msgid "" "This method should not be overloaded in subclassed event loops. For custom " -"exception handling, use the :meth:`set_exception_handler()` method." +"exception handling, use the :meth:`set_exception_handler` method." msgstr "" #: library/asyncio-eventloop.rst:1392 @@ -1780,7 +1840,7 @@ msgstr "" #: library/asyncio-eventloop.rst:1472 msgid "" "an existing file descriptor (a positive integer), for example those created " -"with :meth:`os.pipe()`" +"with :meth:`os.pipe`" msgstr "" #: library/asyncio-eventloop.rst:1473 library/asyncio-eventloop.rst:1483 @@ -1962,6 +2022,16 @@ msgid "" "accepting new connections when the ``async with`` statement is completed::" msgstr "" +#: library/asyncio-eventloop.rst:1613 +msgid "" +"srv = await loop.create_server(...)\n" +"\n" +"async with srv:\n" +" # some code\n" +"\n" +"# At this point, srv is closed and no longer accepts new connections." +msgstr "" + #: library/asyncio-eventloop.rst:1621 msgid "Server object is an asynchronous context manager since Python 3.7." msgstr "" @@ -2025,6 +2095,21 @@ msgid "" "Only one ``serve_forever`` task can exist per one *Server* object." msgstr "" +#: library/asyncio-eventloop.rst:1673 +msgid "" +"async def client_connected(reader, writer):\n" +" # Communicate with the client with\n" +" # reader/writer streams. For example:\n" +" await reader.readline()\n" +"\n" +"async def main(host, port):\n" +" srv = await asyncio.start_server(\n" +" client_connected, host, port)\n" +" await srv.serve_forever()\n" +"\n" +"asyncio.run(main('127.0.0.1', 0))" +msgstr "" + #: library/asyncio-eventloop.rst:1689 msgid "Return ``True`` if the server is accepting new connections." msgstr "" @@ -2074,18 +2159,23 @@ msgid "" "used::" msgstr "" -#: library/asyncio-eventloop.rst:1741 -msgid ":ref:`Availability `: Unix, Windows." +#: library/asyncio-eventloop.rst:1730 +msgid "" +"import asyncio\n" +"import selectors\n" +"\n" +"class MyPolicy(asyncio.DefaultEventLoopPolicy):\n" +" def new_event_loop(self):\n" +" selector = selectors.SelectSelector()\n" +" return asyncio.SelectorEventLoop(selector)\n" +"\n" +"asyncio.set_event_loop_policy(MyPolicy())" msgstr "" #: library/asyncio-eventloop.rst:1746 msgid "An event loop for Windows that uses \"I/O Completion Ports\" (IOCP)." msgstr "" -#: library/asyncio-eventloop.rst:1748 -msgid ":ref:`Availability `: Windows." -msgstr "" - #: library/asyncio-eventloop.rst:1752 msgid "" "`MSDN documentation on I/O Completion Ports ` example created with a coroutine " @@ -2141,6 +2252,31 @@ msgid "" "5 seconds, and then stops the event loop::" msgstr "" +#: library/asyncio-eventloop.rst:1817 +msgid "" +"import asyncio\n" +"import datetime\n" +"\n" +"def display_date(end_time, loop):\n" +" print(datetime.datetime.now())\n" +" if (loop.time() + 1.0) < end_time:\n" +" loop.call_later(1, display_date, end_time, loop)\n" +" else:\n" +" loop.stop()\n" +"\n" +"loop = asyncio.new_event_loop()\n" +"\n" +"# Schedule the first call to display_date()\n" +"end_time = loop.time() + 5.0\n" +"loop.call_soon(display_date, end_time, loop)\n" +"\n" +"# Blocking call interrupted by loop.stop()\n" +"try:\n" +" loop.run_forever()\n" +"finally:\n" +" loop.close()" +msgstr "" + #: library/asyncio-eventloop.rst:1841 msgid "" "A similar :ref:`current date ` example created with a " @@ -2157,6 +2293,42 @@ msgid "" "add_reader` method and then close the event loop::" msgstr "" +#: library/asyncio-eventloop.rst:1853 +msgid "" +"import asyncio\n" +"from socket import socketpair\n" +"\n" +"# Create a pair of connected file descriptors\n" +"rsock, wsock = socketpair()\n" +"\n" +"loop = asyncio.new_event_loop()\n" +"\n" +"def reader():\n" +" data = rsock.recv(100)\n" +" print(\"Received:\", data.decode())\n" +"\n" +" # We are done: unregister the file descriptor\n" +" loop.remove_reader(rsock)\n" +"\n" +" # Stop the event loop\n" +" loop.stop()\n" +"\n" +"# Register the file descriptor for read event\n" +"loop.add_reader(rsock, reader)\n" +"\n" +"# Simulate the reception of data from the network\n" +"loop.call_soon(wsock.send, 'abc'.encode())\n" +"\n" +"try:\n" +" # Run the event loop\n" +" loop.run_forever()\n" +"finally:\n" +" # We are done. Close sockets and the event loop.\n" +" rsock.close()\n" +" wsock.close()\n" +" loop.close()" +msgstr "" + #: library/asyncio-eventloop.rst:1888 msgid "" "A similar :ref:`example ` using " @@ -2182,3 +2354,30 @@ msgid "" "Register handlers for signals :const:`~signal.SIGINT` and :const:`~signal." "SIGTERM` using the :meth:`loop.add_signal_handler` method::" msgstr "" + +#: library/asyncio-eventloop.rst:1907 +msgid "" +"import asyncio\n" +"import functools\n" +"import os\n" +"import signal\n" +"\n" +"def ask_exit(signame, loop):\n" +" print(\"got signal %s: exit\" % signame)\n" +" loop.stop()\n" +"\n" +"async def main():\n" +" loop = asyncio.get_running_loop()\n" +"\n" +" for signame in {'SIGINT', 'SIGTERM'}:\n" +" loop.add_signal_handler(\n" +" getattr(signal, signame),\n" +" functools.partial(ask_exit, signame, loop))\n" +"\n" +" await asyncio.sleep(3600)\n" +"\n" +"print(\"Event loop running for 1 hour, press Ctrl+C to interrupt.\")\n" +"print(f\"pid {os.getpid()}: send SIGINT or SIGTERM to exit.\")\n" +"\n" +"asyncio.run(main())" +msgstr "" diff --git a/library/asyncio-future.po b/library/asyncio-future.po index b5901db58..c3bff5d00 100644 --- a/library/asyncio-future.po +++ b/library/asyncio-future.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -216,6 +216,12 @@ msgid "" "setting a result or an exception for it::" msgstr "" +#: library/asyncio-future.rst:154 +msgid "" +"if not fut.cancelled():\n" +" fut.set_result(42)" +msgstr "" + #: library/asyncio-future.rst:159 msgid "Add a callback to be run when the Future is *done*." msgstr "" @@ -243,6 +249,13 @@ msgid "" "g.::" msgstr "" +#: library/asyncio-future.rst:174 +msgid "" +"# Call 'print(\"Future:\", fut)' when \"fut\" is done.\n" +"fut.add_done_callback(\n" +" functools.partial(print, \"Future:\"))" +msgstr "" + #: library/asyncio-future.rst:178 msgid "" "The *context* keyword-only parameter was added. See :pep:`567` for more " @@ -300,6 +313,37 @@ msgid "" "Task to set result for the Future, and waits until the Future has a result::" msgstr "" +#: library/asyncio-future.rst:226 +msgid "" +"async def set_after(fut, delay, value):\n" +" # Sleep for *delay* seconds.\n" +" await asyncio.sleep(delay)\n" +"\n" +" # Set *value* as a result of *fut* Future.\n" +" fut.set_result(value)\n" +"\n" +"async def main():\n" +" # Get the current event loop.\n" +" loop = asyncio.get_running_loop()\n" +"\n" +" # Create a new Future object.\n" +" fut = loop.create_future()\n" +"\n" +" # Run \"set_after()\" coroutine in a parallel Task.\n" +" # We are using the low-level \"loop.create_task()\" API here because\n" +" # we already have a reference to the event loop at hand.\n" +" # Otherwise we could have just used \"asyncio.create_task()\".\n" +" loop.create_task(\n" +" set_after(fut, 1, '... world'))\n" +"\n" +" print('hello ...')\n" +"\n" +" # Wait until *fut* has a result (1 second) and print it.\n" +" print(await fut)\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: library/asyncio-future.rst:257 msgid "" "The Future object was designed to mimic :class:`concurrent.futures.Future`. " diff --git a/library/asyncio-llapi-index.po b/library/asyncio-llapi-index.po index 84810aa09..c61892001 100644 --- a/library/asyncio-llapi-index.po +++ b/library/asyncio-llapi-index.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-10-05 21:24+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -115,7 +115,7 @@ msgid "Close the event loop." msgstr "" #: library/asyncio-llapi-index.rst:59 -msgid ":meth:`loop.is_running()`" +msgid ":meth:`loop.is_running`" msgstr "" #: library/asyncio-llapi-index.rst:60 @@ -123,7 +123,7 @@ msgid "Return ``True`` if the event loop is running." msgstr "" #: library/asyncio-llapi-index.rst:62 -msgid ":meth:`loop.is_closed()`" +msgid ":meth:`loop.is_closed`" msgstr "" #: library/asyncio-llapi-index.rst:63 diff --git a/library/asyncio-platforms.po b/library/asyncio-platforms.po index cefab21c6..1491d6401 100644 --- a/library/asyncio-platforms.po +++ b/library/asyncio-platforms.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-09-18 19:05+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -151,3 +151,13 @@ msgid "" "class:`~selectors.SelectSelector` or :class:`~selectors.PollSelector` to " "support character devices on these older versions of macOS. Example::" msgstr "" + +#: library/asyncio-platforms.rst:100 +msgid "" +"import asyncio\n" +"import selectors\n" +"\n" +"selector = selectors.SelectSelector()\n" +"loop = asyncio.SelectorEventLoop(selector)\n" +"asyncio.set_event_loop(loop)" +msgstr "" diff --git a/library/asyncio-policy.po b/library/asyncio-policy.po index 33c65b22b..710149670 100644 --- a/library/asyncio-policy.po +++ b/library/asyncio-policy.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-02-24 17:22+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -158,7 +158,7 @@ msgid "" msgstr "" #: library/asyncio-policy.rst:139 -msgid ":ref:`Availability `: Windows." +msgid "Availability" msgstr "" #: library/asyncio-policy.rst:136 @@ -383,3 +383,19 @@ msgid "" "`DefaultEventLoopPolicy` and override the methods for which custom behavior " "is wanted, e.g.::" msgstr "" + +#: library/asyncio-policy.rst:317 +msgid "" +"class MyEventLoopPolicy(asyncio.DefaultEventLoopPolicy):\n" +"\n" +" def get_event_loop(self):\n" +" \"\"\"Get the event loop.\n" +"\n" +" This may be None or an instance of EventLoop.\n" +" \"\"\"\n" +" loop = super().get_event_loop()\n" +" # Do something with loop ...\n" +" return loop\n" +"\n" +"asyncio.set_event_loop_policy(MyEventLoopPolicy())" +msgstr "" diff --git a/library/asyncio-protocol.po b/library/asyncio-protocol.po index c4842f056..2367a2b61 100644 --- a/library/asyncio-protocol.po +++ b/library/asyncio-protocol.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-02-24 17:22+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -259,6 +259,13 @@ msgid "" "of the transport::" msgstr "" +#: library/asyncio-protocol.rst:182 +msgid "" +"sock = transport.get_extra_info('socket')\n" +"if sock is not None:\n" +" print(sock.getsockopt(...))" +msgstr "" + #: library/asyncio-protocol.rst:186 msgid "Categories of information that can be queried on some transports:" msgstr "" @@ -780,6 +787,14 @@ msgstr "" msgid "State machine:" msgstr "" +#: library/asyncio-protocol.rst:580 +msgid "" +"start -> connection_made\n" +" [-> data_received]*\n" +" [-> eof_received]?\n" +"-> connection_lost -> end" +msgstr "" + #: library/asyncio-protocol.rst:589 msgid "Buffered Streaming Protocols" msgstr "" @@ -846,6 +861,16 @@ msgid "" "won't be called after it." msgstr "" +#: library/asyncio-protocol.rst:638 +msgid "" +"start -> connection_made\n" +" [-> get_buffer\n" +" [-> buffer_updated]?\n" +" ]*\n" +" [-> eof_received]?\n" +"-> connection_lost -> end" +msgstr "" + #: library/asyncio-protocol.rst:649 msgid "Datagram Protocols" msgstr "" @@ -948,6 +973,44 @@ msgid "" "back received data, and close the connection::" msgstr "" +#: library/asyncio-protocol.rst:726 +msgid "" +"import asyncio\n" +"\n" +"\n" +"class EchoServerProtocol(asyncio.Protocol):\n" +" def connection_made(self, transport):\n" +" peername = transport.get_extra_info('peername')\n" +" print('Connection from {}'.format(peername))\n" +" self.transport = transport\n" +"\n" +" def data_received(self, data):\n" +" message = data.decode()\n" +" print('Data received: {!r}'.format(message))\n" +"\n" +" print('Send: {!r}'.format(message))\n" +" self.transport.write(data)\n" +"\n" +" print('Close the client socket')\n" +" self.transport.close()\n" +"\n" +"\n" +"async def main():\n" +" # Get a reference to the event loop as we plan to use\n" +" # low-level APIs.\n" +" loop = asyncio.get_running_loop()\n" +"\n" +" server = await loop.create_server(\n" +" lambda: EchoServerProtocol(),\n" +" '127.0.0.1', 8888)\n" +"\n" +" async with server:\n" +" await server.serve_forever()\n" +"\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: library/asyncio-protocol.rst:764 msgid "" "The :ref:`TCP echo server using streams ` " @@ -964,6 +1027,51 @@ msgid "" "data, and waits until the connection is closed::" msgstr "" +#: library/asyncio-protocol.rst:775 +msgid "" +"import asyncio\n" +"\n" +"\n" +"class EchoClientProtocol(asyncio.Protocol):\n" +" def __init__(self, message, on_con_lost):\n" +" self.message = message\n" +" self.on_con_lost = on_con_lost\n" +"\n" +" def connection_made(self, transport):\n" +" transport.write(self.message.encode())\n" +" print('Data sent: {!r}'.format(self.message))\n" +"\n" +" def data_received(self, data):\n" +" print('Data received: {!r}'.format(data.decode()))\n" +"\n" +" def connection_lost(self, exc):\n" +" print('The server closed the connection')\n" +" self.on_con_lost.set_result(True)\n" +"\n" +"\n" +"async def main():\n" +" # Get a reference to the event loop as we plan to use\n" +" # low-level APIs.\n" +" loop = asyncio.get_running_loop()\n" +"\n" +" on_con_lost = loop.create_future()\n" +" message = 'Hello World!'\n" +"\n" +" transport, protocol = await loop.create_connection(\n" +" lambda: EchoClientProtocol(message, on_con_lost),\n" +" '127.0.0.1', 8888)\n" +"\n" +" # Wait until the protocol signals that the connection\n" +" # is lost and close the transport.\n" +" try:\n" +" await on_con_lost\n" +" finally:\n" +" transport.close()\n" +"\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: library/asyncio-protocol.rst:820 msgid "" "The :ref:`TCP echo client using streams ` " @@ -980,6 +1088,44 @@ msgid "" "sends back received data::" msgstr "" +#: library/asyncio-protocol.rst:832 +msgid "" +"import asyncio\n" +"\n" +"\n" +"class EchoServerProtocol:\n" +" def connection_made(self, transport):\n" +" self.transport = transport\n" +"\n" +" def datagram_received(self, data, addr):\n" +" message = data.decode()\n" +" print('Received %r from %s' % (message, addr))\n" +" print('Send %r to %s' % (message, addr))\n" +" self.transport.sendto(data, addr)\n" +"\n" +"\n" +"async def main():\n" +" print(\"Starting UDP server\")\n" +"\n" +" # Get a reference to the event loop as we plan to use\n" +" # low-level APIs.\n" +" loop = asyncio.get_running_loop()\n" +"\n" +" # One protocol instance will be created to serve all\n" +" # client requests.\n" +" transport, protocol = await loop.create_datagram_endpoint(\n" +" lambda: EchoServerProtocol(),\n" +" local_addr=('127.0.0.1', 9999))\n" +"\n" +" try:\n" +" await asyncio.sleep(3600) # Serve for 1 hour.\n" +" finally:\n" +" transport.close()\n" +"\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: library/asyncio-protocol.rst:871 msgid "UDP Echo Client" msgstr "" @@ -990,6 +1136,57 @@ msgid "" "sends data and closes the transport when it receives the answer::" msgstr "" +#: library/asyncio-protocol.rst:876 +msgid "" +"import asyncio\n" +"\n" +"\n" +"class EchoClientProtocol:\n" +" def __init__(self, message, on_con_lost):\n" +" self.message = message\n" +" self.on_con_lost = on_con_lost\n" +" self.transport = None\n" +"\n" +" def connection_made(self, transport):\n" +" self.transport = transport\n" +" print('Send:', self.message)\n" +" self.transport.sendto(self.message.encode())\n" +"\n" +" def datagram_received(self, data, addr):\n" +" print(\"Received:\", data.decode())\n" +"\n" +" print(\"Close the socket\")\n" +" self.transport.close()\n" +"\n" +" def error_received(self, exc):\n" +" print('Error received:', exc)\n" +"\n" +" def connection_lost(self, exc):\n" +" print(\"Connection closed\")\n" +" self.on_con_lost.set_result(True)\n" +"\n" +"\n" +"async def main():\n" +" # Get a reference to the event loop as we plan to use\n" +" # low-level APIs.\n" +" loop = asyncio.get_running_loop()\n" +"\n" +" on_con_lost = loop.create_future()\n" +" message = \"Hello World!\"\n" +"\n" +" transport, protocol = await loop.create_datagram_endpoint(\n" +" lambda: EchoClientProtocol(message, on_con_lost),\n" +" remote_addr=('127.0.0.1', 9999))\n" +"\n" +" try:\n" +" await on_con_lost\n" +" finally:\n" +" transport.close()\n" +"\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: library/asyncio-protocol.rst:928 msgid "Connecting Existing Sockets" msgstr "" @@ -1000,6 +1197,58 @@ msgid "" "method with a protocol::" msgstr "" +#: library/asyncio-protocol.rst:933 +msgid "" +"import asyncio\n" +"import socket\n" +"\n" +"\n" +"class MyProtocol(asyncio.Protocol):\n" +"\n" +" def __init__(self, on_con_lost):\n" +" self.transport = None\n" +" self.on_con_lost = on_con_lost\n" +"\n" +" def connection_made(self, transport):\n" +" self.transport = transport\n" +"\n" +" def data_received(self, data):\n" +" print(\"Received:\", data.decode())\n" +"\n" +" # We are done: close the transport;\n" +" # connection_lost() will be called automatically.\n" +" self.transport.close()\n" +"\n" +" def connection_lost(self, exc):\n" +" # The socket has been closed\n" +" self.on_con_lost.set_result(True)\n" +"\n" +"\n" +"async def main():\n" +" # Get a reference to the event loop as we plan to use\n" +" # low-level APIs.\n" +" loop = asyncio.get_running_loop()\n" +" on_con_lost = loop.create_future()\n" +"\n" +" # Create a pair of connected sockets\n" +" rsock, wsock = socket.socketpair()\n" +"\n" +" # Register the socket to wait for data.\n" +" transport, protocol = await loop.create_connection(\n" +" lambda: MyProtocol(on_con_lost), sock=rsock)\n" +"\n" +" # Simulate the reception of data from the network.\n" +" loop.call_soon(wsock.send, 'abc'.encode())\n" +"\n" +" try:\n" +" await protocol.on_con_lost\n" +" finally:\n" +" transport.close()\n" +" wsock.close()\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: library/asyncio-protocol.rst:984 msgid "" "The :ref:`watch a file descriptor for read events " @@ -1028,6 +1277,67 @@ msgstr "" msgid "The subprocess is created by the :meth:`loop.subprocess_exec` method::" msgstr "" +#: library/asyncio-protocol.rst:1002 +msgid "" +"import asyncio\n" +"import sys\n" +"\n" +"class DateProtocol(asyncio.SubprocessProtocol):\n" +" def __init__(self, exit_future):\n" +" self.exit_future = exit_future\n" +" self.output = bytearray()\n" +" self.pipe_closed = False\n" +" self.exited = False\n" +"\n" +" def pipe_connection_lost(self, fd, exc):\n" +" self.pipe_closed = True\n" +" self.check_for_exit()\n" +"\n" +" def pipe_data_received(self, fd, data):\n" +" self.output.extend(data)\n" +"\n" +" def process_exited(self):\n" +" self.exited = True\n" +" # process_exited() method can be called before\n" +" # pipe_connection_lost() method: wait until both methods are\n" +" # called.\n" +" self.check_for_exit()\n" +"\n" +" def check_for_exit(self):\n" +" if self.pipe_closed and self.exited:\n" +" self.exit_future.set_result(True)\n" +"\n" +"async def get_date():\n" +" # Get a reference to the event loop as we plan to use\n" +" # low-level APIs.\n" +" loop = asyncio.get_running_loop()\n" +"\n" +" code = 'import datetime; print(datetime.datetime.now())'\n" +" exit_future = asyncio.Future(loop=loop)\n" +"\n" +" # Create the subprocess controlled by DateProtocol;\n" +" # redirect the standard output into a pipe.\n" +" transport, protocol = await loop.subprocess_exec(\n" +" lambda: DateProtocol(exit_future),\n" +" sys.executable, '-c', code,\n" +" stdin=None, stderr=None)\n" +"\n" +" # Wait for the subprocess exit using the process_exited()\n" +" # method of the protocol.\n" +" await exit_future\n" +"\n" +" # Close the stdout pipe.\n" +" transport.close()\n" +"\n" +" # Read the output which was collected by the\n" +" # pipe_data_received() method of the protocol.\n" +" data = bytes(protocol.output)\n" +" return data.decode('ascii').rstrip()\n" +"\n" +"date = asyncio.run(get_date())\n" +"print(f\"Current date: {date}\")" +msgstr "" + #: library/asyncio-protocol.rst:1060 msgid "" "See also the :ref:`same example ` " diff --git a/library/asyncio-queue.po b/library/asyncio-queue.po index 0b601c1bd..ec790f8d4 100644 --- a/library/asyncio-queue.po +++ b/library/asyncio-queue.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2022-12-17 01:28+0300\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -85,7 +85,7 @@ msgstr "" #: library/asyncio-queue.rst:57 msgid "" "If the queue was initialized with ``maxsize=0`` (the default), then :meth:" -"`full()` never returns ``True``." +"`full` never returns ``True``." msgstr "" #: library/asyncio-queue.rst:62 @@ -202,3 +202,60 @@ msgstr "" msgid "" "Queues can be used to distribute workload between several concurrent tasks::" msgstr "" + +#: library/asyncio-queue.rst:156 +msgid "" +"import asyncio\n" +"import random\n" +"import time\n" +"\n" +"\n" +"async def worker(name, queue):\n" +" while True:\n" +" # Get a \"work item\" out of the queue.\n" +" sleep_for = await queue.get()\n" +"\n" +" # Sleep for the \"sleep_for\" seconds.\n" +" await asyncio.sleep(sleep_for)\n" +"\n" +" # Notify the queue that the \"work item\" has been processed.\n" +" queue.task_done()\n" +"\n" +" print(f'{name} has slept for {sleep_for:.2f} seconds')\n" +"\n" +"\n" +"async def main():\n" +" # Create a queue that we will use to store our \"workload\".\n" +" queue = asyncio.Queue()\n" +"\n" +" # Generate random timings and put them into the queue.\n" +" total_sleep_time = 0\n" +" for _ in range(20):\n" +" sleep_for = random.uniform(0.05, 1.0)\n" +" total_sleep_time += sleep_for\n" +" queue.put_nowait(sleep_for)\n" +"\n" +" # Create three worker tasks to process the queue concurrently.\n" +" tasks = []\n" +" for i in range(3):\n" +" task = asyncio.create_task(worker(f'worker-{i}', queue))\n" +" tasks.append(task)\n" +"\n" +" # Wait until the queue is fully processed.\n" +" started_at = time.monotonic()\n" +" await queue.join()\n" +" total_slept_for = time.monotonic() - started_at\n" +"\n" +" # Cancel our worker tasks.\n" +" for task in tasks:\n" +" task.cancel()\n" +" # Wait until all worker tasks are cancelled.\n" +" await asyncio.gather(*tasks, return_exceptions=True)\n" +"\n" +" print('====')\n" +" print(f'3 workers slept in parallel for {total_slept_for:.2f} seconds')\n" +" print(f'total expected sleep time: {total_sleep_time:.2f} seconds')\n" +"\n" +"\n" +"asyncio.run(main())" +msgstr "" diff --git a/library/asyncio-runner.po b/library/asyncio-runner.po index 46c1a6903..7bd8556f5 100644 --- a/library/asyncio-runner.po +++ b/library/asyncio-runner.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-09-18 22:33+0300\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -82,6 +82,15 @@ msgstr "" msgid "Example::" msgstr "" +#: library/asyncio-runner.rst:52 +msgid "" +"async def main():\n" +" await asyncio.sleep(1)\n" +" print('hello')\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: library/asyncio-runner.rst:60 msgid "Updated to use :meth:`loop.shutdown_default_executor`." msgstr "" @@ -121,10 +130,20 @@ msgstr "" #: library/asyncio-runner.rst:92 msgid "" -"Basically, :func:`asyncio.run()` example can be rewritten with the runner " +"Basically, :func:`asyncio.run` example can be rewritten with the runner " "usage::" msgstr "" +#: library/asyncio-runner.rst:94 +msgid "" +"async def main():\n" +" await asyncio.sleep(1)\n" +" print('hello')\n" +"\n" +"with asyncio.Runner() as runner:\n" +" runner.run(main())" +msgstr "" + #: library/asyncio-runner.rst:105 msgid "Run a :term:`coroutine ` *coro* in the embedded loop." msgstr "" diff --git a/library/asyncio-stream.po b/library/asyncio-stream.po index e2d2710bb..d428e415d 100644 --- a/library/asyncio-stream.po +++ b/library/asyncio-stream.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-02-24 17:22+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -35,6 +35,28 @@ msgstr "" msgid "Here is an example of a TCP echo client written using asyncio streams::" msgstr "" +#: library/asyncio-stream.rst:404 +msgid "" +"import asyncio\n" +"\n" +"async def tcp_echo_client(message):\n" +" reader, writer = await asyncio.open_connection(\n" +" '127.0.0.1', 8888)\n" +"\n" +" print(f'Send: {message!r}')\n" +" writer.write(message.encode())\n" +" await writer.drain()\n" +"\n" +" data = await reader.read(100)\n" +" print(f'Received: {data.decode()!r}')\n" +"\n" +" print('Close the connection')\n" +" writer.close()\n" +" await writer.wait_closed()\n" +"\n" +"asyncio.run(tcp_echo_client('Hello World!'))" +msgstr "" + #: library/asyncio-stream.rst:42 msgid "See also the `Examples`_ section below." msgstr "" @@ -149,7 +171,7 @@ msgid "See also the documentation of :meth:`loop.create_unix_connection`." msgstr "" #: library/asyncio-stream.rst:181 -msgid ":ref:`Availability `: Unix." +msgid "Availability" msgstr "" #: library/asyncio-stream.rst:153 @@ -302,6 +324,12 @@ msgstr "" msgid "The method should be used along with the ``drain()`` method::" msgstr "" +#: library/asyncio-stream.rst:291 +msgid "" +"stream.write(data)\n" +"await stream.drain()" +msgstr "" + #: library/asyncio-stream.rst:296 msgid "" "The method writes a list (or any iterable) of bytes to the underlying socket " @@ -309,6 +337,12 @@ msgid "" "until it can be sent." msgstr "" +#: library/asyncio-stream.rst:303 +msgid "" +"stream.writelines(lines)\n" +"await stream.drain()" +msgstr "" + #: library/asyncio-stream.rst:308 msgid "The method closes the stream and the underlying socket." msgstr "" @@ -319,6 +353,12 @@ msgid "" "``wait_closed()`` method::" msgstr "" +#: library/asyncio-stream.rst:313 +msgid "" +"stream.close()\n" +"await stream.wait_closed()" +msgstr "" + #: library/asyncio-stream.rst:318 msgid "" "Return ``True`` if the underlying transport supports the :meth:`write_eof` " @@ -344,6 +384,12 @@ msgstr "" msgid "Wait until it is appropriate to resume writing to the stream. Example::" msgstr "" +#: library/asyncio-stream.rst:340 +msgid "" +"writer.write(data)\n" +"await writer.drain()" +msgstr "" + #: library/asyncio-stream.rst:343 msgid "" "This is a flow control method that interacts with the underlying IO write " @@ -428,6 +474,38 @@ msgstr "" msgid "TCP echo server using the :func:`asyncio.start_server` function::" msgstr "" +#: library/asyncio-stream.rst:437 +msgid "" +"import asyncio\n" +"\n" +"async def handle_echo(reader, writer):\n" +" data = await reader.read(100)\n" +" message = data.decode()\n" +" addr = writer.get_extra_info('peername')\n" +"\n" +" print(f\"Received {message!r} from {addr!r}\")\n" +"\n" +" print(f\"Send: {message!r}\")\n" +" writer.write(data)\n" +" await writer.drain()\n" +"\n" +" print(\"Close the connection\")\n" +" writer.close()\n" +" await writer.wait_closed()\n" +"\n" +"async def main():\n" +" server = await asyncio.start_server(\n" +" handle_echo, '127.0.0.1', 8888)\n" +"\n" +" addrs = ', '.join(str(sock.getsockname()) for sock in server.sockets)\n" +" print(f'Serving on {addrs}')\n" +"\n" +" async with server:\n" +" await server.serve_forever()\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: library/asyncio-stream.rst:469 msgid "" "The :ref:`TCP echo server protocol " @@ -444,14 +522,61 @@ msgid "" "Simple example querying HTTP headers of the URL passed on the command line::" msgstr "" +#: library/asyncio-stream.rst:478 +msgid "" +"import asyncio\n" +"import urllib.parse\n" +"import sys\n" +"\n" +"async def print_http_headers(url):\n" +" url = urllib.parse.urlsplit(url)\n" +" if url.scheme == 'https':\n" +" reader, writer = await asyncio.open_connection(\n" +" url.hostname, 443, ssl=True)\n" +" else:\n" +" reader, writer = await asyncio.open_connection(\n" +" url.hostname, 80)\n" +"\n" +" query = (\n" +" f\"HEAD {url.path or '/'} HTTP/1.0\\r\\n\"\n" +" f\"Host: {url.hostname}\\r\\n\"\n" +" f\"\\r\\n\"\n" +" )\n" +"\n" +" writer.write(query.encode('latin-1'))\n" +" while True:\n" +" line = await reader.readline()\n" +" if not line:\n" +" break\n" +"\n" +" line = line.decode('latin1').rstrip()\n" +" if line:\n" +" print(f'HTTP header> {line}')\n" +"\n" +" # Ignore the body, close the socket\n" +" writer.close()\n" +" await writer.wait_closed()\n" +"\n" +"url = sys.argv[1]\n" +"asyncio.run(print_http_headers(url))" +msgstr "" + #: library/asyncio-stream.rst:515 msgid "Usage::" msgstr "" +#: library/asyncio-stream.rst:517 +msgid "python example.py http://example.com/path/page.html" +msgstr "" + #: library/asyncio-stream.rst:519 msgid "or with HTTPS::" msgstr "" +#: library/asyncio-stream.rst:521 +msgid "python example.py https://example.com/path/page.html" +msgstr "" + #: library/asyncio-stream.rst:527 msgid "Register an open socket to wait for data using streams" msgstr "" @@ -462,6 +587,39 @@ msgid "" "`open_connection` function::" msgstr "" +#: library/asyncio-stream.rst:532 +msgid "" +"import asyncio\n" +"import socket\n" +"\n" +"async def wait_for_data():\n" +" # Get a reference to the current event loop because\n" +" # we want to access low-level APIs.\n" +" loop = asyncio.get_running_loop()\n" +"\n" +" # Create a pair of connected sockets.\n" +" rsock, wsock = socket.socketpair()\n" +"\n" +" # Register the open socket to wait for data.\n" +" reader, writer = await asyncio.open_connection(sock=rsock)\n" +"\n" +" # Simulate the reception of data from the network\n" +" loop.call_soon(wsock.send, 'abc'.encode())\n" +"\n" +" # Wait for data\n" +" data = await reader.read(100)\n" +"\n" +" # Got data, we are done: close the socket\n" +" print(\"Received:\", data.decode())\n" +" writer.close()\n" +" await writer.wait_closed()\n" +"\n" +" # Close the second socket\n" +" wsock.close()\n" +"\n" +"asyncio.run(wait_for_data())" +msgstr "" + #: library/asyncio-stream.rst:564 msgid "" "The :ref:`register an open socket to wait for data using a protocol " diff --git a/library/asyncio-subprocess.po b/library/asyncio-subprocess.po index ae48666c2..5ff1ef5ab 100644 --- a/library/asyncio-subprocess.po +++ b/library/asyncio-subprocess.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-02-24 17:22+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -38,10 +38,38 @@ msgid "" "result::" msgstr "" +#: library/asyncio-subprocess.rst:22 +msgid "" +"import asyncio\n" +"\n" +"async def run(cmd):\n" +" proc = await asyncio.create_subprocess_shell(\n" +" cmd,\n" +" stdout=asyncio.subprocess.PIPE,\n" +" stderr=asyncio.subprocess.PIPE)\n" +"\n" +" stdout, stderr = await proc.communicate()\n" +"\n" +" print(f'[{cmd!r} exited with {proc.returncode}]')\n" +" if stdout:\n" +" print(f'[stdout]\\n{stdout.decode()}')\n" +" if stderr:\n" +" print(f'[stderr]\\n{stderr.decode()}')\n" +"\n" +"asyncio.run(run('ls /zzz'))" +msgstr "" + #: library/asyncio-subprocess.rst:40 msgid "will print::" msgstr "" +#: library/asyncio-subprocess.rst:42 +msgid "" +"['ls /zzz' exited with 1]\n" +"[stderr]\n" +"ls: /zzz: No such file or directory" +msgstr "" + #: library/asyncio-subprocess.rst:46 msgid "" "Because all asyncio subprocess functions are asynchronous and asyncio " @@ -50,6 +78,16 @@ msgid "" "the above example to run several commands simultaneously::" msgstr "" +#: library/asyncio-subprocess.rst:51 +msgid "" +"async def main():\n" +" await asyncio.gather(\n" +" run('ls /zzz'),\n" +" run('sleep 1; echo \"hello\"'))\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: library/asyncio-subprocess.rst:58 msgid "See also the `Examples`_ subsection." msgstr "" @@ -435,6 +473,32 @@ msgid "" "The subprocess is created by the :func:`create_subprocess_exec` function::" msgstr "" +#: library/asyncio-subprocess.rst:352 +msgid "" +"import asyncio\n" +"import sys\n" +"\n" +"async def get_date():\n" +" code = 'import datetime; print(datetime.datetime.now())'\n" +"\n" +" # Create the subprocess; redirect the standard output\n" +" # into a pipe.\n" +" proc = await asyncio.create_subprocess_exec(\n" +" sys.executable, '-c', code,\n" +" stdout=asyncio.subprocess.PIPE)\n" +"\n" +" # Read one line of output.\n" +" data = await proc.stdout.readline()\n" +" line = data.decode('ascii').rstrip()\n" +"\n" +" # Wait for the subprocess exit.\n" +" await proc.wait()\n" +" return line\n" +"\n" +"date = asyncio.run(get_date())\n" +"print(f\"Current date: {date}\")" +msgstr "" + #: library/asyncio-subprocess.rst:376 msgid "" "See also the :ref:`same example ` written " diff --git a/library/asyncio-sync.po b/library/asyncio-sync.po index 2dd2ff5f8..5a4b50d58 100644 --- a/library/asyncio-sync.po +++ b/library/asyncio-sync.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2022-12-17 01:28+0300\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -89,10 +89,31 @@ msgstr "" msgid "The preferred way to use a Lock is an :keyword:`async with` statement::" msgstr "" +#: library/asyncio-sync.rst:50 +msgid "" +"lock = asyncio.Lock()\n" +"\n" +"# ... later\n" +"async with lock:\n" +" # access shared state" +msgstr "" + #: library/asyncio-sync.rst:199 library/asyncio-sync.rst:298 msgid "which is equivalent to::" msgstr "" +#: library/asyncio-sync.rst:58 +msgid "" +"lock = asyncio.Lock()\n" +"\n" +"# ... later\n" +"await lock.acquire()\n" +"try:\n" +" # access shared state\n" +"finally:\n" +" lock.release()" +msgstr "" + #: library/asyncio-sync.rst:112 library/asyncio-sync.rst:286 #: library/asyncio-sync.rst:341 msgid "Removed the *loop* parameter." @@ -162,6 +183,30 @@ msgstr "" msgid "Example::" msgstr "" +#: library/asyncio-sync.rst:119 +msgid "" +"async def waiter(event):\n" +" print('waiting for it ...')\n" +" await event.wait()\n" +" print('... got it!')\n" +"\n" +"async def main():\n" +" # Create an Event object.\n" +" event = asyncio.Event()\n" +"\n" +" # Spawn a Task to wait until 'event' is set.\n" +" waiter_task = asyncio.create_task(waiter(event))\n" +"\n" +" # Sleep for 1 second and set the event.\n" +" await asyncio.sleep(1)\n" +" event.set()\n" +"\n" +" # Wait until the waiter task is finished.\n" +" await waiter_task\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: library/asyncio-sync.rst:142 msgid "Wait until the event is set." msgstr "" @@ -228,6 +273,27 @@ msgid "" "The preferred way to use a Condition is an :keyword:`async with` statement::" msgstr "" +#: library/asyncio-sync.rst:193 +msgid "" +"cond = asyncio.Condition()\n" +"\n" +"# ... later\n" +"async with cond:\n" +" await cond.wait()" +msgstr "" + +#: library/asyncio-sync.rst:201 +msgid "" +"cond = asyncio.Condition()\n" +"\n" +"# ... later\n" +"await cond.acquire()\n" +"try:\n" +" await cond.wait()\n" +"finally:\n" +" cond.release()" +msgstr "" + #: library/asyncio-sync.rst:212 msgid "Acquire the underlying lock." msgstr "" @@ -326,6 +392,27 @@ msgid "" "The preferred way to use a Semaphore is an :keyword:`async with` statement::" msgstr "" +#: library/asyncio-sync.rst:292 +msgid "" +"sem = asyncio.Semaphore(10)\n" +"\n" +"# ... later\n" +"async with sem:\n" +" # work with shared resource" +msgstr "" + +#: library/asyncio-sync.rst:300 +msgid "" +"sem = asyncio.Semaphore(10)\n" +"\n" +"# ... later\n" +"await sem.acquire()\n" +"try:\n" +" # work with shared resource\n" +"finally:\n" +" sem.release()" +msgstr "" + #: library/asyncio-sync.rst:311 msgid "Acquire a semaphore." msgstr "" @@ -395,10 +482,42 @@ msgstr "" msgid "The barrier can be reused any number of times." msgstr "" +#: library/asyncio-sync.rst:367 +msgid "" +"async def example_barrier():\n" +" # barrier with 3 parties\n" +" b = asyncio.Barrier(3)\n" +"\n" +" # create 2 new waiting tasks\n" +" asyncio.create_task(b.wait())\n" +" asyncio.create_task(b.wait())\n" +"\n" +" await asyncio.sleep(0)\n" +" print(b)\n" +"\n" +" # The third .wait() call passes the barrier\n" +" await b.wait()\n" +" print(b)\n" +" print(\"barrier passed\")\n" +"\n" +" await asyncio.sleep(0)\n" +" print(b)\n" +"\n" +"asyncio.run(example_barrier())" +msgstr "" + #: library/asyncio-sync.rst:388 msgid "Result of this example is::" msgstr "" +#: library/asyncio-sync.rst:390 +msgid "" +"\n" +"\n" +"barrier passed\n" +"" +msgstr "" + #: library/asyncio-sync.rst:399 msgid "" "Pass the barrier. When all the tasks party to the barrier have called this " @@ -419,6 +538,15 @@ msgid "" "housekeeping, e.g.::" msgstr "" +#: library/asyncio-sync.rst:411 +msgid "" +"...\n" +"async with barrier as position:\n" +" if position == 0:\n" +" # Only one task prints this\n" +" print('End of *draining phase*')" +msgstr "" + #: library/asyncio-sync.rst:417 msgid "" "This method may raise a :class:`BrokenBarrierError` exception if the barrier " diff --git a/library/asyncio-task.po b/library/asyncio-task.po index 3ed3cf890..99a80e741 100644 --- a/library/asyncio-task.po +++ b/library/asyncio-task.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -41,11 +41,31 @@ msgid "" "snippet of code prints \"hello\", waits 1 second, and then prints \"world\"::" msgstr "" +#: library/asyncio-task.rst:30 +msgid "" +">>> import asyncio\n" +"\n" +">>> async def main():\n" +"... print('hello')\n" +"... await asyncio.sleep(1)\n" +"... print('world')\n" +"\n" +">>> asyncio.run(main())\n" +"hello\n" +"world" +msgstr "" + #: library/asyncio-task.rst:41 msgid "" "Note that simply calling a coroutine will not schedule it to be executed::" msgstr "" +#: library/asyncio-task.rst:44 +msgid "" +">>> main()\n" +"" +msgstr "" + #: library/asyncio-task.rst:47 msgid "To actually run a coroutine, asyncio provides the following mechanisms:" msgstr "" @@ -63,10 +83,38 @@ msgid "" "*another* 2 seconds::" msgstr "" +#: library/asyncio-task.rst:56 +msgid "" +"import asyncio\n" +"import time\n" +"\n" +"async def say_after(delay, what):\n" +" await asyncio.sleep(delay)\n" +" print(what)\n" +"\n" +"async def main():\n" +" print(f\"started at {time.strftime('%X')}\")\n" +"\n" +" await say_after(1, 'hello')\n" +" await say_after(2, 'world')\n" +"\n" +" print(f\"finished at {time.strftime('%X')}\")\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: library/asyncio-task.rst:73 msgid "Expected output::" msgstr "" +#: library/asyncio-task.rst:75 +msgid "" +"started at 17:13:52\n" +"hello\n" +"world\n" +"finished at 17:13:55" +msgstr "" + #: library/asyncio-task.rst:80 msgid "" "The :func:`asyncio.create_task` function to run coroutines concurrently as " @@ -79,18 +127,62 @@ msgid "" "*concurrently*::" msgstr "" +#: library/asyncio-task.rst:86 +msgid "" +"async def main():\n" +" task1 = asyncio.create_task(\n" +" say_after(1, 'hello'))\n" +"\n" +" task2 = asyncio.create_task(\n" +" say_after(2, 'world'))\n" +"\n" +" print(f\"started at {time.strftime('%X')}\")\n" +"\n" +" # Wait until both tasks are completed (should take\n" +" # around 2 seconds.)\n" +" await task1\n" +" await task2\n" +"\n" +" print(f\"finished at {time.strftime('%X')}\")" +msgstr "" + #: library/asyncio-task.rst:102 msgid "" "Note that expected output now shows that the snippet runs 1 second faster " "than before::" msgstr "" +#: library/asyncio-task.rst:105 +msgid "" +"started at 17:14:32\n" +"hello\n" +"world\n" +"finished at 17:14:34" +msgstr "" + #: library/asyncio-task.rst:110 msgid "" "The :class:`asyncio.TaskGroup` class provides a more modern alternative to :" "func:`create_task`. Using this API, the last example becomes::" msgstr "" +#: library/asyncio-task.rst:114 +msgid "" +"async def main():\n" +" async with asyncio.TaskGroup() as tg:\n" +" task1 = tg.create_task(\n" +" say_after(1, 'hello'))\n" +"\n" +" task2 = tg.create_task(\n" +" say_after(2, 'world'))\n" +"\n" +" print(f\"started at {time.strftime('%X')}\")\n" +"\n" +" # The await is implicit when the context manager exits.\n" +"\n" +" print(f\"finished at {time.strftime('%X')}\")" +msgstr "" + #: library/asyncio-task.rst:128 msgid "The timing and output should be the same as for the previous version." msgstr "" @@ -122,6 +214,25 @@ msgid "" "coroutines::" msgstr "" +#: library/asyncio-task.rst:152 +msgid "" +"import asyncio\n" +"\n" +"async def nested():\n" +" return 42\n" +"\n" +"async def main():\n" +" # Nothing happens if we just call \"nested()\".\n" +" # A coroutine object is created but not awaited,\n" +" # so it *won't run at all*.\n" +" nested() # will raise a \"RuntimeWarning\".\n" +"\n" +" # Let's do it differently now and await it:\n" +" print(await nested()) # will print \"42\".\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: library/asyncio-task.rst:170 msgid "" "In this documentation the term \"coroutine\" can be used for two closely " @@ -151,6 +262,25 @@ msgid "" "create_task` the coroutine is automatically scheduled to run soon::" msgstr "" +#: library/asyncio-task.rst:187 +msgid "" +"import asyncio\n" +"\n" +"async def nested():\n" +" return 42\n" +"\n" +"async def main():\n" +" # Schedule nested() to run soon concurrently\n" +" # with \"main()\".\n" +" task = asyncio.create_task(nested())\n" +"\n" +" # \"task\" can now be used to cancel \"nested()\", or\n" +" # can simply be awaited to wait until it is complete:\n" +" await task\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: library/asyncio-task.rst:205 msgid "Futures" msgstr "" @@ -185,6 +315,18 @@ msgid "" "awaited::" msgstr "" +#: library/asyncio-task.rst:221 +msgid "" +"async def main():\n" +" await function_that_returns_a_future_object()\n" +"\n" +" # this is also valid:\n" +" await asyncio.gather(\n" +" function_that_returns_a_future_object(),\n" +" some_python_coroutine()\n" +" )" +msgstr "" + #: library/asyncio-task.rst:230 msgid "" "A good example of a low-level function that returns a Future object is :meth:" @@ -240,11 +382,27 @@ msgid "" "tasks, gather them in a collection::" msgstr "" -#: library/asyncio-task.rst:1075 +#: library/asyncio-task.rst:272 +msgid "" +"background_tasks = set()\n" +"\n" +"for i in range(10):\n" +" task = asyncio.create_task(some_coro(param=i))\n" +"\n" +" # Add task to the set. This creates a strong reference.\n" +" background_tasks.add(task)\n" +"\n" +" # To prevent keeping references to finished tasks forever,\n" +" # make each task remove its own reference from the set after\n" +" # completion:\n" +" task.add_done_callback(background_tasks.discard)" +msgstr "" + +#: library/asyncio-task.rst:1122 msgid "Added the *name* parameter." msgstr "" -#: library/asyncio-task.rst:1082 +#: library/asyncio-task.rst:1129 msgid "Added the *context* parameter." msgstr "" @@ -301,11 +459,21 @@ msgid "" "`asyncio.create_task`." msgstr "" -#: library/asyncio-task.rst:472 library/asyncio-task.rst:703 -#: library/asyncio-task.rst:769 library/asyncio-task.rst:868 +#: library/asyncio-task.rst:519 library/asyncio-task.rst:750 +#: library/asyncio-task.rst:816 library/asyncio-task.rst:915 msgid "Example::" msgstr "" +#: library/asyncio-task.rst:340 +msgid "" +"async def main():\n" +" async with asyncio.TaskGroup() as tg:\n" +" task1 = tg.create_task(some_coro(...))\n" +" task2 = tg.create_task(another_coro(...))\n" +" print(f\"Both tasks have completed now: {task1.result()}, {task2." +"result()}\")" +msgstr "" + #: library/asyncio-task.rst:346 msgid "" "The ``async with`` statement will wait for all tasks in the group to finish. " @@ -357,65 +525,137 @@ msgid "" msgstr "" #: library/asyncio-task.rst:390 +msgid "Terminating a Task Group" +msgstr "" + +#: library/asyncio-task.rst:392 +msgid "" +"While terminating a task group is not natively supported by the standard " +"library, termination can be achieved by adding an exception-raising task to " +"the task group and ignoring the raised exception:" +msgstr "" + +#: library/asyncio-task.rst:396 +msgid "" +"import asyncio\n" +"from asyncio import TaskGroup\n" +"\n" +"class TerminateTaskGroup(Exception):\n" +" \"\"\"Exception raised to terminate a task group.\"\"\"\n" +"\n" +"async def force_terminate_task_group():\n" +" \"\"\"Used to force termination of a task group.\"\"\"\n" +" raise TerminateTaskGroup()\n" +"\n" +"async def job(task_id, sleep_time):\n" +" print(f'Task {task_id}: start')\n" +" await asyncio.sleep(sleep_time)\n" +" print(f'Task {task_id}: done')\n" +"\n" +"async def main():\n" +" try:\n" +" async with TaskGroup() as group:\n" +" # spawn some tasks\n" +" group.create_task(job(1, 0.5))\n" +" group.create_task(job(2, 1.5))\n" +" # sleep for 1 second\n" +" await asyncio.sleep(1)\n" +" # add an exception-raising task to force the group to terminate\n" +" group.create_task(force_terminate_task_group())\n" +" except* TerminateTaskGroup:\n" +" pass\n" +"\n" +"asyncio.run(main())" +msgstr "" + +#: library/asyncio-task.rst:428 +msgid "Expected output:" +msgstr "" + +#: library/asyncio-task.rst:430 +msgid "" +"Task 1: start\n" +"Task 2: start\n" +"Task 1: done" +msgstr "" + +#: library/asyncio-task.rst:437 msgid "Sleeping" msgstr "" -#: library/asyncio-task.rst:394 +#: library/asyncio-task.rst:441 msgid "Block for *delay* seconds." msgstr "" -#: library/asyncio-task.rst:396 +#: library/asyncio-task.rst:443 msgid "" "If *result* is provided, it is returned to the caller when the coroutine " "completes." msgstr "" -#: library/asyncio-task.rst:399 +#: library/asyncio-task.rst:446 msgid "" "``sleep()`` always suspends the current task, allowing other tasks to run." msgstr "" -#: library/asyncio-task.rst:402 +#: library/asyncio-task.rst:449 msgid "" "Setting the delay to 0 provides an optimized path to allow other tasks to " "run. This can be used by long-running functions to avoid blocking the event " "loop for the full duration of the function call." msgstr "" -#: library/asyncio-task.rst:408 +#: library/asyncio-task.rst:455 msgid "" "Example of coroutine displaying the current date every second for 5 seconds::" msgstr "" -#: library/asyncio-task.rst:521 library/asyncio-task.rst:794 -#: library/asyncio-task.rst:874 +#: library/asyncio-task.rst:458 +msgid "" +"import asyncio\n" +"import datetime\n" +"\n" +"async def display_date():\n" +" loop = asyncio.get_running_loop()\n" +" end_time = loop.time() + 5.0\n" +" while True:\n" +" print(datetime.datetime.now())\n" +" if (loop.time() + 1.0) >= end_time:\n" +" break\n" +" await asyncio.sleep(1)\n" +"\n" +"asyncio.run(display_date())" +msgstr "" + +#: library/asyncio-task.rst:568 library/asyncio-task.rst:841 +#: library/asyncio-task.rst:921 msgid "Removed the *loop* parameter." msgstr "" -#: library/asyncio-task.rst:431 +#: library/asyncio-task.rst:478 msgid "Running Tasks Concurrently" msgstr "" -#: library/asyncio-task.rst:435 +#: library/asyncio-task.rst:482 msgid "" "Run :ref:`awaitable objects ` in the *aws* sequence " "*concurrently*." msgstr "" -#: library/asyncio-task.rst:438 +#: library/asyncio-task.rst:485 msgid "" "If any awaitable in *aws* is a coroutine, it is automatically scheduled as a " "Task." msgstr "" -#: library/asyncio-task.rst:441 +#: library/asyncio-task.rst:488 msgid "" "If all awaitables are completed successfully, the result is an aggregate " "list of returned values. The order of result values corresponds to the " "order of awaitables in *aws*." msgstr "" -#: library/asyncio-task.rst:445 +#: library/asyncio-task.rst:492 msgid "" "If *return_exceptions* is ``False`` (default), the first raised exception is " "immediately propagated to the task that awaits on ``gather()``. Other " @@ -423,19 +663,19 @@ msgid "" "run." msgstr "" -#: library/asyncio-task.rst:450 +#: library/asyncio-task.rst:497 msgid "" "If *return_exceptions* is ``True``, exceptions are treated the same as " "successful results, and aggregated in the result list." msgstr "" -#: library/asyncio-task.rst:453 +#: library/asyncio-task.rst:500 msgid "" "If ``gather()`` is *cancelled*, all submitted awaitables (that have not " "completed yet) are also *cancelled*." msgstr "" -#: library/asyncio-task.rst:456 +#: library/asyncio-task.rst:503 msgid "" "If any Task or Future from the *aws* sequence is *cancelled*, it is treated " "as if it raised :exc:`CancelledError` -- the ``gather()`` call is **not** " @@ -443,7 +683,7 @@ msgid "" "submitted Task/Future to cause other Tasks/Futures to be cancelled." msgstr "" -#: library/asyncio-task.rst:463 +#: library/asyncio-task.rst:510 msgid "" "A new alternative to create and run tasks concurrently and wait for their " "completion is :class:`asyncio.TaskGroup`. *TaskGroup* provides stronger " @@ -453,7 +693,46 @@ msgid "" "tasks)." msgstr "" -#: library/asyncio-task.rst:510 +#: library/asyncio-task.rst:521 +msgid "" +"import asyncio\n" +"\n" +"async def factorial(name, number):\n" +" f = 1\n" +" for i in range(2, number + 1):\n" +" print(f\"Task {name}: Compute factorial({number}), currently i={i}..." +"\")\n" +" await asyncio.sleep(1)\n" +" f *= i\n" +" print(f\"Task {name}: factorial({number}) = {f}\")\n" +" return f\n" +"\n" +"async def main():\n" +" # Schedule three calls *concurrently*:\n" +" L = await asyncio.gather(\n" +" factorial(\"A\", 2),\n" +" factorial(\"B\", 3),\n" +" factorial(\"C\", 4),\n" +" )\n" +" print(L)\n" +"\n" +"asyncio.run(main())\n" +"\n" +"# Expected output:\n" +"#\n" +"# Task A: Compute factorial(2), currently i=2...\n" +"# Task B: Compute factorial(3), currently i=2...\n" +"# Task C: Compute factorial(4), currently i=2...\n" +"# Task A: factorial(2) = 2\n" +"# Task B: Compute factorial(3), currently i=3...\n" +"# Task C: Compute factorial(4), currently i=3...\n" +"# Task B: factorial(3) = 6\n" +"# Task C: Compute factorial(4), currently i=4...\n" +"# Task C: factorial(4) = 24\n" +"# [2, 6, 24]" +msgstr "" + +#: library/asyncio-task.rst:557 msgid "" "If *return_exceptions* is false, cancelling gather() after it has been " "marked done won't cancel any submitted awaitables. For instance, gather can " @@ -462,28 +741,28 @@ msgid "" "the awaitables) from gather won't cancel any other awaitables." msgstr "" -#: library/asyncio-task.rst:517 +#: library/asyncio-task.rst:564 msgid "" "If the *gather* itself is cancelled, the cancellation is propagated " "regardless of *return_exceptions*." msgstr "" -#: library/asyncio-task.rst:524 +#: library/asyncio-task.rst:571 msgid "" "Deprecation warning is emitted if no positional arguments are provided or " "not all positional arguments are Future-like objects and there is no running " "event loop." msgstr "" -#: library/asyncio-task.rst:533 +#: library/asyncio-task.rst:580 msgid "Eager Task Factory" msgstr "" -#: library/asyncio-task.rst:537 +#: library/asyncio-task.rst:584 msgid "A task factory for eager task execution." msgstr "" -#: library/asyncio-task.rst:539 +#: library/asyncio-task.rst:586 msgid "" "When using this factory (via :meth:`loop.set_task_factory(asyncio." "eager_task_factory) `), coroutines begin execution " @@ -493,13 +772,13 @@ msgid "" "synchronously." msgstr "" -#: library/asyncio-task.rst:545 +#: library/asyncio-task.rst:592 msgid "" "A common example where this is beneficial is coroutines which employ caching " "or memoization to avoid actual I/O when possible." msgstr "" -#: library/asyncio-task.rst:550 +#: library/asyncio-task.rst:597 msgid "" "Immediate execution of the coroutine is a semantic change. If the coroutine " "returns or raises, the task is never scheduled to the event loop. If the " @@ -508,50 +787,60 @@ msgid "" "the application's task execution order is likely to change." msgstr "" -#: library/asyncio-task.rst:561 +#: library/asyncio-task.rst:608 msgid "" "Create an eager task factory, similar to :func:`eager_task_factory`, using " "the provided *custom_task_constructor* when creating a new task instead of " "the default :class:`Task`." msgstr "" -#: library/asyncio-task.rst:565 +#: library/asyncio-task.rst:612 msgid "" "*custom_task_constructor* must be a *callable* with the signature matching " "the signature of :class:`Task.__init__ `. The callable must return a :" "class:`asyncio.Task`-compatible object." msgstr "" -#: library/asyncio-task.rst:569 +#: library/asyncio-task.rst:616 msgid "" "This function returns a *callable* intended to be used as a task factory of " "an event loop via :meth:`loop.set_task_factory(factory) `)." msgstr "" -#: library/asyncio-task.rst:576 +#: library/asyncio-task.rst:623 msgid "Shielding From Cancellation" msgstr "" -#: library/asyncio-task.rst:580 +#: library/asyncio-task.rst:627 msgid "" "Protect an :ref:`awaitable object ` from being :meth:" "`cancelled `." msgstr "" -#: library/asyncio-task.rst:749 +#: library/asyncio-task.rst:796 msgid "If *aw* is a coroutine it is automatically scheduled as a Task." msgstr "" -#: library/asyncio-task.rst:585 +#: library/asyncio-task.rst:632 msgid "The statement::" msgstr "" -#: library/asyncio-task.rst:590 +#: library/asyncio-task.rst:634 +msgid "" +"task = asyncio.create_task(something())\n" +"res = await shield(task)" +msgstr "" + +#: library/asyncio-task.rst:637 msgid "is equivalent to::" msgstr "" -#: library/asyncio-task.rst:594 +#: library/asyncio-task.rst:639 +msgid "res = await something()" +msgstr "" + +#: library/asyncio-task.rst:641 msgid "" "*except* that if the coroutine containing it is cancelled, the Task running " "in ``something()`` is not cancelled. From the point of view of " @@ -560,20 +849,29 @@ msgid "" "`CancelledError`." msgstr "" -#: library/asyncio-task.rst:600 +#: library/asyncio-task.rst:647 msgid "" "If ``something()`` is cancelled by other means (i.e. from within itself) " "that would also cancel ``shield()``." msgstr "" -#: library/asyncio-task.rst:603 +#: library/asyncio-task.rst:650 msgid "" "If it is desired to completely ignore cancellation (not recommended) the " "``shield()`` function should be combined with a try/except clause, as " "follows::" msgstr "" -#: library/asyncio-task.rst:615 +#: library/asyncio-task.rst:654 +msgid "" +"task = asyncio.create_task(something())\n" +"try:\n" +" res = await shield(task)\n" +"except CancelledError:\n" +" res = None" +msgstr "" + +#: library/asyncio-task.rst:662 msgid "" "Save a reference to tasks passed to this function, to avoid a task " "disappearing mid-execution. The event loop only keeps weak references to " @@ -581,36 +879,43 @@ msgid "" "any time, even before it's done." msgstr "" -#: library/asyncio-task.rst:623 +#: library/asyncio-task.rst:670 msgid "" "Deprecation warning is emitted if *aw* is not Future-like object and there " "is no running event loop." msgstr "" -#: library/asyncio-task.rst:629 +#: library/asyncio-task.rst:676 msgid "Timeouts" msgstr "" -#: library/asyncio-task.rst:633 +#: library/asyncio-task.rst:680 msgid "" "Return an :ref:`asynchronous context manager ` that " "can be used to limit the amount of time spent waiting on something." msgstr "" -#: library/asyncio-task.rst:637 +#: library/asyncio-task.rst:684 msgid "" "*delay* can either be ``None``, or a float/int number of seconds to wait. If " "*delay* is ``None``, no time limit will be applied; this can be useful if " "the delay is unknown when the context manager is created." msgstr "" -#: library/asyncio-task.rst:642 +#: library/asyncio-task.rst:689 msgid "" "In either case, the context manager can be rescheduled after creation using :" "meth:`Timeout.reschedule`." msgstr "" -#: library/asyncio-task.rst:651 +#: library/asyncio-task.rst:694 +msgid "" +"async def main():\n" +" async with asyncio.timeout(10):\n" +" await long_running_task()" +msgstr "" + +#: library/asyncio-task.rst:698 msgid "" "If ``long_running_task`` takes more than 10 seconds to complete, the context " "manager will cancel the current task and handle the resulting :exc:`asyncio." @@ -618,192 +923,261 @@ msgid "" "can be caught and handled." msgstr "" -#: library/asyncio-task.rst:658 +#: library/asyncio-task.rst:705 msgid "" "The :func:`asyncio.timeout` context manager is what transforms the :exc:" "`asyncio.CancelledError` into a :exc:`TimeoutError`, which means the :exc:" "`TimeoutError` can only be caught *outside* of the context manager." msgstr "" -#: library/asyncio-task.rst:663 +#: library/asyncio-task.rst:710 msgid "Example of catching :exc:`TimeoutError`::" msgstr "" -#: library/asyncio-task.rst:674 +#: library/asyncio-task.rst:712 +msgid "" +"async def main():\n" +" try:\n" +" async with asyncio.timeout(10):\n" +" await long_running_task()\n" +" except TimeoutError:\n" +" print(\"The long operation timed out, but we've handled it.\")\n" +"\n" +" print(\"This statement will run regardless.\")" +msgstr "" + +#: library/asyncio-task.rst:721 msgid "" "The context manager produced by :func:`asyncio.timeout` can be rescheduled " "to a different deadline and inspected." msgstr "" -#: library/asyncio-task.rst:679 +#: library/asyncio-task.rst:726 msgid "" "An :ref:`asynchronous context manager ` for " "cancelling overdue coroutines." msgstr "" -#: library/asyncio-task.rst:682 +#: library/asyncio-task.rst:729 msgid "" "``when`` should be an absolute time at which the context should time out, as " "measured by the event loop's clock:" msgstr "" -#: library/asyncio-task.rst:685 +#: library/asyncio-task.rst:732 msgid "If ``when`` is ``None``, the timeout will never trigger." msgstr "" -#: library/asyncio-task.rst:686 +#: library/asyncio-task.rst:733 msgid "" "If ``when < loop.time()``, the timeout will trigger on the next iteration of " "the event loop." msgstr "" -#: library/asyncio-task.rst:691 +#: library/asyncio-task.rst:738 msgid "" "Return the current deadline, or ``None`` if the current deadline is not set." msgstr "" -#: library/asyncio-task.rst:696 +#: library/asyncio-task.rst:743 msgid "Reschedule the timeout." msgstr "" -#: library/asyncio-task.rst:700 +#: library/asyncio-task.rst:747 msgid "Return whether the context manager has exceeded its deadline (expired)." msgstr "" -#: library/asyncio-task.rst:720 +#: library/asyncio-task.rst:752 +msgid "" +"async def main():\n" +" try:\n" +" # We do not know the timeout when starting, so we pass ``None``.\n" +" async with asyncio.timeout(None) as cm:\n" +" # We know the timeout now, so we reschedule it.\n" +" new_deadline = get_running_loop().time() + 10\n" +" cm.reschedule(new_deadline)\n" +"\n" +" await long_running_task()\n" +" except TimeoutError:\n" +" pass\n" +"\n" +" if cm.expired():\n" +" print(\"Looks like we haven't finished on time.\")" +msgstr "" + +#: library/asyncio-task.rst:767 msgid "Timeout context managers can be safely nested." msgstr "" -#: library/asyncio-task.rst:726 +#: library/asyncio-task.rst:773 msgid "" "Similar to :func:`asyncio.timeout`, except *when* is the absolute time to " "stop waiting, or ``None``." msgstr "" -#: library/asyncio-task.rst:746 +#: library/asyncio-task.rst:778 +msgid "" +"async def main():\n" +" loop = get_running_loop()\n" +" deadline = loop.time() + 20\n" +" try:\n" +" async with asyncio.timeout_at(deadline):\n" +" await long_running_task()\n" +" except TimeoutError:\n" +" print(\"The long operation timed out, but we've handled it.\")\n" +"\n" +" print(\"This statement will run regardless.\")" +msgstr "" + +#: library/asyncio-task.rst:793 msgid "" "Wait for the *aw* :ref:`awaitable ` to complete with a " "timeout." msgstr "" -#: library/asyncio-task.rst:751 +#: library/asyncio-task.rst:798 msgid "" "*timeout* can either be ``None`` or a float or int number of seconds to wait " "for. If *timeout* is ``None``, block until the future completes." msgstr "" -#: library/asyncio-task.rst:755 +#: library/asyncio-task.rst:802 msgid "" "If a timeout occurs, it cancels the task and raises :exc:`TimeoutError`." msgstr "" -#: library/asyncio-task.rst:758 +#: library/asyncio-task.rst:805 msgid "" "To avoid the task :meth:`cancellation `, wrap it in :func:" "`shield`." msgstr "" -#: library/asyncio-task.rst:761 +#: library/asyncio-task.rst:808 msgid "" "The function will wait until the future is actually cancelled, so the total " "wait time may exceed the *timeout*. If an exception happens during " "cancellation, it is propagated." msgstr "" -#: library/asyncio-task.rst:765 +#: library/asyncio-task.rst:812 msgid "If the wait is cancelled, the future *aw* is also cancelled." msgstr "" -#: library/asyncio-task.rst:789 +#: library/asyncio-task.rst:818 +msgid "" +"async def eternity():\n" +" # Sleep for one hour\n" +" await asyncio.sleep(3600)\n" +" print('yay!')\n" +"\n" +"async def main():\n" +" # Wait for at most 1 second\n" +" try:\n" +" await asyncio.wait_for(eternity(), timeout=1.0)\n" +" except TimeoutError:\n" +" print('timeout!')\n" +"\n" +"asyncio.run(main())\n" +"\n" +"# Expected output:\n" +"#\n" +"# timeout!" +msgstr "" + +#: library/asyncio-task.rst:836 msgid "" "When *aw* is cancelled due to a timeout, ``wait_for`` waits for *aw* to be " "cancelled. Previously, it raised :exc:`TimeoutError` immediately." msgstr "" -#: library/asyncio-task.rst:797 +#: library/asyncio-task.rst:844 msgid "Raises :exc:`TimeoutError` instead of :exc:`asyncio.TimeoutError`." msgstr "" -#: library/asyncio-task.rst:802 +#: library/asyncio-task.rst:849 msgid "Waiting Primitives" msgstr "" -#: library/asyncio-task.rst:806 +#: library/asyncio-task.rst:853 msgid "" "Run :class:`~asyncio.Future` and :class:`~asyncio.Task` instances in the " "*aws* iterable concurrently and block until the condition specified by " "*return_when*." msgstr "" -#: library/asyncio-task.rst:810 +#: library/asyncio-task.rst:857 msgid "The *aws* iterable must not be empty." msgstr "" -#: library/asyncio-task.rst:812 +#: library/asyncio-task.rst:859 msgid "Returns two sets of Tasks/Futures: ``(done, pending)``." msgstr "" -#: library/asyncio-task.rst:814 +#: library/asyncio-task.rst:861 msgid "Usage::" msgstr "" -#: library/asyncio-task.rst:818 +#: library/asyncio-task.rst:863 +msgid "done, pending = await asyncio.wait(aws)" +msgstr "" + +#: library/asyncio-task.rst:865 msgid "" "*timeout* (a float or int), if specified, can be used to control the maximum " "number of seconds to wait before returning." msgstr "" -#: library/asyncio-task.rst:821 +#: library/asyncio-task.rst:868 msgid "" "Note that this function does not raise :exc:`TimeoutError`. Futures or Tasks " "that aren't done when the timeout occurs are simply returned in the second " "set." msgstr "" -#: library/asyncio-task.rst:825 +#: library/asyncio-task.rst:872 msgid "" "*return_when* indicates when this function should return. It must be one of " "the following constants:" msgstr "" -#: library/asyncio-task.rst:831 +#: library/asyncio-task.rst:878 msgid "Constant" msgstr "" -#: library/asyncio-task.rst:832 +#: library/asyncio-task.rst:879 msgid "Description" msgstr "" -#: library/asyncio-task.rst:835 +#: library/asyncio-task.rst:882 msgid "The function will return when any future finishes or is cancelled." msgstr "" -#: library/asyncio-task.rst:838 +#: library/asyncio-task.rst:885 msgid "" "The function will return when any future finishes by raising an exception. " "If no future raises an exception then it is equivalent to :const:" "`ALL_COMPLETED`." msgstr "" -#: library/asyncio-task.rst:843 +#: library/asyncio-task.rst:890 msgid "The function will return when all futures finish or are cancelled." msgstr "" -#: library/asyncio-task.rst:845 +#: library/asyncio-task.rst:892 msgid "" "Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the futures " "when a timeout occurs." msgstr "" -#: library/asyncio-task.rst:851 +#: library/asyncio-task.rst:898 msgid "Passing coroutine objects to ``wait()`` directly is forbidden." msgstr "" -#: library/asyncio-task.rst:881 +#: library/asyncio-task.rst:928 msgid "Added support for generators yielding tasks." msgstr "" -#: library/asyncio-task.rst:860 +#: library/asyncio-task.rst:907 msgid "" "Run :ref:`awaitable objects ` in the *aws* iterable " "concurrently. Return an iterator of coroutines. Each coroutine returned can " @@ -811,26 +1185,33 @@ msgid "" "remaining awaitables." msgstr "" -#: library/asyncio-task.rst:865 +#: library/asyncio-task.rst:912 msgid "" "Raises :exc:`TimeoutError` if the timeout occurs before all Futures are done." msgstr "" -#: library/asyncio-task.rst:877 +#: library/asyncio-task.rst:917 +msgid "" +"for coro in as_completed(aws):\n" +" earliest_result = await coro\n" +" # ..." +msgstr "" + +#: library/asyncio-task.rst:924 msgid "" "Deprecation warning is emitted if not all awaitable objects in the *aws* " "iterable are Future-like objects and there is no running event loop." msgstr "" -#: library/asyncio-task.rst:886 +#: library/asyncio-task.rst:933 msgid "Running in Threads" msgstr "" -#: library/asyncio-task.rst:890 +#: library/asyncio-task.rst:937 msgid "Asynchronously run function *func* in a separate thread." msgstr "" -#: library/asyncio-task.rst:892 +#: library/asyncio-task.rst:939 msgid "" "Any \\*args and \\*\\*kwargs supplied for this function are directly passed " "to *func*. Also, the current :class:`contextvars.Context` is propagated, " @@ -838,19 +1219,48 @@ msgid "" "separate thread." msgstr "" -#: library/asyncio-task.rst:897 +#: library/asyncio-task.rst:944 msgid "" "Return a coroutine that can be awaited to get the eventual result of *func*." msgstr "" -#: library/asyncio-task.rst:899 +#: library/asyncio-task.rst:946 msgid "" "This coroutine function is primarily intended to be used for executing IO-" "bound functions/methods that would otherwise block the event loop if they " "were run in the main thread. For example::" msgstr "" -#: library/asyncio-task.rst:929 +#: library/asyncio-task.rst:950 +msgid "" +"def blocking_io():\n" +" print(f\"start blocking_io at {time.strftime('%X')}\")\n" +" # Note that time.sleep() can be replaced with any blocking\n" +" # IO-bound operation, such as file operations.\n" +" time.sleep(1)\n" +" print(f\"blocking_io complete at {time.strftime('%X')}\")\n" +"\n" +"async def main():\n" +" print(f\"started main at {time.strftime('%X')}\")\n" +"\n" +" await asyncio.gather(\n" +" asyncio.to_thread(blocking_io),\n" +" asyncio.sleep(1))\n" +"\n" +" print(f\"finished main at {time.strftime('%X')}\")\n" +"\n" +"\n" +"asyncio.run(main())\n" +"\n" +"# Expected output:\n" +"#\n" +"# started main at 19:50:53\n" +"# start blocking_io at 19:50:53\n" +"# blocking_io complete at 19:50:54\n" +"# finished main at 19:50:54" +msgstr "" + +#: library/asyncio-task.rst:976 msgid "" "Directly calling ``blocking_io()`` in any coroutine would block the event " "loop for its duration, resulting in an additional 1 second of run time. " @@ -858,7 +1268,7 @@ msgid "" "thread without blocking the event loop." msgstr "" -#: library/asyncio-task.rst:936 +#: library/asyncio-task.rst:983 msgid "" "Due to the :term:`GIL`, ``asyncio.to_thread()`` can typically only be used " "to make IO-bound functions non-blocking. However, for extension modules that " @@ -866,85 +1276,110 @@ msgid "" "``asyncio.to_thread()`` can also be used for CPU-bound functions." msgstr "" -#: library/asyncio-task.rst:945 +#: library/asyncio-task.rst:992 msgid "Scheduling From Other Threads" msgstr "" -#: library/asyncio-task.rst:949 +#: library/asyncio-task.rst:996 msgid "Submit a coroutine to the given event loop. Thread-safe." msgstr "" -#: library/asyncio-task.rst:951 +#: library/asyncio-task.rst:998 msgid "" "Return a :class:`concurrent.futures.Future` to wait for the result from " "another OS thread." msgstr "" -#: library/asyncio-task.rst:954 +#: library/asyncio-task.rst:1001 msgid "" "This function is meant to be called from a different OS thread than the one " "where the event loop is running. Example::" msgstr "" -#: library/asyncio-task.rst:966 +#: library/asyncio-task.rst:1004 +msgid "" +"# Create a coroutine\n" +"coro = asyncio.sleep(1, result=3)\n" +"\n" +"# Submit the coroutine to a given loop\n" +"future = asyncio.run_coroutine_threadsafe(coro, loop)\n" +"\n" +"# Wait for the result with an optional timeout argument\n" +"assert future.result(timeout) == 3" +msgstr "" + +#: library/asyncio-task.rst:1013 msgid "" "If an exception is raised in the coroutine, the returned Future will be " "notified. It can also be used to cancel the task in the event loop::" msgstr "" -#: library/asyncio-task.rst:980 +#: library/asyncio-task.rst:1017 +msgid "" +"try:\n" +" result = future.result(timeout)\n" +"except TimeoutError:\n" +" print('The coroutine took too long, cancelling the task...')\n" +" future.cancel()\n" +"except Exception as exc:\n" +" print(f'The coroutine raised an exception: {exc!r}')\n" +"else:\n" +" print(f'The coroutine returned: {result!r}')" +msgstr "" + +#: library/asyncio-task.rst:1027 msgid "" "See the :ref:`concurrency and multithreading ` " "section of the documentation." msgstr "" -#: library/asyncio-task.rst:983 +#: library/asyncio-task.rst:1030 msgid "" "Unlike other asyncio functions this function requires the *loop* argument to " "be passed explicitly." msgstr "" -#: library/asyncio-task.rst:990 +#: library/asyncio-task.rst:1037 msgid "Introspection" msgstr "" -#: library/asyncio-task.rst:995 +#: library/asyncio-task.rst:1042 msgid "" "Return the currently running :class:`Task` instance, or ``None`` if no task " "is running." msgstr "" -#: library/asyncio-task.rst:998 +#: library/asyncio-task.rst:1045 msgid "" "If *loop* is ``None`` :func:`get_running_loop` is used to get the current " "loop." msgstr "" -#: library/asyncio-task.rst:1006 +#: library/asyncio-task.rst:1053 msgid "Return a set of not yet finished :class:`Task` objects run by the loop." msgstr "" -#: library/asyncio-task.rst:1009 +#: library/asyncio-task.rst:1056 msgid "" "If *loop* is ``None``, :func:`get_running_loop` is used for getting current " "loop." msgstr "" -#: library/asyncio-task.rst:1017 +#: library/asyncio-task.rst:1064 msgid "Return ``True`` if *obj* is a coroutine object." msgstr "" -#: library/asyncio-task.rst:1023 +#: library/asyncio-task.rst:1070 msgid "Task Object" msgstr "" -#: library/asyncio-task.rst:1027 +#: library/asyncio-task.rst:1074 msgid "" "A :class:`Future-like ` object that runs a Python :ref:`coroutine " "`. Not thread-safe." msgstr "" -#: library/asyncio-task.rst:1030 +#: library/asyncio-task.rst:1077 msgid "" "Tasks are used to run coroutines in event loops. If a coroutine awaits on a " "Future, the Task suspends the execution of the coroutine and waits for the " @@ -952,21 +1387,21 @@ msgid "" "wrapped coroutine resumes." msgstr "" -#: library/asyncio-task.rst:1036 +#: library/asyncio-task.rst:1083 msgid "" "Event loops use cooperative scheduling: an event loop runs one Task at a " "time. While a Task awaits for the completion of a Future, the event loop " "runs other Tasks, callbacks, or performs IO operations." msgstr "" -#: library/asyncio-task.rst:1041 +#: library/asyncio-task.rst:1088 msgid "" "Use the high-level :func:`asyncio.create_task` function to create Tasks, or " "the low-level :meth:`loop.create_task` or :func:`ensure_future` functions. " "Manual instantiation of Tasks is discouraged." msgstr "" -#: library/asyncio-task.rst:1046 +#: library/asyncio-task.rst:1093 msgid "" "To cancel a running Task use the :meth:`cancel` method. Calling it will " "cause the Task to throw a :exc:`CancelledError` exception into the wrapped " @@ -974,20 +1409,20 @@ msgid "" "cancellation, the Future object will be cancelled." msgstr "" -#: library/asyncio-task.rst:1051 +#: library/asyncio-task.rst:1098 msgid "" ":meth:`cancelled` can be used to check if the Task was cancelled. The method " "returns ``True`` if the wrapped coroutine did not suppress the :exc:" "`CancelledError` exception and was actually cancelled." msgstr "" -#: library/asyncio-task.rst:1056 +#: library/asyncio-task.rst:1103 msgid "" ":class:`asyncio.Task` inherits from :class:`Future` all of its APIs except :" "meth:`Future.set_result` and :meth:`Future.set_exception`." msgstr "" -#: library/asyncio-task.rst:1060 +#: library/asyncio-task.rst:1107 msgid "" "An optional keyword-only *context* argument allows specifying a custom :" "class:`contextvars.Context` for the *coro* to run in. If no *context* is " @@ -995,7 +1430,7 @@ msgid "" "in the copied context." msgstr "" -#: library/asyncio-task.rst:1065 +#: library/asyncio-task.rst:1112 msgid "" "An optional keyword-only *eager_start* argument allows eagerly starting the " "execution of the :class:`asyncio.Task` at task creation time. If set to " @@ -1005,96 +1440,96 @@ msgid "" "eagerly and will skip scheduling to the event loop." msgstr "" -#: library/asyncio-task.rst:1072 +#: library/asyncio-task.rst:1119 msgid "Added support for the :mod:`contextvars` module." msgstr "" -#: library/asyncio-task.rst:1078 +#: library/asyncio-task.rst:1125 msgid "" "Deprecation warning is emitted if *loop* is not specified and there is no " "running event loop." msgstr "" -#: library/asyncio-task.rst:1085 +#: library/asyncio-task.rst:1132 msgid "Added the *eager_start* parameter." msgstr "" -#: library/asyncio-task.rst:1090 +#: library/asyncio-task.rst:1137 msgid "Return ``True`` if the Task is *done*." msgstr "" -#: library/asyncio-task.rst:1092 +#: library/asyncio-task.rst:1139 msgid "" "A Task is *done* when the wrapped coroutine either returned a value, raised " "an exception, or the Task was cancelled." msgstr "" -#: library/asyncio-task.rst:1097 +#: library/asyncio-task.rst:1144 msgid "Return the result of the Task." msgstr "" -#: library/asyncio-task.rst:1099 +#: library/asyncio-task.rst:1146 msgid "" "If the Task is *done*, the result of the wrapped coroutine is returned (or " "if the coroutine raised an exception, that exception is re-raised.)" msgstr "" -#: library/asyncio-task.rst:1117 +#: library/asyncio-task.rst:1164 msgid "" "If the Task has been *cancelled*, this method raises a :exc:`CancelledError` " "exception." msgstr "" -#: library/asyncio-task.rst:1106 +#: library/asyncio-task.rst:1153 msgid "" "If the Task's result isn't yet available, this method raises an :exc:" "`InvalidStateError` exception." msgstr "" -#: library/asyncio-task.rst:1111 +#: library/asyncio-task.rst:1158 msgid "Return the exception of the Task." msgstr "" -#: library/asyncio-task.rst:1113 +#: library/asyncio-task.rst:1160 msgid "" "If the wrapped coroutine raised an exception that exception is returned. If " "the wrapped coroutine returned normally this method returns ``None``." msgstr "" -#: library/asyncio-task.rst:1120 +#: library/asyncio-task.rst:1167 msgid "" "If the Task isn't *done* yet, this method raises an :exc:`InvalidStateError` " "exception." msgstr "" -#: library/asyncio-task.rst:1125 +#: library/asyncio-task.rst:1172 msgid "Add a callback to be run when the Task is *done*." msgstr "" -#: library/asyncio-task.rst:1136 +#: library/asyncio-task.rst:1183 msgid "This method should only be used in low-level callback-based code." msgstr "" -#: library/asyncio-task.rst:1129 +#: library/asyncio-task.rst:1176 msgid "" "See the documentation of :meth:`Future.add_done_callback` for more details." msgstr "" -#: library/asyncio-task.rst:1134 +#: library/asyncio-task.rst:1181 msgid "Remove *callback* from the callbacks list." msgstr "" -#: library/asyncio-task.rst:1138 +#: library/asyncio-task.rst:1185 msgid "" "See the documentation of :meth:`Future.remove_done_callback` for more " "details." msgstr "" -#: library/asyncio-task.rst:1143 +#: library/asyncio-task.rst:1190 msgid "Return the list of stack frames for this Task." msgstr "" -#: library/asyncio-task.rst:1145 +#: library/asyncio-task.rst:1192 msgid "" "If the wrapped coroutine is not done, this returns the stack where it is " "suspended. If the coroutine has completed successfully or was cancelled, " @@ -1102,15 +1537,15 @@ msgid "" "this returns the list of traceback frames." msgstr "" -#: library/asyncio-task.rst:1151 +#: library/asyncio-task.rst:1198 msgid "The frames are always ordered from oldest to newest." msgstr "" -#: library/asyncio-task.rst:1153 +#: library/asyncio-task.rst:1200 msgid "Only one stack frame is returned for a suspended coroutine." msgstr "" -#: library/asyncio-task.rst:1155 +#: library/asyncio-task.rst:1202 msgid "" "The optional *limit* argument sets the maximum number of frames to return; " "by default all available frames are returned. The ordering of the returned " @@ -1119,81 +1554,81 @@ msgid "" "are returned. (This matches the behavior of the traceback module.)" msgstr "" -#: library/asyncio-task.rst:1164 +#: library/asyncio-task.rst:1211 msgid "Print the stack or traceback for this Task." msgstr "" -#: library/asyncio-task.rst:1166 +#: library/asyncio-task.rst:1213 msgid "" "This produces output similar to that of the traceback module for the frames " "retrieved by :meth:`get_stack`." msgstr "" -#: library/asyncio-task.rst:1169 +#: library/asyncio-task.rst:1216 msgid "The *limit* argument is passed to :meth:`get_stack` directly." msgstr "" -#: library/asyncio-task.rst:1171 +#: library/asyncio-task.rst:1218 msgid "" "The *file* argument is an I/O stream to which the output is written; by " "default output is written to :data:`sys.stdout`." msgstr "" -#: library/asyncio-task.rst:1176 +#: library/asyncio-task.rst:1223 msgid "Return the coroutine object wrapped by the :class:`Task`." msgstr "" -#: library/asyncio-task.rst:1180 +#: library/asyncio-task.rst:1227 msgid "" "This will return ``None`` for Tasks which have already completed eagerly. " "See the :ref:`Eager Task Factory `." msgstr "" -#: library/asyncio-task.rst:1187 +#: library/asyncio-task.rst:1234 msgid "Newly added eager task execution means result may be ``None``." msgstr "" -#: library/asyncio-task.rst:1191 +#: library/asyncio-task.rst:1238 msgid "" "Return the :class:`contextvars.Context` object associated with the task." msgstr "" -#: library/asyncio-task.rst:1198 +#: library/asyncio-task.rst:1245 msgid "Return the name of the Task." msgstr "" -#: library/asyncio-task.rst:1200 +#: library/asyncio-task.rst:1247 msgid "" "If no name has been explicitly assigned to the Task, the default asyncio " "Task implementation generates a default name during instantiation." msgstr "" -#: library/asyncio-task.rst:1208 +#: library/asyncio-task.rst:1255 msgid "Set the name of the Task." msgstr "" -#: library/asyncio-task.rst:1210 +#: library/asyncio-task.rst:1257 msgid "" "The *value* argument can be any object, which is then converted to a string." msgstr "" -#: library/asyncio-task.rst:1213 +#: library/asyncio-task.rst:1260 msgid "" "In the default Task implementation, the name will be visible in the :func:" "`repr` output of a task object." msgstr "" -#: library/asyncio-task.rst:1220 +#: library/asyncio-task.rst:1267 msgid "Request the Task to be cancelled." msgstr "" -#: library/asyncio-task.rst:1222 +#: library/asyncio-task.rst:1269 msgid "" "This arranges for a :exc:`CancelledError` exception to be thrown into the " "wrapped coroutine on the next cycle of the event loop." msgstr "" -#: library/asyncio-task.rst:1225 +#: library/asyncio-task.rst:1272 msgid "" "The coroutine then has a chance to clean up or even deny the request by " "suppressing the exception with a :keyword:`try` ... ... ``except " @@ -1205,46 +1640,83 @@ msgid "" "addition to catching the exception." msgstr "" -#: library/asyncio-task.rst:1235 +#: library/asyncio-task.rst:1282 msgid "Added the *msg* parameter." msgstr "" -#: library/asyncio-task.rst:1238 +#: library/asyncio-task.rst:1285 msgid "The ``msg`` parameter is propagated from cancelled task to its awaiter." msgstr "" -#: library/asyncio-task.rst:1243 +#: library/asyncio-task.rst:1290 msgid "" "The following example illustrates how coroutines can intercept the " "cancellation request::" msgstr "" -#: library/asyncio-task.rst:1282 +#: library/asyncio-task.rst:1293 +msgid "" +"async def cancel_me():\n" +" print('cancel_me(): before sleep')\n" +"\n" +" try:\n" +" # Wait for 1 hour\n" +" await asyncio.sleep(3600)\n" +" except asyncio.CancelledError:\n" +" print('cancel_me(): cancel sleep')\n" +" raise\n" +" finally:\n" +" print('cancel_me(): after sleep')\n" +"\n" +"async def main():\n" +" # Create a \"cancel_me\" Task\n" +" task = asyncio.create_task(cancel_me())\n" +"\n" +" # Wait for 1 second\n" +" await asyncio.sleep(1)\n" +"\n" +" task.cancel()\n" +" try:\n" +" await task\n" +" except asyncio.CancelledError:\n" +" print(\"main(): cancel_me is cancelled now\")\n" +"\n" +"asyncio.run(main())\n" +"\n" +"# Expected output:\n" +"#\n" +"# cancel_me(): before sleep\n" +"# cancel_me(): cancel sleep\n" +"# cancel_me(): after sleep\n" +"# main(): cancel_me is cancelled now" +msgstr "" + +#: library/asyncio-task.rst:1329 msgid "Return ``True`` if the Task is *cancelled*." msgstr "" -#: library/asyncio-task.rst:1284 +#: library/asyncio-task.rst:1331 msgid "" "The Task is *cancelled* when the cancellation was requested with :meth:" "`cancel` and the wrapped coroutine propagated the :exc:`CancelledError` " "exception thrown into it." msgstr "" -#: library/asyncio-task.rst:1290 +#: library/asyncio-task.rst:1337 msgid "Decrement the count of cancellation requests to this Task." msgstr "" -#: library/asyncio-task.rst:1292 +#: library/asyncio-task.rst:1339 msgid "Returns the remaining number of cancellation requests." msgstr "" -#: library/asyncio-task.rst:1294 +#: library/asyncio-task.rst:1341 msgid "" "Note that once execution of a cancelled task completed, further calls to :" "meth:`uncancel` are ineffective." msgstr "" -#: library/asyncio-task.rst:1299 +#: library/asyncio-task.rst:1346 msgid "" "This method is used by asyncio's internals and isn't expected to be used by " "end-user code. In particular, if a Task gets successfully uncancelled, this " @@ -1253,7 +1725,21 @@ msgid "" "respective structured block. For example::" msgstr "" -#: library/asyncio-task.rst:1317 +#: library/asyncio-task.rst:1353 +msgid "" +"async def make_request_with_timeout():\n" +" try:\n" +" async with asyncio.timeout(1):\n" +" # Structured block affected by the timeout:\n" +" await make_request()\n" +" await make_another_request()\n" +" except TimeoutError:\n" +" log(\"There was a timeout\")\n" +" # Outer code not affected by the timeout:\n" +" await unrelated_code()" +msgstr "" + +#: library/asyncio-task.rst:1364 msgid "" "While the block with ``make_request()`` and ``make_another_request()`` might " "get cancelled due to the timeout, ``unrelated_code()`` should continue " @@ -1262,20 +1748,20 @@ msgid "" "similar fashion." msgstr "" -#: library/asyncio-task.rst:1323 +#: library/asyncio-task.rst:1370 msgid "" "If end-user code is, for some reason, suppressing cancellation by catching :" "exc:`CancelledError`, it needs to call this method to remove the " "cancellation state." msgstr "" -#: library/asyncio-task.rst:1329 +#: library/asyncio-task.rst:1376 msgid "" "Return the number of pending cancellation requests to this Task, i.e., the " "number of calls to :meth:`cancel` less the number of :meth:`uncancel` calls." msgstr "" -#: library/asyncio-task.rst:1333 +#: library/asyncio-task.rst:1380 msgid "" "Note that if this number is greater than zero but the Task is still " "executing, :meth:`cancelled` will still return ``False``. This is because " @@ -1284,7 +1770,7 @@ msgid "" "to zero." msgstr "" -#: library/asyncio-task.rst:1339 +#: library/asyncio-task.rst:1386 msgid "" "This method is used by asyncio's internals and isn't expected to be used by " "end-user code. See :meth:`uncancel` for more details." diff --git a/library/asyncio.po b/library/asyncio.po index 02105d298..005134867 100644 --- a/library/asyncio.po +++ b/library/asyncio.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: 2024-07-06 18:16+0300\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -36,6 +36,18 @@ msgstr ":mod:`!asyncio` --- Eşzamansız I/O" msgid "Hello World!" msgstr "Merhaba Dünya!" +#: library/asyncio.rst:13 +msgid "" +"import asyncio\n" +"\n" +"async def main():\n" +" print('Hello ...')\n" +" await asyncio.sleep(1)\n" +" print('... World!')\n" +"\n" +"asyncio.run(main())" +msgstr "" + #: library/asyncio.rst:22 msgid "" "asyncio is a library to write **concurrent** code using the **async/await** " @@ -128,8 +140,8 @@ msgstr "" "futures>` async/await sözdizimi ile birleştirin." #: includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not Emscripten, not WASI." -msgstr ":ref:`Uygunluk `: ne Emscripten , ne de WASI değil." +msgid "Availability" +msgstr "" #: includes/wasm-notavail.rst:5 msgid "" @@ -150,8 +162,22 @@ msgid "You can experiment with an ``asyncio`` concurrent context in the REPL:" msgstr "" "REPL üzerinde ``asyncio`` ile eşzamanlı bağlamda denemeler yapabilirsiniz:" +#: library/asyncio.rst:67 +msgid "" +"$ python -m asyncio\n" +"asyncio REPL ...\n" +"Use \"await\" directly instead of \"asyncio.run()\".\n" +"Type \"help\", \"copyright\", \"credits\" or \"license\" for more " +"information.\n" +">>> import asyncio\n" +">>> await asyncio.sleep(10, result='hello')\n" +"'hello'" +msgstr "" + #: library/asyncio.rst:77 -msgid "Raises an auditing event cpython.run_stdin with no arguments." +msgid "" +"Raises an :ref:`auditing event ` ``cpython.run_stdin`` with no " +"arguments." msgstr "" #: library/asyncio.rst:79 @@ -165,3 +191,6 @@ msgstr "Referans" #: library/asyncio.rst:119 msgid "The source code for asyncio can be found in :source:`Lib/asyncio/`." msgstr "Asyncio için kaynak kodu :source:`Lib/asyncio/` dizininde bulunabilir." + +#~ msgid ":ref:`Availability `: not Emscripten, not WASI." +#~ msgstr ":ref:`Uygunluk `: ne Emscripten , ne de WASI değil." diff --git a/library/atexit.po b/library/atexit.po index 5c58e9a5f..2764901c7 100644 --- a/library/atexit.po +++ b/library/atexit.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -126,16 +126,58 @@ msgid "" "making an explicit call into this module at termination. ::" msgstr "" +#: library/atexit.rst:89 +msgid "" +"try:\n" +" with open('counterfile') as infile:\n" +" _count = int(infile.read())\n" +"except FileNotFoundError:\n" +" _count = 0\n" +"\n" +"def incrcounter(n):\n" +" global _count\n" +" _count = _count + n\n" +"\n" +"def savecounter():\n" +" with open('counterfile', 'w') as outfile:\n" +" outfile.write('%d' % _count)\n" +"\n" +"import atexit\n" +"\n" +"atexit.register(savecounter)" +msgstr "" + #: library/atexit.rst:107 msgid "" "Positional and keyword arguments may also be passed to :func:`register` to " "be passed along to the registered function when it is called::" msgstr "" +#: library/atexit.rst:110 +msgid "" +"def goodbye(name, adjective):\n" +" print('Goodbye %s, it was %s to meet you.' % (name, adjective))\n" +"\n" +"import atexit\n" +"\n" +"atexit.register(goodbye, 'Donny', 'nice')\n" +"# or:\n" +"atexit.register(goodbye, adjective='nice', name='Donny')" +msgstr "" + #: library/atexit.rst:119 msgid "Usage as a :term:`decorator`::" msgstr "" +#: library/atexit.rst:121 +msgid "" +"import atexit\n" +"\n" +"@atexit.register\n" +"def goodbye():\n" +" print('You are now leaving the Python sector.')" +msgstr "" + #: library/atexit.rst:127 msgid "This only works with functions that can be called without arguments." msgstr "" diff --git a/library/audioop.po b/library/audioop.po index 9050811bb..79419718a 100644 --- a/library/audioop.po +++ b/library/audioop.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -187,6 +187,12 @@ msgid "" "samples for these formats, you need to also add 128 to the result::" msgstr "" +#: library/audioop.rst:163 +msgid "" +"new_frames = audioop.lin2lin(frames, old_width, 1)\n" +"new_frames = audioop.bias(new_frames, 1, 128)" +msgstr "" + #: library/audioop.rst:166 msgid "" "The same, in reverse, has to be applied when converting from 8 to 16, 24 or " @@ -284,6 +290,18 @@ msgid "" "that::" msgstr "" +#: library/audioop.rst:249 +msgid "" +"def mul_stereo(sample, width, lfactor, rfactor):\n" +" lsample = audioop.tomono(sample, width, 1, 0)\n" +" rsample = audioop.tomono(sample, width, 0, 1)\n" +" lsample = audioop.mul(lsample, width, lfactor)\n" +" rsample = audioop.mul(rsample, width, rfactor)\n" +" lsample = audioop.tostereo(lsample, width, 1, 0)\n" +" rsample = audioop.tostereo(rsample, width, 0, 1)\n" +" return audioop.add(lsample, rsample, width)" +msgstr "" + #: library/audioop.rst:258 msgid "" "If you use the ADPCM coder to build network packets and you want your " @@ -311,6 +329,22 @@ msgid "" "input sample and subtract the whole output sample from the input sample::" msgstr "" +#: library/audioop.rst:275 +msgid "" +"def echocancel(outputdata, inputdata):\n" +" pos = audioop.findmax(outputdata, 800) # one tenth second\n" +" out_test = outputdata[pos*2:]\n" +" in_test = inputdata[pos*2:]\n" +" ipos, factor = audioop.findfit(in_test, out_test)\n" +" # Optional (for better cancellation):\n" +" # factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],\n" +" # out_test)\n" +" prefill = '\\0'*(pos+ipos)*2\n" +" postfill = '\\0'*(len(inputdata)-len(prefill)-len(outputdata))\n" +" outputdata = prefill + audioop.mul(outputdata, 2, -factor) + postfill\n" +" return audioop.add(inputdata, outputdata, 2)" +msgstr "" + #: library/audioop.rst:24 msgid "Intel/DVI ADPCM" msgstr "" diff --git a/library/binascii.po b/library/binascii.po index 01e525f17..e4bd5fac6 100644 --- a/library/binascii.po +++ b/library/binascii.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -151,6 +151,15 @@ msgid "" "algorithm. Use as follows::" msgstr "" +#: library/binascii.rst:117 +msgid "" +"print(binascii.crc32(b\"hello world\"))\n" +"# Or, in two pieces:\n" +"crc = binascii.crc32(b\"hello\")\n" +"crc = binascii.crc32(b\" world\", crc)\n" +"print('crc32 = {:#010x}'.format(crc))" +msgstr "" + #: library/binascii.rst:123 msgid "The result is always unsigned." msgstr "" diff --git a/library/bisect.po b/library/bisect.po index d5ee824b4..c2ffb5465 100644 --- a/library/bisect.po +++ b/library/bisect.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -193,6 +193,44 @@ msgid "" "sorted lists::" msgstr "" +#: library/bisect.rst:150 +msgid "" +"def index(a, x):\n" +" 'Locate the leftmost value exactly equal to x'\n" +" i = bisect_left(a, x)\n" +" if i != len(a) and a[i] == x:\n" +" return i\n" +" raise ValueError\n" +"\n" +"def find_lt(a, x):\n" +" 'Find rightmost value less than x'\n" +" i = bisect_left(a, x)\n" +" if i:\n" +" return a[i-1]\n" +" raise ValueError\n" +"\n" +"def find_le(a, x):\n" +" 'Find rightmost value less than or equal to x'\n" +" i = bisect_right(a, x)\n" +" if i:\n" +" return a[i-1]\n" +" raise ValueError\n" +"\n" +"def find_gt(a, x):\n" +" 'Find leftmost value greater than x'\n" +" i = bisect_right(a, x)\n" +" if i != len(a):\n" +" return a[i]\n" +" raise ValueError\n" +"\n" +"def find_ge(a, x):\n" +" 'Find leftmost item greater than or equal to x'\n" +" i = bisect_left(a, x)\n" +" if i != len(a):\n" +" return a[i]\n" +" raise ValueError" +msgstr "" + #: library/bisect.rst:187 msgid "Examples" msgstr "" @@ -205,6 +243,16 @@ msgid "" "90 and up is an 'A', 80 to 89 is a 'B', and so on::" msgstr "" +#: library/bisect.rst:196 +msgid "" +">>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):\n" +"... i = bisect(breakpoints, score)\n" +"... return grades[i]\n" +"...\n" +">>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]\n" +"['F', 'A', 'C', 'C', 'B', 'A', 'A']" +msgstr "" + #: library/bisect.rst:203 msgid "" "The :py:func:`~bisect.bisect` and :py:func:`~bisect.insort` functions also " @@ -212,8 +260,56 @@ msgid "" "field used for ordering records in a table::" msgstr "" +#: library/bisect.rst:207 +msgid "" +">>> from collections import namedtuple\n" +">>> from operator import attrgetter\n" +">>> from bisect import bisect, insort\n" +">>> from pprint import pprint\n" +"\n" +">>> Movie = namedtuple('Movie', ('name', 'released', 'director'))\n" +"\n" +">>> movies = [\n" +"... Movie('Jaws', 1975, 'Spielberg'),\n" +"... Movie('Titanic', 1997, 'Cameron'),\n" +"... Movie('The Birds', 1963, 'Hitchcock'),\n" +"... Movie('Aliens', 1986, 'Cameron')\n" +"... ]\n" +"\n" +">>> # Find the first movie released after 1960\n" +">>> by_year = attrgetter('released')\n" +">>> movies.sort(key=by_year)\n" +">>> movies[bisect(movies, 1960, key=by_year)]\n" +"Movie(name='The Birds', released=1963, director='Hitchcock')\n" +"\n" +">>> # Insert a movie while maintaining sort order\n" +">>> romance = Movie('Love Story', 1970, 'Hiller')\n" +">>> insort(movies, romance, key=by_year)\n" +">>> pprint(movies)\n" +"[Movie(name='The Birds', released=1963, director='Hitchcock'),\n" +" Movie(name='Love Story', released=1970, director='Hiller'),\n" +" Movie(name='Jaws', released=1975, director='Spielberg'),\n" +" Movie(name='Aliens', released=1986, director='Cameron'),\n" +" Movie(name='Titanic', released=1997, director='Cameron')]" +msgstr "" + #: library/bisect.rst:237 msgid "" "If the key function is expensive, it is possible to avoid repeated function " "calls by searching a list of precomputed keys to find the index of a record::" msgstr "" + +#: library/bisect.rst:240 +msgid "" +">>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)]\n" +">>> data.sort(key=lambda r: r[1]) # Or use operator.itemgetter(1).\n" +">>> keys = [r[1] for r in data] # Precompute a list of keys.\n" +">>> data[bisect_left(keys, 0)]\n" +"('black', 0)\n" +">>> data[bisect_left(keys, 1)]\n" +"('blue', 1)\n" +">>> data[bisect_left(keys, 5)]\n" +"('red', 5)\n" +">>> data[bisect_left(keys, 8)]\n" +"('yellow', 8)" +msgstr "" diff --git a/library/builtins.po b/library/builtins.po index 2c5e95d53..bc41c18d1 100644 --- a/library/builtins.po +++ b/library/builtins.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -24,11 +24,10 @@ msgstr "" msgid "" "This module provides direct access to all 'built-in' identifiers of Python; " "for example, ``builtins.open`` is the full name for the built-in function :" -"func:`open`. See :ref:`built-in-funcs` and :ref:`built-in-consts` for " -"documentation." +"func:`open`." msgstr "" -#: library/builtins.rst:15 +#: library/builtins.rst:12 msgid "" "This module is not normally accessed explicitly by most applications, but " "can be useful in modules that provide objects with the same name as a built-" @@ -37,7 +36,27 @@ msgid "" "wraps the built-in :func:`open`, this module can be used directly::" msgstr "" -#: library/builtins.rst:38 +#: library/builtins.rst:18 +msgid "" +"import builtins\n" +"\n" +"def open(path):\n" +" f = builtins.open(path, 'r')\n" +" return UpperCaser(f)\n" +"\n" +"class UpperCaser:\n" +" '''Wrapper around a file that converts output to uppercase.'''\n" +"\n" +" def __init__(self, f):\n" +" self._f = f\n" +"\n" +" def read(self, count=-1):\n" +" return self._f.read(count).upper()\n" +"\n" +" # ..." +msgstr "" + +#: library/builtins.rst:35 msgid "" "As an implementation detail, most modules have the name ``__builtins__`` " "made available as part of their globals. The value of ``__builtins__`` is " @@ -45,3 +64,19 @@ msgid "" "__dict__` attribute. Since this is an implementation detail, it may not be " "used by alternate implementations of Python." msgstr "" + +#: library/builtins.rst:43 +msgid ":ref:`built-in-consts`" +msgstr "" + +#: library/builtins.rst:44 +msgid ":ref:`bltin-exceptions`" +msgstr "" + +#: library/builtins.rst:45 +msgid ":ref:`built-in-funcs`" +msgstr "" + +#: library/builtins.rst:46 +msgid ":ref:`bltin-types`" +msgstr "" diff --git a/library/calendar.po b/library/calendar.po index 075530d59..54a138c31 100644 --- a/library/calendar.po +++ b/library/calendar.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -233,10 +233,21 @@ msgid "" "A list of CSS classes used for each weekday. The default class list is::" msgstr "" +#: library/calendar.rst:213 +msgid "" +"cssclasses = [\"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\", \"sun\"]" +msgstr "" + #: library/calendar.rst:215 msgid "more styles can be added for each day::" msgstr "" +#: library/calendar.rst:217 +msgid "" +"cssclasses = [\"mon text-bold\", \"tue\", \"wed\", \"thu\", \"fri\", " +"\"sat\", \"sun red\"]" +msgstr "" + #: library/calendar.rst:219 msgid "Note that the length of this list must be seven items." msgstr "" @@ -282,10 +293,24 @@ msgid "" "single CSS class with a space separated list of CSS classes, for example::" msgstr "" +#: library/calendar.rst:273 +msgid "\"text-bold text-red\"" +msgstr "" + #: library/calendar.rst:275 msgid "Here is an example how :class:`!HTMLCalendar` can be customized::" msgstr "" +#: library/calendar.rst:277 +msgid "" +"class CustomHTMLCal(calendar.HTMLCalendar):\n" +" cssclasses = [style + \" text-nowrap\" for style in\n" +" calendar.HTMLCalendar.cssclasses]\n" +" cssclass_month_head = \"text-center month-head\"\n" +" cssclass_month = \"text-center month\"\n" +" cssclass_year = \"text-italic lead\"" +msgstr "" + #: library/calendar.rst:287 msgid "" "This subclass of :class:`TextCalendar` can be passed a locale name in the " @@ -318,6 +343,12 @@ msgid "" "provided for convenience. For example, to set the first weekday to Sunday::" msgstr "" +#: library/calendar.rst:314 +msgid "" +"import calendar\n" +"calendar.setfirstweekday(calendar.SUNDAY)" +msgstr "" + #: library/calendar.rst:320 msgid "Returns the current setting for the weekday to start each week." msgstr "" @@ -397,177 +428,227 @@ msgid "The :mod:`calendar` module exports the following data attributes:" msgstr "" #: library/calendar.rst:396 -msgid "An array that represents the days of the week in the current locale." +msgid "" +"A sequence that represents the days of the week in the current locale, where " +"Monday is day number 0." msgstr "" -#: library/calendar.rst:401 +#: library/calendar.rst:406 msgid "" -"An array that represents the abbreviated days of the week in the current " -"locale." +"A sequence that represents the abbreviated days of the week in the current " +"locale, where Mon is day number 0." msgstr "" -#: library/calendar.rst:412 +#: library/calendar.rst:421 msgid "" "Aliases for the days of the week, where ``MONDAY`` is ``0`` and ``SUNDAY`` " "is ``6``." msgstr "" -#: library/calendar.rst:420 +#: library/calendar.rst:429 msgid "" "Enumeration defining days of the week as integer constants. The members of " "this enumeration are exported to the module scope as :data:`MONDAY` through :" "data:`SUNDAY`." msgstr "" -#: library/calendar.rst:429 +#: library/calendar.rst:438 msgid "" -"An array that represents the months of the year in the current locale. This " -"follows normal convention of January being month number 1, so it has a " +"A sequence that represents the months of the year in the current locale. " +"This follows normal convention of January being month number 1, so it has a " "length of 13 and ``month_name[0]`` is the empty string." msgstr "" -#: library/calendar.rst:436 +#: library/calendar.rst:449 msgid "" -"An array that represents the abbreviated months of the year in the current " +"A sequence that represents the abbreviated months of the year in the current " "locale. This follows normal convention of January being month number 1, so " "it has a length of 13 and ``month_abbr[0]`` is the empty string." msgstr "" -#: library/calendar.rst:454 +#: library/calendar.rst:470 msgid "" "Aliases for the months of the year, where ``JANUARY`` is ``1`` and " "``DECEMBER`` is ``12``." msgstr "" -#: library/calendar.rst:462 +#: library/calendar.rst:478 msgid "" "Enumeration defining months of the year as integer constants. The members of " "this enumeration are exported to the module scope as :data:`JANUARY` " "through :data:`DECEMBER`." msgstr "" -#: library/calendar.rst:469 +#: library/calendar.rst:485 msgid "The :mod:`calendar` module defines the following exceptions:" msgstr "" -#: library/calendar.rst:473 +#: library/calendar.rst:489 msgid "" "A subclass of :exc:`ValueError`, raised when the given month number is " "outside of the range 1-12 (inclusive)." msgstr "" -#: library/calendar.rst:478 +#: library/calendar.rst:494 msgid "The invalid month number." msgstr "" -#: library/calendar.rst:483 +#: library/calendar.rst:499 msgid "" "A subclass of :exc:`ValueError`, raised when the given weekday number is " "outside of the range 0-6 (inclusive)." msgstr "" -#: library/calendar.rst:488 +#: library/calendar.rst:504 msgid "The invalid weekday number." msgstr "" -#: library/calendar.rst:493 +#: library/calendar.rst:509 msgid "Module :mod:`datetime`" msgstr "" -#: library/calendar.rst:494 +#: library/calendar.rst:510 msgid "" "Object-oriented interface to dates and times with similar functionality to " "the :mod:`time` module." msgstr "" -#: library/calendar.rst:497 +#: library/calendar.rst:513 msgid "Module :mod:`time`" msgstr "" -#: library/calendar.rst:498 +#: library/calendar.rst:514 msgid "Low-level time related functions." msgstr "" -#: library/calendar.rst:504 +#: library/calendar.rst:520 msgid "Command-Line Usage" msgstr "" -#: library/calendar.rst:508 +#: library/calendar.rst:524 msgid "" "The :mod:`calendar` module can be executed as a script from the command line " "to interactively print a calendar." msgstr "" -#: library/calendar.rst:518 +#: library/calendar.rst:527 +msgid "" +"python -m calendar [-h] [-L LOCALE] [-e ENCODING] [-t {text,html}]\n" +" [-w WIDTH] [-l LINES] [-s SPACING] [-m MONTHS] [-c CSS]\n" +" [year] [month]" +msgstr "" + +#: library/calendar.rst:534 msgid "For example, to print a calendar for the year 2000:" msgstr "" -#: library/calendar.rst:561 +#: library/calendar.rst:536 +msgid "" +"$ python -m calendar 2000\n" +" 2000\n" +"\n" +" January February March\n" +"Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n" +" 1 2 1 2 3 4 5 6 1 2 3 4 5\n" +" 3 4 5 6 7 8 9 7 8 9 10 11 12 13 6 7 8 9 10 11 12\n" +"10 11 12 13 14 15 16 14 15 16 17 18 19 20 13 14 15 16 17 18 19\n" +"17 18 19 20 21 22 23 21 22 23 24 25 26 27 20 21 22 23 24 25 26\n" +"24 25 26 27 28 29 30 28 29 27 28 29 30 31\n" +"31\n" +"\n" +" April May June\n" +"Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n" +" 1 2 1 2 3 4 5 6 7 1 2 3 4\n" +" 3 4 5 6 7 8 9 8 9 10 11 12 13 14 5 6 7 8 9 10 11\n" +"10 11 12 13 14 15 16 15 16 17 18 19 20 21 12 13 14 15 16 17 18\n" +"17 18 19 20 21 22 23 22 23 24 25 26 27 28 19 20 21 22 23 24 25\n" +"24 25 26 27 28 29 30 29 30 31 26 27 28 29 30\n" +"\n" +" July August September\n" +"Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n" +" 1 2 1 2 3 4 5 6 1 2 3\n" +" 3 4 5 6 7 8 9 7 8 9 10 11 12 13 4 5 6 7 8 9 10\n" +"10 11 12 13 14 15 16 14 15 16 17 18 19 20 11 12 13 14 15 16 17\n" +"17 18 19 20 21 22 23 21 22 23 24 25 26 27 18 19 20 21 22 23 24\n" +"24 25 26 27 28 29 30 28 29 30 31 25 26 27 28 29 30\n" +"31\n" +"\n" +" October November December\n" +"Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n" +" 1 1 2 3 4 5 1 2 3\n" +" 2 3 4 5 6 7 8 6 7 8 9 10 11 12 4 5 6 7 8 9 10\n" +" 9 10 11 12 13 14 15 13 14 15 16 17 18 19 11 12 13 14 15 16 17\n" +"16 17 18 19 20 21 22 20 21 22 23 24 25 26 18 19 20 21 22 23 24\n" +"23 24 25 26 27 28 29 27 28 29 30 25 26 27 28 29 30 31\n" +"30 31" +msgstr "" + +#: library/calendar.rst:577 msgid "The following options are accepted:" msgstr "" -#: library/calendar.rst:568 +#: library/calendar.rst:584 msgid "Show the help message and exit." msgstr "" -#: library/calendar.rst:573 +#: library/calendar.rst:589 msgid "The locale to use for month and weekday names. Defaults to English." msgstr "" -#: library/calendar.rst:579 +#: library/calendar.rst:595 msgid "" "The encoding to use for output. :option:`--encoding` is required if :option:" "`--locale` is set." msgstr "" -#: library/calendar.rst:585 +#: library/calendar.rst:601 msgid "Print the calendar to the terminal as text, or as an HTML document." msgstr "" -#: library/calendar.rst:591 +#: library/calendar.rst:607 msgid "" "The year to print the calendar for. Must be a number between 1 and 9999. " "Defaults to the current year." msgstr "" -#: library/calendar.rst:598 +#: library/calendar.rst:614 msgid "" "The month of the specified :option:`year` to print the calendar for. Must be " "a number between 1 and 12, and may only be used in text mode. Defaults to " "printing a calendar for the full year." msgstr "" -#: library/calendar.rst:604 +#: library/calendar.rst:620 msgid "*Text-mode options:*" msgstr "" -#: library/calendar.rst:608 +#: library/calendar.rst:624 msgid "" "The width of the date column in terminal columns. The date is printed " "centred in the column. Any value lower than 2 is ignored. Defaults to 2." msgstr "" -#: library/calendar.rst:616 +#: library/calendar.rst:632 msgid "" "The number of lines for each week in terminal rows. The date is printed top-" "aligned. Any value lower than 1 is ignored. Defaults to 1." msgstr "" -#: library/calendar.rst:624 +#: library/calendar.rst:640 msgid "" "The space between months in columns. Any value lower than 2 is ignored. " "Defaults to 6." msgstr "" -#: library/calendar.rst:631 +#: library/calendar.rst:647 msgid "The number of months printed per row. Defaults to 3." msgstr "" -#: library/calendar.rst:635 +#: library/calendar.rst:651 msgid "*HTML-mode options:*" msgstr "" -#: library/calendar.rst:639 +#: library/calendar.rst:655 msgid "" "The path of a CSS stylesheet to use for the calendar. This must either be " "relative to the generated HTML, or an absolute HTTP or ``file:///`` URL." diff --git a/library/cgi.po b/library/cgi.po index 2f63175aa..58f3eb7d9 100644 --- a/library/cgi.po +++ b/library/cgi.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -57,7 +57,7 @@ msgid "" msgstr "" #: includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not Emscripten, not WASI." +msgid "Availability" msgstr "" #: includes/wasm-notavail.rst:5 @@ -105,6 +105,12 @@ msgid "" "header section looks like this::" msgstr "" +#: library/cgi.rst:68 +msgid "" +"print(\"Content-Type: text/html\") # HTML is following\n" +"print() # blank line, end of headers" +msgstr "" + #: library/cgi.rst:71 msgid "" "The second section is usually HTML, which allows the client software to " @@ -112,6 +118,13 @@ msgid "" "Python code that prints a simple piece of HTML::" msgstr "" +#: library/cgi.rst:75 +msgid "" +"print(\"CGI script output\")\n" +"print(\"

This is my first CGI script

\")\n" +"print(\"Hello, world!\")" +msgstr "" + #: library/cgi.rst:83 msgid "Using the cgi module" msgstr "" @@ -124,6 +137,12 @@ msgstr "" msgid "When you write a new script, consider adding these lines::" msgstr "" +#: library/cgi.rst:505 +msgid "" +"import cgitb\n" +"cgitb.enable()" +msgstr "" + #: library/cgi.rst:92 msgid "" "This activates a special exception handler that will display detailed " @@ -132,6 +151,12 @@ msgid "" "saved to files instead, with code like this::" msgstr "" +#: library/cgi.rst:97 +msgid "" +"import cgitb\n" +"cgitb.enable(display=0, logdir=\"/path/to/logdir\")" +msgstr "" + #: library/cgi.rst:100 msgid "" "It's very helpful to use this feature during script development. The reports " @@ -170,6 +195,18 @@ msgid "" "the fields ``name`` and ``addr`` are both set to a non-empty string::" msgstr "" +#: library/cgi.rst:127 +msgid "" +"form = cgi.FieldStorage()\n" +"if \"name\" not in form or \"addr\" not in form:\n" +" print(\"

Error

\")\n" +" print(\"Please fill in the name and addr fields.\")\n" +" return\n" +"print(\"

name:\", form[\"name\"].value)\n" +"print(\"

addr:\", form[\"addr\"].value)\n" +"...further form processing here..." +msgstr "" + #: library/cgi.rst:136 msgid "" "Here the fields, accessed through ``form[key]``, are themselves instances " @@ -193,6 +230,12 @@ msgid "" "username fields, separated by commas::" msgstr "" +#: library/cgi.rst:153 +msgid "" +"value = form.getlist(\"username\")\n" +"usernames = \",\".join(value)" +msgstr "" + #: library/cgi.rst:156 msgid "" "If a field represents an uploaded file, accessing the value via the :attr:" @@ -206,6 +249,18 @@ msgid "" "IOBase.readline` methods will return bytes)::" msgstr "" +#: library/cgi.rst:167 +msgid "" +"fileitem = form[\"userfile\"]\n" +"if fileitem.file:\n" +" # It's an uploaded file; count lines\n" +" linecount = 0\n" +" while True:\n" +" line = fileitem.file.readline()\n" +" if not line: break\n" +" linecount = linecount + 1" +msgstr "" + #: library/cgi.rst:176 msgid "" ":class:`FieldStorage` objects also support being used in a :keyword:`with` " @@ -285,12 +340,27 @@ msgid "" "expected a user to post more than one value under one name::" msgstr "" +#: library/cgi.rst:228 +msgid "" +"item = form.getvalue(\"item\")\n" +"if isinstance(item, list):\n" +" # The user is requesting more than one item.\n" +"else:\n" +" # The user is requesting only one item." +msgstr "" + #: library/cgi.rst:234 msgid "" "This situation is common for example when a form contains a group of " "multiple checkboxes with the same name::" msgstr "" +#: library/cgi.rst:237 +msgid "" +"\n" +"" +msgstr "" + #: library/cgi.rst:240 msgid "" "In most situations, however, there's only one form control with a particular " @@ -298,6 +368,10 @@ msgid "" "this name. So you write a script containing for example this code::" msgstr "" +#: library/cgi.rst:244 +msgid "user = form.getvalue(\"user\").upper()" +msgstr "" + #: library/cgi.rst:246 msgid "" "The problem with the code is that you should never expect that a client will " @@ -346,6 +420,15 @@ msgstr "" msgid "Using these methods you can write nice compact code::" msgstr "" +#: library/cgi.rst:281 +msgid "" +"import cgi\n" +"form = cgi.FieldStorage()\n" +"user = form.getfirst(\"user\", \"\").upper() # This way it's safe.\n" +"for item in form.getlist(\"item\"):\n" +" do_something(item)" +msgstr "" + #: library/cgi.rst:291 msgid "Functions" msgstr "" @@ -428,6 +511,14 @@ msgstr "" msgid "For example, with :class:`email.message.EmailMessage`::" msgstr "" +#: library/cgi.rst:352 +msgid "" +"from email.message import EmailMessage\n" +"msg = EmailMessage()\n" +"msg['content-type'] = 'application/json; charset=\"utf8\"'\n" +"main, params = msg.get_content_type(), msg['content-type'].params" +msgstr "" + #: library/cgi.rst:360 msgid "" "Robust test CGI script, usable as main program. Writes minimal HTTP headers " @@ -491,6 +582,10 @@ msgid "" "column 1 followed by the pathname of the Python interpreter, for instance::" msgstr "" +#: library/cgi.rst:416 +msgid "#!/usr/local/bin/python" +msgstr "" + #: library/cgi.rst:418 msgid "" "Make sure the Python interpreter exists and is executable by \"others\"." @@ -518,6 +613,13 @@ msgid "" "importing other modules. For example::" msgstr "" +#: library/cgi.rst:435 +msgid "" +"import sys\n" +"sys.path.insert(0, \"/usr/home/joe/lib/python\")\n" +"sys.path.insert(0, \"/usr/local/lib/python\")" +msgstr "" + #: library/cgi.rst:439 msgid "(This way, the directory inserted last will be searched first!)" msgstr "" @@ -565,6 +667,10 @@ msgid "" "your browser of the form:" msgstr "" +#: library/cgi.rst:473 +msgid "http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home" +msgstr "" + #: library/cgi.rst:477 msgid "" "If this gives an error of type 404, the server cannot find the script -- " @@ -583,6 +689,10 @@ msgid "" "from your script: replace its main code with the single statement ::" msgstr "" +#: library/cgi.rst:489 +msgid "cgi.test()" +msgstr "" + #: library/cgi.rst:491 msgid "" "This should produce the same results as those gotten from installing the :" @@ -620,6 +730,15 @@ msgid "" "modules)::" msgstr "" +#: library/cgi.rst:515 +msgid "" +"import sys\n" +"sys.stderr = sys.stdout\n" +"print(\"Content-Type: text/plain\")\n" +"print()\n" +"...your code here..." +msgstr "" + #: library/cgi.rst:521 msgid "" "This relies on the Python interpreter to print the traceback. The content " diff --git a/library/cgitb.po b/library/cgitb.po index 7b5a47975..e90d61979 100644 --- a/library/cgitb.po +++ b/library/cgitb.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -48,6 +48,12 @@ msgstr "" msgid "To enable this feature, simply add this to the top of your CGI script::" msgstr "" +#: library/cgitb.rst:37 +msgid "" +"import cgitb\n" +"cgitb.enable()" +msgstr "" + #: library/cgitb.rst:40 msgid "" "The options to the :func:`enable` function control whether the report is " diff --git a/library/cmath.po b/library/cmath.po index 58e3d60b0..4f1d65ca8 100644 --- a/library/cmath.po +++ b/library/cmath.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -50,12 +50,24 @@ msgid "" "imaginary axis::" msgstr "" +#: library/cmath.rst:31 +msgid "" +">>> cmath.sqrt(complex(-2.0, -0.0))\n" +"-1.4142135623730951j" +msgstr "" + #: library/cmath.rst:34 msgid "" "But an argument of ``complex(-2.0, 0.0)`` is treated as though it lies above " "the branch cut::" msgstr "" +#: library/cmath.rst:37 +msgid "" +">>> cmath.sqrt(complex(-2.0, 0.0))\n" +"1.4142135623730951j" +msgstr "" + #: library/cmath.rst:42 msgid "Conversions to and from polar coordinates" msgstr "" @@ -92,6 +104,14 @@ msgid "" "sign of ``x.imag``, even when ``x.imag`` is zero::" msgstr "" +#: library/cmath.rst:66 +msgid "" +">>> phase(complex(-1.0, 0.0))\n" +"3.141592653589793\n" +">>> phase(complex(-1.0, -0.0))\n" +"-3.141592653589793" +msgstr "" + #: library/cmath.rst:74 msgid "" "The modulus (absolute value) of a complex number *x* can be computed using " diff --git a/library/cmd.po b/library/cmd.po index a7ff76d54..6a3a70c22 100644 --- a/library/cmd.po +++ b/library/cmd.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -304,6 +304,86 @@ msgid "" "attr:`~Cmd.cmdqueue` for immediate playback::" msgstr "" +#: library/cmd.rst:255 +msgid "" +"import cmd, sys\n" +"from turtle import *\n" +"\n" +"class TurtleShell(cmd.Cmd):\n" +" intro = 'Welcome to the turtle shell. Type help or ? to list commands." +"\\n'\n" +" prompt = '(turtle) '\n" +" file = None\n" +"\n" +" # ----- basic turtle commands -----\n" +" def do_forward(self, arg):\n" +" 'Move the turtle forward by the specified distance: FORWARD 10'\n" +" forward(*parse(arg))\n" +" def do_right(self, arg):\n" +" 'Turn turtle right by given number of degrees: RIGHT 20'\n" +" right(*parse(arg))\n" +" def do_left(self, arg):\n" +" 'Turn turtle left by given number of degrees: LEFT 90'\n" +" left(*parse(arg))\n" +" def do_goto(self, arg):\n" +" 'Move turtle to an absolute position with changing orientation. " +"GOTO 100 200'\n" +" goto(*parse(arg))\n" +" def do_home(self, arg):\n" +" 'Return turtle to the home position: HOME'\n" +" home()\n" +" def do_circle(self, arg):\n" +" 'Draw circle with given radius an options extent and steps: CIRCLE " +"50'\n" +" circle(*parse(arg))\n" +" def do_position(self, arg):\n" +" 'Print the current turtle position: POSITION'\n" +" print('Current position is %d %d\\n' % position())\n" +" def do_heading(self, arg):\n" +" 'Print the current turtle heading in degrees: HEADING'\n" +" print('Current heading is %d\\n' % (heading(),))\n" +" def do_color(self, arg):\n" +" 'Set the color: COLOR BLUE'\n" +" color(arg.lower())\n" +" def do_undo(self, arg):\n" +" 'Undo (repeatedly) the last turtle action(s): UNDO'\n" +" def do_reset(self, arg):\n" +" 'Clear the screen and return turtle to center: RESET'\n" +" reset()\n" +" def do_bye(self, arg):\n" +" 'Stop recording, close the turtle window, and exit: BYE'\n" +" print('Thank you for using Turtle')\n" +" self.close()\n" +" bye()\n" +" return True\n" +"\n" +" # ----- record and playback -----\n" +" def do_record(self, arg):\n" +" 'Save future commands to filename: RECORD rose.cmd'\n" +" self.file = open(arg, 'w')\n" +" def do_playback(self, arg):\n" +" 'Playback commands from a file: PLAYBACK rose.cmd'\n" +" self.close()\n" +" with open(arg) as f:\n" +" self.cmdqueue.extend(f.read().splitlines())\n" +" def precmd(self, line):\n" +" line = line.lower()\n" +" if self.file and 'playback' not in line:\n" +" print(line, file=self.file)\n" +" return line\n" +" def close(self):\n" +" if self.file:\n" +" self.file.close()\n" +" self.file = None\n" +"\n" +"def parse(arg):\n" +" 'Convert a series of zero or more numbers to an argument tuple'\n" +" return tuple(map(int, arg.split()))\n" +"\n" +"if __name__ == '__main__':\n" +" TurtleShell().cmdloop()" +msgstr "" + #: library/cmd.rst:330 msgid "" "Here is a sample session with the turtle shell showing the help functions, " @@ -311,6 +391,67 @@ msgid "" "facility:" msgstr "" +#: library/cmd.rst:333 +msgid "" +"Welcome to the turtle shell. Type help or ? to list commands.\n" +"\n" +"(turtle) ?\n" +"\n" +"Documented commands (type help ):\n" +"========================================\n" +"bye color goto home playback record right\n" +"circle forward heading left position reset undo\n" +"\n" +"(turtle) help forward\n" +"Move the turtle forward by the specified distance: FORWARD 10\n" +"(turtle) record spiral.cmd\n" +"(turtle) position\n" +"Current position is 0 0\n" +"\n" +"(turtle) heading\n" +"Current heading is 0\n" +"\n" +"(turtle) reset\n" +"(turtle) circle 20\n" +"(turtle) right 30\n" +"(turtle) circle 40\n" +"(turtle) right 30\n" +"(turtle) circle 60\n" +"(turtle) right 30\n" +"(turtle) circle 80\n" +"(turtle) right 30\n" +"(turtle) circle 100\n" +"(turtle) right 30\n" +"(turtle) circle 120\n" +"(turtle) right 30\n" +"(turtle) circle 120\n" +"(turtle) heading\n" +"Current heading is 180\n" +"\n" +"(turtle) forward 100\n" +"(turtle)\n" +"(turtle) right 90\n" +"(turtle) forward 100\n" +"(turtle)\n" +"(turtle) right 90\n" +"(turtle) forward 400\n" +"(turtle) right 90\n" +"(turtle) forward 500\n" +"(turtle) right 90\n" +"(turtle) forward 400\n" +"(turtle) right 90\n" +"(turtle) forward 300\n" +"(turtle) playback spiral.cmd\n" +"Current position is 0 0\n" +"\n" +"Current heading is 0\n" +"\n" +"Current heading is 180\n" +"\n" +"(turtle) bye\n" +"Thank you for using Turtle" +msgstr "" + #: library/cmd.rst:64 msgid "? (question mark)" msgstr "" diff --git a/library/codecs.po b/library/codecs.po index f8d373ed6..66d2f8519 100644 --- a/library/codecs.po +++ b/library/codecs.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -2624,7 +2624,7 @@ msgid "This module implements the ANSI codepage (CP_ACP)." msgstr "" #: library/codecs.rst:1543 -msgid ":ref:`Availability `: Windows." +msgid "Availability" msgstr "" #: library/codecs.rst:1545 diff --git a/library/collections.abc.po b/library/collections.abc.po index fc1704ec3..4e68c3896 100644 --- a/library/collections.abc.po +++ b/library/collections.abc.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -50,6 +50,24 @@ msgid "" "desired. Other methods may be added as needed:" msgstr "" +#: library/collections.abc.rst:35 +msgid "" +"class C(Sequence): # Direct inheritance\n" +" def __init__(self): ... # Extra method not required by the " +"ABC\n" +" def __getitem__(self, index): ... # Required abstract method\n" +" def __len__(self): ... # Required abstract method\n" +" def count(self, value): ... # Optionally override a mixin method" +msgstr "" + +#: library/collections.abc.rst:43 +msgid "" +">>> issubclass(C, Sequence)\n" +"True\n" +">>> isinstance(C(), Sequence)\n" +"True" +msgstr "" + #: library/collections.abc.rst:50 msgid "" "2) Existing classes and built-in classes can be registered as \"virtual " @@ -60,6 +78,27 @@ msgid "" "rule is for methods that are automatically inferred from the rest of the API:" msgstr "" +#: library/collections.abc.rst:58 +msgid "" +"class D: # No inheritance\n" +" def __init__(self): ... # Extra method not required by the " +"ABC\n" +" def __getitem__(self, index): ... # Abstract method\n" +" def __len__(self): ... # Abstract method\n" +" def count(self, value): ... # Mixin method\n" +" def index(self, value): ... # Mixin method\n" +"\n" +"Sequence.register(D) # Register instead of inherit" +msgstr "" + +#: library/collections.abc.rst:69 +msgid "" +">>> issubclass(D, Sequence)\n" +"True\n" +">>> isinstance(D(), Sequence)\n" +"True" +msgstr "" + #: library/collections.abc.rst:76 msgid "" "In this example, class :class:`!D` does not need to define ``__contains__``, " @@ -75,6 +114,21 @@ msgid "" "required methods (unless those methods have been set to :const:`None`):" msgstr "" +#: library/collections.abc.rst:86 +msgid "" +"class E:\n" +" def __iter__(self): ...\n" +" def __next__(self): ..." +msgstr "" + +#: library/collections.abc.rst:92 +msgid "" +">>> issubclass(E, Iterable)\n" +"True\n" +">>> isinstance(E(), Iterable)\n" +"True" +msgstr "" + #: library/collections.abc.rst:99 msgid "" "Complex interfaces do not support this last technique because an interface " @@ -441,11 +495,17 @@ msgstr "" msgid "ABC for classes that provide the :meth:`~object.__call__` method." msgstr "" -#: library/collections.abc.rst:221 +#: library/collections.abc.rst:219 +msgid "" +"See :ref:`annotating-callables` for details on how to use :class:`!Callable` " +"in type annotations." +msgstr "" + +#: library/collections.abc.rst:224 msgid "ABC for classes that provide the :meth:`~container.__iter__` method." msgstr "" -#: library/collections.abc.rst:223 +#: library/collections.abc.rst:226 msgid "" "Checking ``isinstance(obj, Iterable)`` detects classes that are registered " "as :class:`Iterable` or that have an :meth:`~container.__iter__` method, but " @@ -454,23 +514,23 @@ msgid "" "`iterable` is to call ``iter(obj)``." msgstr "" -#: library/collections.abc.rst:232 +#: library/collections.abc.rst:235 msgid "ABC for sized iterable container classes." msgstr "" -#: library/collections.abc.rst:238 +#: library/collections.abc.rst:241 msgid "" "ABC for classes that provide the :meth:`~iterator.__iter__` and :meth:" "`~iterator.__next__` methods. See also the definition of :term:`iterator`." msgstr "" -#: library/collections.abc.rst:244 +#: library/collections.abc.rst:247 msgid "" "ABC for iterable classes that also provide the :meth:`~object.__reversed__` " "method." msgstr "" -#: library/collections.abc.rst:251 +#: library/collections.abc.rst:254 msgid "" "ABC for :term:`generator` classes that implement the protocol defined in :" "pep:`342` that extends :term:`iterators ` with the :meth:" @@ -478,11 +538,17 @@ msgid "" "methods." msgstr "" -#: library/collections.abc.rst:262 +#: library/collections.abc.rst:259 +msgid "" +"See :ref:`annotating-generators-and-coroutines` for details on using :class:" +"`!Generator` in type annotations." +msgstr "" + +#: library/collections.abc.rst:268 msgid "ABCs for read-only and mutable :term:`sequences `." msgstr "" -#: library/collections.abc.rst:264 +#: library/collections.abc.rst:270 msgid "" "Implementation note: Some of the mixin methods, such as :meth:`~container." "__iter__`, :meth:`~object.__reversed__` and :meth:`index`, make repeated " @@ -493,44 +559,44 @@ msgid "" "quadratic performance and will likely need to be overridden." msgstr "" -#: library/collections.abc.rst:273 +#: library/collections.abc.rst:279 msgid "The index() method added support for *stop* and *start* arguments." msgstr "" -#: library/collections.abc.rst:277 +#: library/collections.abc.rst:283 msgid "" "The :class:`ByteString` ABC has been deprecated. For use in typing, prefer a " "union, like ``bytes | bytearray``, or :class:`collections.abc.Buffer`. For " "use as an ABC, prefer :class:`Sequence` or :class:`collections.abc.Buffer`." msgstr "" -#: library/collections.abc.rst:286 +#: library/collections.abc.rst:292 msgid "ABCs for read-only and mutable :ref:`sets `." msgstr "" -#: library/collections.abc.rst:291 +#: library/collections.abc.rst:297 msgid "ABCs for read-only and mutable :term:`mappings `." msgstr "" -#: library/collections.abc.rst:298 +#: library/collections.abc.rst:304 msgid "" "ABCs for mapping, items, keys, and values :term:`views `." msgstr "" -#: library/collections.abc.rst:302 +#: library/collections.abc.rst:308 msgid "" "ABC for :term:`awaitable` objects, which can be used in :keyword:`await` " "expressions. Custom implementations must provide the :meth:`~object." "__await__` method." msgstr "" -#: library/collections.abc.rst:306 +#: library/collections.abc.rst:312 msgid "" ":term:`Coroutine ` objects and instances of the :class:" "`~collections.abc.Coroutine` ABC are all instances of this ABC." msgstr "" -#: library/collections.abc.rst:310 +#: library/collections.abc.rst:316 msgid "" "In CPython, generator-based coroutines (:term:`generators ` " "decorated with :func:`@types.coroutine `) are *awaitables*, " @@ -539,7 +605,7 @@ msgid "" "`inspect.isawaitable` to detect them." msgstr "" -#: library/collections.abc.rst:320 +#: library/collections.abc.rst:326 msgid "" "ABC for :term:`coroutine` compatible classes. These implement the following " "methods, defined in :ref:`coroutine-objects`: :meth:`~coroutine.send`, :meth:" @@ -548,7 +614,7 @@ msgid "" "instances are also instances of :class:`Awaitable`." msgstr "" -#: library/collections.abc.rst:328 +#: library/collections.abc.rst:334 msgid "" "In CPython, generator-based coroutines (:term:`generators ` " "decorated with :func:`@types.coroutine `) are *awaitables*, " @@ -557,41 +623,61 @@ msgid "" "`inspect.isawaitable` to detect them." msgstr "" -#: library/collections.abc.rst:338 +#: library/collections.abc.rst:340 +msgid "" +"See :ref:`annotating-generators-and-coroutines` for details on using :class:" +"`!Coroutine` in type annotations. The variance and order of type parameters " +"correspond to those of :class:`Generator`." +msgstr "" + +#: library/collections.abc.rst:349 msgid "" "ABC for classes that provide an ``__aiter__`` method. See also the " "definition of :term:`asynchronous iterable`." msgstr "" -#: library/collections.abc.rst:345 +#: library/collections.abc.rst:356 msgid "" "ABC for classes that provide ``__aiter__`` and ``__anext__`` methods. See " "also the definition of :term:`asynchronous iterator`." msgstr "" -#: library/collections.abc.rst:352 +#: library/collections.abc.rst:363 msgid "" "ABC for :term:`asynchronous generator` classes that implement the protocol " "defined in :pep:`525` and :pep:`492`." msgstr "" -#: library/collections.abc.rst:359 +#: library/collections.abc.rst:366 +msgid "" +"See :ref:`annotating-generators-and-coroutines` for details on using :class:" +"`!AsyncGenerator` in type annotations." +msgstr "" + +#: library/collections.abc.rst:373 msgid "" "ABC for classes that provide the :meth:`~object.__buffer__` method, " "implementing the :ref:`buffer protocol `. See :pep:`688`." msgstr "" -#: library/collections.abc.rst:365 +#: library/collections.abc.rst:379 msgid "Examples and Recipes" msgstr "" -#: library/collections.abc.rst:367 +#: library/collections.abc.rst:381 msgid "" "ABCs allow us to ask classes or instances if they provide particular " "functionality, for example::" msgstr "" -#: library/collections.abc.rst:374 +#: library/collections.abc.rst:384 +msgid "" +"size = None\n" +"if isinstance(myvar, collections.abc.Sized):\n" +" size = len(myvar)" +msgstr "" + +#: library/collections.abc.rst:388 msgid "" "Several of the ABCs are also useful as mixins that make it easier to develop " "classes supporting container APIs. For example, to write a class supporting " @@ -601,11 +687,37 @@ msgid "" "methods such as :meth:`!__and__` and :meth:`~frozenset.isdisjoint`::" msgstr "" -#: library/collections.abc.rst:403 +#: library/collections.abc.rst:395 +msgid "" +"class ListBasedSet(collections.abc.Set):\n" +" ''' Alternate set implementation favoring space over speed\n" +" and not requiring the set elements to be hashable. '''\n" +" def __init__(self, iterable):\n" +" self.elements = lst = []\n" +" for value in iterable:\n" +" if value not in lst:\n" +" lst.append(value)\n" +"\n" +" def __iter__(self):\n" +" return iter(self.elements)\n" +"\n" +" def __contains__(self, value):\n" +" return value in self.elements\n" +"\n" +" def __len__(self):\n" +" return len(self.elements)\n" +"\n" +"s1 = ListBasedSet('abcdef')\n" +"s2 = ListBasedSet('defghi')\n" +"overlap = s1 & s2 # The __and__() method is supported " +"automatically" +msgstr "" + +#: library/collections.abc.rst:417 msgid "Notes on using :class:`Set` and :class:`MutableSet` as a mixin:" msgstr "" -#: library/collections.abc.rst:406 +#: library/collections.abc.rst:420 msgid "" "Since some set operations create new sets, the default mixin methods need a " "way to create new instances from an :term:`iterable`. The class constructor " @@ -618,14 +730,14 @@ msgid "" "iterable argument." msgstr "" -#: library/collections.abc.rst:417 +#: library/collections.abc.rst:431 msgid "" "To override the comparisons (presumably for speed, as the semantics are " "fixed), redefine :meth:`~object.__le__` and :meth:`~object.__ge__`, then the " "other operations will automatically follow suit." msgstr "" -#: library/collections.abc.rst:423 +#: library/collections.abc.rst:437 msgid "" "The :class:`Set` mixin provides a :meth:`!_hash` method to compute a hash " "value for the set; however, :meth:`~object.__hash__` is not defined because " @@ -634,12 +746,12 @@ msgid "" "define ``__hash__ = Set._hash``." msgstr "" -#: library/collections.abc.rst:431 +#: library/collections.abc.rst:445 msgid "" "`OrderedSet recipe `_ for an " "example built on :class:`MutableSet`." msgstr "" -#: library/collections.abc.rst:434 +#: library/collections.abc.rst:448 msgid "For more about ABCs, see the :mod:`abc` module and :pep:`3119`." msgstr "" diff --git a/library/collections.po b/library/collections.po index 29d2c518c..aa133e630 100644 --- a/library/collections.po +++ b/library/collections.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -198,12 +198,28 @@ msgid "" "the mappings last to first::" msgstr "" +#: library/collections.rst:105 +msgid "" +">>> baseline = {'music': 'bach', 'art': 'rembrandt'}\n" +">>> adjustments = {'art': 'van gogh', 'opera': 'carmen'}\n" +">>> list(ChainMap(adjustments, baseline))\n" +"['music', 'art', 'opera']" +msgstr "" + #: library/collections.rst:110 msgid "" "This gives the same ordering as a series of :meth:`dict.update` calls " "starting with the last mapping::" msgstr "" +#: library/collections.rst:113 +msgid "" +">>> combined = baseline.copy()\n" +">>> combined.update(adjustments)\n" +">>> list(combined)\n" +"['music', 'art', 'opera']" +msgstr "" + #: library/collections.rst:118 msgid "Added support for ``|`` and ``|=`` operators, specified in :pep:`584`." msgstr "" @@ -251,6 +267,12 @@ msgstr "" msgid "Example of simulating Python's internal lookup chain::" msgstr "" +#: library/collections.rst:153 +msgid "" +"import builtins\n" +"pylookup = ChainMap(locals(), globals(), vars(builtins))" +msgstr "" + #: library/collections.rst:156 msgid "" "Example of letting user specified command-line arguments take precedence " @@ -258,12 +280,50 @@ msgid "" "values::" msgstr "" +#: library/collections.rst:159 +msgid "" +"import os, argparse\n" +"\n" +"defaults = {'color': 'red', 'user': 'guest'}\n" +"\n" +"parser = argparse.ArgumentParser()\n" +"parser.add_argument('-u', '--user')\n" +"parser.add_argument('-c', '--color')\n" +"namespace = parser.parse_args()\n" +"command_line_args = {k: v for k, v in vars(namespace).items() if v is not " +"None}\n" +"\n" +"combined = ChainMap(command_line_args, os.environ, defaults)\n" +"print(combined['color'])\n" +"print(combined['user'])" +msgstr "" + #: library/collections.rst:173 msgid "" "Example patterns for using the :class:`ChainMap` class to simulate nested " "contexts::" msgstr "" +#: library/collections.rst:176 +msgid "" +"c = ChainMap() # Create root context\n" +"d = c.new_child() # Create nested child context\n" +"e = c.new_child() # Child of c, independent from d\n" +"e.maps[0] # Current context dictionary -- like Python's " +"locals()\n" +"e.maps[-1] # Root context -- like Python's globals()\n" +"e.parents # Enclosing context chain -- like Python's nonlocals\n" +"\n" +"d['x'] = 1 # Set value in current context\n" +"d['x'] # Get first key in the chain of contexts\n" +"del d['x'] # Delete from current context\n" +"list(d) # All nested values\n" +"k in d # Check all nested values\n" +"len(d) # Number of nested values\n" +"d.items() # All nested items\n" +"dict(d) # Flatten into a regular dictionary" +msgstr "" + #: library/collections.rst:192 msgid "" "The :class:`ChainMap` class only makes updates (writes and deletions) to the " @@ -272,6 +332,34 @@ msgid "" "subclass that updates keys found deeper in the chain::" msgstr "" +#: library/collections.rst:197 +msgid "" +"class DeepChainMap(ChainMap):\n" +" 'Variant of ChainMap that allows direct updates to inner scopes'\n" +"\n" +" def __setitem__(self, key, value):\n" +" for mapping in self.maps:\n" +" if key in mapping:\n" +" mapping[key] = value\n" +" return\n" +" self.maps[0][key] = value\n" +"\n" +" def __delitem__(self, key):\n" +" for mapping in self.maps:\n" +" if key in mapping:\n" +" del mapping[key]\n" +" return\n" +" raise KeyError(key)\n" +"\n" +">>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': " +"'yellow'})\n" +">>> d['lion'] = 'orange' # update an existing key two levels down\n" +">>> d['snake'] = 'red' # new keys get added to the topmost dict\n" +">>> del d['elephant'] # remove an existing key one level down\n" +">>> d # display result\n" +"DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})" +msgstr "" + #: library/collections.rst:223 msgid ":class:`Counter` objects" msgstr "" @@ -282,6 +370,24 @@ msgid "" "example::" msgstr "" +#: library/collections.rst:228 +msgid "" +">>> # Tally occurrences of words in a list\n" +">>> cnt = Counter()\n" +">>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:\n" +"... cnt[word] += 1\n" +"...\n" +">>> cnt\n" +"Counter({'blue': 3, 'red': 2, 'green': 1})\n" +"\n" +">>> # Find the ten most common words in Hamlet\n" +">>> import re\n" +">>> words = re.findall(r'\\w+', open('hamlet.txt').read().lower())\n" +">>> Counter(words).most_common(10)\n" +"[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),\n" +" ('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]" +msgstr "" + #: library/collections.rst:245 msgid "" "A :class:`Counter` is a :class:`dict` subclass for counting :term:`hashable` " @@ -391,6 +497,19 @@ msgstr "" msgid "Common patterns for working with :class:`Counter` objects::" msgstr "" +#: library/collections.rst:356 +msgid "" +"c.total() # total of all counts\n" +"c.clear() # reset all counts\n" +"list(c) # list unique elements\n" +"set(c) # convert to a set\n" +"dict(c) # convert to a regular dictionary\n" +"c.items() # convert to a list of (elem, cnt) pairs\n" +"Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs\n" +"c.most_common()[:-n-1:-1] # n least common elements\n" +"+c # remove zero and negative counts" +msgstr "" + #: library/collections.rst:366 msgid "" "Several mathematical operations are provided for combining :class:`Counter` " @@ -402,6 +521,24 @@ msgid "" "but the output will exclude results with counts of zero or less." msgstr "" +#: library/collections.rst:374 +msgid "" +">>> c = Counter(a=3, b=1)\n" +">>> d = Counter(a=1, b=2)\n" +">>> c + d # add two counters together: c[x] + d[x]\n" +"Counter({'a': 4, 'b': 3})\n" +">>> c - d # subtract (keeping only positive counts)\n" +"Counter({'a': 2})\n" +">>> c & d # intersection: min(c[x], d[x])\n" +"Counter({'a': 1, 'b': 1})\n" +">>> c | d # union: max(c[x], d[x])\n" +"Counter({'a': 3, 'b': 2})\n" +">>> c == d # equality: c[x] == d[x]\n" +"False\n" +">>> c <= d # inclusion: c[x] <= d[x]\n" +"False" +msgstr "" + #: library/collections.rst:391 msgid "" "Unary addition and subtraction are shortcuts for adding an empty counter or " @@ -487,6 +624,11 @@ msgid "" "elements, see :func:`itertools.combinations_with_replacement`::" msgstr "" +#: library/collections.rst:447 +msgid "" +"map(Counter, combinations_with_replacement('ABC', 2)) # --> AA AB AC BB BC CC" +msgstr "" + #: library/collections.rst:451 msgid ":class:`deque` objects" msgstr "" @@ -642,6 +784,62 @@ msgstr "" msgid "Example:" msgstr "" +#: library/collections.rst:596 +msgid "" +">>> from collections import deque\n" +">>> d = deque('ghi') # make a new deque with three items\n" +">>> for elem in d: # iterate over the deque's elements\n" +"... print(elem.upper())\n" +"G\n" +"H\n" +"I\n" +"\n" +">>> d.append('j') # add a new entry to the right side\n" +">>> d.appendleft('f') # add a new entry to the left side\n" +">>> d # show the representation of the deque\n" +"deque(['f', 'g', 'h', 'i', 'j'])\n" +"\n" +">>> d.pop() # return and remove the rightmost item\n" +"'j'\n" +">>> d.popleft() # return and remove the leftmost item\n" +"'f'\n" +">>> list(d) # list the contents of the deque\n" +"['g', 'h', 'i']\n" +">>> d[0] # peek at leftmost item\n" +"'g'\n" +">>> d[-1] # peek at rightmost item\n" +"'i'\n" +"\n" +">>> list(reversed(d)) # list the contents of a deque in " +"reverse\n" +"['i', 'h', 'g']\n" +">>> 'h' in d # search the deque\n" +"True\n" +">>> d.extend('jkl') # add multiple elements at once\n" +">>> d\n" +"deque(['g', 'h', 'i', 'j', 'k', 'l'])\n" +">>> d.rotate(1) # right rotation\n" +">>> d\n" +"deque(['l', 'g', 'h', 'i', 'j', 'k'])\n" +">>> d.rotate(-1) # left rotation\n" +">>> d\n" +"deque(['g', 'h', 'i', 'j', 'k', 'l'])\n" +"\n" +">>> deque(reversed(d)) # make a new deque in reverse order\n" +"deque(['l', 'k', 'j', 'i', 'h', 'g'])\n" +">>> d.clear() # empty the deque\n" +">>> d.pop() # cannot pop from an empty deque\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in -toplevel-\n" +" d.pop()\n" +"IndexError: pop from an empty deque\n" +"\n" +">>> d.extendleft('abc') # extendleft() reverses the input " +"order\n" +">>> d\n" +"deque(['c', 'b', 'a'])" +msgstr "" + #: library/collections.rst:651 msgid ":class:`deque` Recipes" msgstr "" @@ -656,12 +854,35 @@ msgid "" "in Unix::" msgstr "" +#: library/collections.rst:658 +msgid "" +"def tail(filename, n=10):\n" +" 'Return the last n lines of a file'\n" +" with open(filename) as f:\n" +" return deque(f, n)" +msgstr "" + #: library/collections.rst:663 msgid "" "Another approach to using deques is to maintain a sequence of recently added " "elements by appending to the right and popping to the left::" msgstr "" +#: library/collections.rst:666 +msgid "" +"def moving_average(iterable, n=3):\n" +" # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0\n" +" # https://en.wikipedia.org/wiki/Moving_average\n" +" it = iter(iterable)\n" +" d = deque(itertools.islice(it, n-1))\n" +" d.appendleft(0)\n" +" s = sum(d)\n" +" for elem in it:\n" +" s += elem - d.popleft()\n" +" d.append(elem)\n" +" yield s / n" +msgstr "" + #: library/collections.rst:678 msgid "" "A `round-robin scheduler A D E B F C\"\n" +" iterators = deque(map(iter, iterables))\n" +" while iterators:\n" +" try:\n" +" while True:\n" +" yield next(iterators[0])\n" +" iterators.rotate(-1)\n" +" except StopIteration:\n" +" # Remove an exhausted iterator.\n" +" iterators.popleft()" +msgstr "" + #: library/collections.rst:697 msgid "" "The :meth:`~deque.rotate` method provides a way to implement :class:`deque` " @@ -679,6 +915,14 @@ msgid "" "d[n]`` relies on the ``rotate()`` method to position elements to be popped::" msgstr "" +#: library/collections.rst:701 +msgid "" +"def delete_nth(d, n):\n" +" d.rotate(-n)\n" +" d.popleft()\n" +" d.rotate(n)" +msgstr "" + #: library/collections.rst:706 msgid "" "To implement :class:`deque` slicing, use a similar approach applying :meth:" @@ -760,7 +1004,7 @@ msgid "" "absent." msgstr "" -#: library/collections.rst:1182 +#: library/collections.rst:1185 msgid "" "Added merge (``|``) and update (``|=``) operators, specified in :pep:`584`." msgstr "" @@ -872,8 +1116,8 @@ msgstr "" #: library/collections.rst:877 msgid "" -"If *module* is defined, the ``__module__`` attribute of the named tuple is " -"set to that value." +"If *module* is defined, the :attr:`~type.__module__` attribute of the named " +"tuple is set to that value." msgstr "" #: library/collections.rst:880 @@ -911,12 +1155,48 @@ msgid "" "Added the *defaults* parameter and the :attr:`_field_defaults` attribute." msgstr "" +#: library/collections.rst:903 +msgid "" +">>> # Basic example\n" +">>> Point = namedtuple('Point', ['x', 'y'])\n" +">>> p = Point(11, y=22) # instantiate with positional or keyword " +"arguments\n" +">>> p[0] + p[1] # indexable like the plain tuple (11, 22)\n" +"33\n" +">>> x, y = p # unpack like a regular tuple\n" +">>> x, y\n" +"(11, 22)\n" +">>> p.x + p.y # fields also accessible by name\n" +"33\n" +">>> p # readable __repr__ with a name=value style\n" +"Point(x=11, y=22)" +msgstr "" + #: library/collections.rst:919 msgid "" "Named tuples are especially useful for assigning field names to result " "tuples returned by the :mod:`csv` or :mod:`sqlite3` modules::" msgstr "" +#: library/collections.rst:922 +msgid "" +"EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, " +"paygrade')\n" +"\n" +"import csv\n" +"for emp in map(EmployeeRecord._make, csv.reader(open(\"employees.csv\", " +"\"rb\"))):\n" +" print(emp.name, emp.title)\n" +"\n" +"import sqlite3\n" +"conn = sqlite3.connect('/companydata')\n" +"cursor = conn.cursor()\n" +"cursor.execute('SELECT name, age, title, department, paygrade FROM " +"employees')\n" +"for emp in map(EmployeeRecord._make, cursor.fetchall()):\n" +" print(emp.name, emp.title)" +msgstr "" + #: library/collections.rst:935 msgid "" "In addition to the methods inherited from tuples, named tuples support three " @@ -929,12 +1209,26 @@ msgid "" "Class method that makes a new instance from an existing sequence or iterable." msgstr "" +#: library/collections.rst:943 +msgid "" +">>> t = [11, 22]\n" +">>> Point._make(t)\n" +"Point(x=11, y=22)" +msgstr "" + #: library/collections.rst:951 msgid "" "Return a new :class:`dict` which maps field names to their corresponding " "values:" msgstr "" +#: library/collections.rst:954 +msgid "" +">>> p = Point(x=11, y=22)\n" +">>> p._asdict()\n" +"{'x': 11, 'y': 22}" +msgstr "" + #: library/collections.rst:960 msgid "Returns an :class:`OrderedDict` instead of a regular :class:`dict`." msgstr "" @@ -953,16 +1247,47 @@ msgid "" "values::" msgstr "" +#: library/collections.rst:975 +msgid "" +">>> p = Point(x=11, y=22)\n" +">>> p._replace(x=33)\n" +"Point(x=33, y=22)\n" +"\n" +">>> for partnum, record in inventory.items():\n" +"... inventory[partnum] = record._replace(price=newprices[partnum], " +"timestamp=time.now())" +msgstr "" + #: library/collections.rst:984 msgid "" "Tuple of strings listing the field names. Useful for introspection and for " "creating new named tuple types from existing named tuples." msgstr "" +#: library/collections.rst:987 +msgid "" +">>> p._fields # view the field names\n" +"('x', 'y')\n" +"\n" +">>> Color = namedtuple('Color', 'red green blue')\n" +">>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)\n" +">>> Pixel(11, 22, 128, 255, 0)\n" +"Pixel(x=11, y=22, red=128, green=255, blue=0)" +msgstr "" + #: library/collections.rst:999 msgid "Dictionary mapping field names to default values." msgstr "" +#: library/collections.rst:1001 +msgid "" +">>> Account = namedtuple('Account', ['type', 'balance'], defaults=[0])\n" +">>> Account._field_defaults\n" +"{'balance': 0}\n" +">>> Account('premium')\n" +"Account(type='premium', balance=0)" +msgstr "" + #: library/collections.rst:1009 msgid "" "To retrieve a field whose name is stored in a string, use the :func:" @@ -982,6 +1307,23 @@ msgid "" "fixed-width print format:" msgstr "" +#: library/collections.rst:1026 +msgid "" +">>> class Point(namedtuple('Point', ['x', 'y'])):\n" +"... __slots__ = ()\n" +"... @property\n" +"... def hypot(self):\n" +"... return (self.x ** 2 + self.y ** 2) ** 0.5\n" +"... def __str__(self):\n" +"... return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, " +"self.hypot)\n" +"\n" +">>> for p in Point(3, 4), Point(14, 5/7):\n" +"... print(p)\n" +"Point: x= 3.000 y= 4.000 hypot= 5.000\n" +"Point: x=14.000 y= 0.714 hypot=14.018" +msgstr "" + #: library/collections.rst:1041 msgid "" "The subclass shown above sets ``__slots__`` to an empty tuple. This helps " @@ -1013,6 +1355,14 @@ msgid "" "keyword::" msgstr "" +#: library/collections.rst:1067 +msgid "" +"class Component(NamedTuple):\n" +" part_number: int\n" +" weight: float\n" +" description: Optional[str] = None" +msgstr "" + #: library/collections.rst:1072 msgid "" "See :meth:`types.SimpleNamespace` for a mutable namespace based on an " @@ -1136,39 +1486,54 @@ msgid "" "if *last* is false. Raises :exc:`KeyError` if the *key* does not exist:" msgstr "" +#: library/collections.rst:1151 +msgid "" +">>> d = OrderedDict.fromkeys('abcde')\n" +">>> d.move_to_end('b')\n" +">>> ''.join(d)\n" +"'acdeb'\n" +">>> d.move_to_end('b', last=False)\n" +">>> ''.join(d)\n" +"'bacde'" +msgstr "" + #: library/collections.rst:1163 msgid "" "In addition to the usual mapping methods, ordered dictionaries also support " "reverse iteration using :func:`reversed`." msgstr "" -#: library/collections.rst:1166 +#: library/collections.rst:1168 msgid "" "Equality tests between :class:`OrderedDict` objects are order-sensitive and " -"are implemented as ``list(od1.items())==list(od2.items())``. Equality tests " -"between :class:`OrderedDict` objects and other :class:`~collections.abc." -"Mapping` objects are order-insensitive like regular dictionaries. This " -"allows :class:`OrderedDict` objects to be substituted anywhere a regular " -"dictionary is used." +"are roughly equivalent to ``list(od1.items())==list(od2.items())``." msgstr "" -#: library/collections.rst:1173 +#: library/collections.rst:1171 +msgid "" +"Equality tests between :class:`OrderedDict` objects and other :class:" +"`~collections.abc.Mapping` objects are order-insensitive like regular " +"dictionaries. This allows :class:`OrderedDict` objects to be substituted " +"anywhere a regular dictionary is used." +msgstr "" + +#: library/collections.rst:1176 msgid "" "The items, keys, and values :term:`views ` of :class:" "`OrderedDict` now support reverse iteration using :func:`reversed`." msgstr "" -#: library/collections.rst:1177 +#: library/collections.rst:1180 msgid "" "With the acceptance of :pep:`468`, order is retained for keyword arguments " "passed to the :class:`OrderedDict` constructor and its :meth:`update` method." msgstr "" -#: library/collections.rst:1187 +#: library/collections.rst:1190 msgid ":class:`OrderedDict` Examples and Recipes" msgstr "" -#: library/collections.rst:1189 +#: library/collections.rst:1192 msgid "" "It is straightforward to create an ordered dictionary variant that remembers " "the order the keys were *last* inserted. If a new entry overwrites an " @@ -1176,17 +1541,92 @@ msgid "" "end::" msgstr "" -#: library/collections.rst:1201 +#: library/collections.rst:1197 +msgid "" +"class LastUpdatedOrderedDict(OrderedDict):\n" +" 'Store items in the order the keys were last added'\n" +"\n" +" def __setitem__(self, key, value):\n" +" super().__setitem__(key, value)\n" +" self.move_to_end(key)" +msgstr "" + +#: library/collections.rst:1204 msgid "" "An :class:`OrderedDict` would also be useful for implementing variants of :" "func:`functools.lru_cache`:" msgstr "" -#: library/collections.rst:1300 +#: library/collections.rst:1207 +msgid "" +"from collections import OrderedDict\n" +"from time import time\n" +"\n" +"class TimeBoundedLRU:\n" +" \"LRU Cache that invalidates and refreshes old entries.\"\n" +"\n" +" def __init__(self, func, maxsize=128, maxage=30):\n" +" self.cache = OrderedDict() # { args : (timestamp, result)}\n" +" self.func = func\n" +" self.maxsize = maxsize\n" +" self.maxage = maxage\n" +"\n" +" def __call__(self, *args):\n" +" if args in self.cache:\n" +" self.cache.move_to_end(args)\n" +" timestamp, result = self.cache[args]\n" +" if time() - timestamp <= self.maxage:\n" +" return result\n" +" result = self.func(*args)\n" +" self.cache[args] = time(), result\n" +" if len(self.cache) > self.maxsize:\n" +" self.cache.popitem(0)\n" +" return result" +msgstr "" + +#: library/collections.rst:1234 +msgid "" +"class MultiHitLRUCache:\n" +" \"\"\" LRU cache that defers caching a result until\n" +" it has been requested multiple times.\n" +"\n" +" To avoid flushing the LRU cache with one-time requests,\n" +" we don't cache until a request has been made more than once.\n" +"\n" +" \"\"\"\n" +"\n" +" def __init__(self, func, maxsize=128, maxrequests=4096, cache_after=1):\n" +" self.requests = OrderedDict() # { uncached_key : request_count }\n" +" self.cache = OrderedDict() # { cached_key : function_result }\n" +" self.func = func\n" +" self.maxrequests = maxrequests # max number of uncached requests\n" +" self.maxsize = maxsize # max number of stored return " +"values\n" +" self.cache_after = cache_after\n" +"\n" +" def __call__(self, *args):\n" +" if args in self.cache:\n" +" self.cache.move_to_end(args)\n" +" return self.cache[args]\n" +" result = self.func(*args)\n" +" self.requests[args] = self.requests.get(args, 0) + 1\n" +" if self.requests[args] <= self.cache_after:\n" +" self.requests.move_to_end(args)\n" +" if len(self.requests) > self.maxrequests:\n" +" self.requests.popitem(0)\n" +" else:\n" +" self.requests.pop(args, None)\n" +" self.cache[args] = result\n" +" if len(self.cache) > self.maxsize:\n" +" self.cache.popitem(0)\n" +" return result" +msgstr "" + +#: library/collections.rst:1303 msgid ":class:`UserDict` objects" msgstr "" -#: library/collections.rst:1302 +#: library/collections.rst:1305 msgid "" "The class, :class:`UserDict` acts as a wrapper around dictionary objects. " "The need for this class has been partially supplanted by the ability to " @@ -1194,7 +1634,7 @@ msgid "" "work with because the underlying dictionary is accessible as an attribute." msgstr "" -#: library/collections.rst:1310 +#: library/collections.rst:1313 msgid "" "Class that simulates a dictionary. The instance's contents are kept in a " "regular dictionary, which is accessible via the :attr:`data` attribute of :" @@ -1203,22 +1643,22 @@ msgid "" "not be kept, allowing it to be used for other purposes." msgstr "" -#: library/collections.rst:1316 +#: library/collections.rst:1319 msgid "" "In addition to supporting the methods and operations of mappings, :class:" "`UserDict` instances provide the following attribute:" msgstr "" -#: library/collections.rst:1321 +#: library/collections.rst:1324 msgid "" "A real dictionary used to store the contents of the :class:`UserDict` class." msgstr "" -#: library/collections.rst:1327 +#: library/collections.rst:1330 msgid ":class:`UserList` objects" msgstr "" -#: library/collections.rst:1329 +#: library/collections.rst:1332 msgid "" "This class acts as a wrapper around list objects. It is a useful base class " "for your own list-like classes which can inherit from them and override " @@ -1226,14 +1666,14 @@ msgid "" "lists." msgstr "" -#: library/collections.rst:1334 +#: library/collections.rst:1337 msgid "" "The need for this class has been partially supplanted by the ability to " "subclass directly from :class:`list`; however, this class can be easier to " "work with because the underlying list is accessible as an attribute." msgstr "" -#: library/collections.rst:1340 +#: library/collections.rst:1343 msgid "" "Class that simulates a list. The instance's contents are kept in a regular " "list, which is accessible via the :attr:`data` attribute of :class:" @@ -1242,19 +1682,19 @@ msgid "" "for example a real Python list or a :class:`UserList` object." msgstr "" -#: library/collections.rst:1346 +#: library/collections.rst:1349 msgid "" "In addition to supporting the methods and operations of mutable sequences, :" "class:`UserList` instances provide the following attribute:" msgstr "" -#: library/collections.rst:1351 +#: library/collections.rst:1354 msgid "" "A real :class:`list` object used to store the contents of the :class:" "`UserList` class." msgstr "" -#: library/collections.rst:1354 +#: library/collections.rst:1357 msgid "" "**Subclassing requirements:** Subclasses of :class:`UserList` are expected " "to offer a constructor which can be called with either no arguments or one " @@ -1264,7 +1704,7 @@ msgid "" "object used as a data source." msgstr "" -#: library/collections.rst:1361 +#: library/collections.rst:1364 msgid "" "If a derived class does not wish to comply with this requirement, all of the " "special methods supported by this class will need to be overridden; please " @@ -1272,11 +1712,11 @@ msgid "" "provided in that case." msgstr "" -#: library/collections.rst:1367 +#: library/collections.rst:1370 msgid ":class:`UserString` objects" msgstr "" -#: library/collections.rst:1369 +#: library/collections.rst:1372 msgid "" "The class, :class:`UserString` acts as a wrapper around string objects. The " "need for this class has been partially supplanted by the ability to subclass " @@ -1284,7 +1724,7 @@ msgid "" "because the underlying string is accessible as an attribute." msgstr "" -#: library/collections.rst:1377 +#: library/collections.rst:1380 msgid "" "Class that simulates a string object. The instance's content is kept in a " "regular string object, which is accessible via the :attr:`data` attribute " @@ -1293,19 +1733,19 @@ msgid "" "converted into a string using the built-in :func:`str` function." msgstr "" -#: library/collections.rst:1384 +#: library/collections.rst:1387 msgid "" "In addition to supporting the methods and operations of strings, :class:" "`UserString` instances provide the following attribute:" msgstr "" -#: library/collections.rst:1389 +#: library/collections.rst:1392 msgid "" "A real :class:`str` object used to store the contents of the :class:" "`UserString` class." msgstr "" -#: library/collections.rst:1392 +#: library/collections.rst:1395 msgid "" "New methods ``__getnewargs__``, ``__rmod__``, ``casefold``, ``format_map``, " "``isprintable``, and ``maketrans``." diff --git a/library/colorsys.po b/library/colorsys.po index b51c52202..fbeeede8f 100644 --- a/library/colorsys.po +++ b/library/colorsys.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -73,3 +73,12 @@ msgstr "" #: library/colorsys.rst:59 msgid "Example::" msgstr "" + +#: library/colorsys.rst:61 +msgid "" +">>> import colorsys\n" +">>> colorsys.rgb_to_hsv(0.2, 0.4, 0.4)\n" +"(0.5, 0.5, 0.4)\n" +">>> colorsys.hsv_to_rgb(0.5, 0.5, 0.4)\n" +"(0.2, 0.4, 0.4)" +msgstr "" diff --git a/library/compileall.po b/library/compileall.po index 3c48e014c..c6c32d583 100644 --- a/library/compileall.po +++ b/library/compileall.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -34,7 +34,7 @@ msgid "" msgstr "" #: includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not Emscripten, not WASI." +msgid "Availability" msgstr "" #: includes/wasm-notavail.rst:5 @@ -124,7 +124,7 @@ msgstr "" #: library/compileall.rst:92 msgid "" "Use *N* workers to compile the files within the given directory. If ``0`` is " -"used, then the result of :func:`os.cpu_count()` will be used." +"used, then the result of :func:`os.cpu_count` will be used." msgstr "" #: library/compileall.rst:98 @@ -382,6 +382,21 @@ msgid "" "subdirectory and all its subdirectories::" msgstr "" +#: library/compileall.rst:326 +msgid "" +"import compileall\n" +"\n" +"compileall.compile_dir('Lib/', force=True)\n" +"\n" +"# Perform same compilation, excluding files in .svn directories.\n" +"import re\n" +"compileall.compile_dir('Lib/', rx=re.compile(r'[/\\\\][.]svn'), force=True)\n" +"\n" +"# pathlib.Path objects can also be used.\n" +"import pathlib\n" +"compileall.compile_dir(pathlib.Path('Lib/'), force=True)" +msgstr "" + #: library/compileall.rst:340 msgid "Module :mod:`py_compile`" msgstr "" diff --git a/library/concurrent.futures.po b/library/concurrent.futures.po index 00d42bed6..ec2f9e06f 100644 --- a/library/concurrent.futures.po +++ b/library/concurrent.futures.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -41,7 +41,7 @@ msgid "" msgstr "" #: includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not Emscripten, not WASI." +msgid "Availability" msgstr "" #: includes/wasm-notavail.rst:5 @@ -68,6 +68,13 @@ msgid "" "callable. ::" msgstr "" +#: library/concurrent.futures.rst:38 +msgid "" +"with ThreadPoolExecutor(max_workers=1) as executor:\n" +" future = executor.submit(pow, 323, 1235)\n" +" print(future.result())" +msgstr "" + #: library/concurrent.futures.rst:44 msgid "Similar to :func:`map(fn, *iterables) ` except:" msgstr "" @@ -151,6 +158,16 @@ msgid "" "meth:`Executor.shutdown` were called with *wait* set to ``True``)::" msgstr "" +#: library/concurrent.futures.rst:100 +msgid "" +"import shutil\n" +"with ThreadPoolExecutor(max_workers=4) as e:\n" +" e.submit(shutil.copy, 'src1.txt', 'dest1.txt')\n" +" e.submit(shutil.copy, 'src2.txt', 'dest2.txt')\n" +" e.submit(shutil.copy, 'src3.txt', 'dest3.txt')\n" +" e.submit(shutil.copy, 'src4.txt', 'dest4.txt')" +msgstr "" + #: library/concurrent.futures.rst:107 msgid "Added *cancel_futures*." msgstr "" @@ -171,10 +188,41 @@ msgid "" "waits on the results of another :class:`Future`. For example::" msgstr "" +#: library/concurrent.futures.rst:120 +msgid "" +"import time\n" +"def wait_on_b():\n" +" time.sleep(5)\n" +" print(b.result()) # b will never complete because it is waiting on a.\n" +" return 5\n" +"\n" +"def wait_on_a():\n" +" time.sleep(5)\n" +" print(a.result()) # a will never complete because it is waiting on b.\n" +" return 6\n" +"\n" +"\n" +"executor = ThreadPoolExecutor(max_workers=2)\n" +"a = executor.submit(wait_on_b)\n" +"b = executor.submit(wait_on_a)" +msgstr "" + #: library/concurrent.futures.rst:136 msgid "And::" msgstr "" +#: library/concurrent.futures.rst:138 +msgid "" +"def wait_on_future():\n" +" f = executor.submit(pow, 5, 2)\n" +" # This will never complete because there is only one worker thread and\n" +" # it is executing this function.\n" +" print(f.result())\n" +"\n" +"executor = ThreadPoolExecutor(max_workers=1)\n" +"executor.submit(wait_on_future)" +msgstr "" + #: library/concurrent.futures.rst:150 msgid "" "An :class:`Executor` subclass that uses a pool of at most *max_workers* " @@ -238,6 +286,37 @@ msgstr "" msgid "ThreadPoolExecutor Example" msgstr "" +#: library/concurrent.futures.rst:198 +msgid "" +"import concurrent.futures\n" +"import urllib.request\n" +"\n" +"URLS = ['http://www.foxnews.com/',\n" +" 'http://www.cnn.com/',\n" +" 'http://europe.wsj.com/',\n" +" 'http://www.bbc.co.uk/',\n" +" 'http://nonexistant-subdomain.python.org/']\n" +"\n" +"# Retrieve a single page and report the URL and contents\n" +"def load_url(url, timeout):\n" +" with urllib.request.urlopen(url, timeout=timeout) as conn:\n" +" return conn.read()\n" +"\n" +"# We can use a with statement to ensure threads are cleaned up promptly\n" +"with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:\n" +" # Start the load operations and mark each future with its URL\n" +" future_to_url = {executor.submit(load_url, url, 60): url for url in " +"URLS}\n" +" for future in concurrent.futures.as_completed(future_to_url):\n" +" url = future_to_url[future]\n" +" try:\n" +" data = future.result()\n" +" except Exception as exc:\n" +" print('%r generated an exception: %s' % (url, exc))\n" +" else:\n" +" print('%r page is %d bytes' % (url, len(data)))" +msgstr "" + #: library/concurrent.futures.rst:227 msgid "ProcessPoolExecutor" msgstr "" @@ -342,6 +421,42 @@ msgstr "" msgid "ProcessPoolExecutor Example" msgstr "" +#: library/concurrent.futures.rst:311 +msgid "" +"import concurrent.futures\n" +"import math\n" +"\n" +"PRIMES = [\n" +" 112272535095293,\n" +" 112582705942171,\n" +" 112272535095293,\n" +" 115280095190773,\n" +" 115797848077099,\n" +" 1099726899285419]\n" +"\n" +"def is_prime(n):\n" +" if n < 2:\n" +" return False\n" +" if n == 2:\n" +" return True\n" +" if n % 2 == 0:\n" +" return False\n" +"\n" +" sqrt_n = int(math.floor(math.sqrt(n)))\n" +" for i in range(3, sqrt_n + 1, 2):\n" +" if n % i == 0:\n" +" return False\n" +" return True\n" +"\n" +"def main():\n" +" with concurrent.futures.ProcessPoolExecutor() as executor:\n" +" for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):\n" +" print('%d is prime: %s' % (number, prime))\n" +"\n" +"if __name__ == '__main__':\n" +" main()" +msgstr "" + #: library/concurrent.futures.rst:346 msgid "Future Objects" msgstr "" diff --git a/library/configparser.po b/library/configparser.po index 02cfbd702..4bd3927b4 100644 --- a/library/configparser.po +++ b/library/configparser.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -68,15 +68,31 @@ msgid "" "sometimes used for configuration, but does not support comments." msgstr "" -#: library/configparser.rst:60 +#: library/configparser.rst:61 msgid "Quick Start" msgstr "" -#: library/configparser.rst:62 +#: library/configparser.rst:63 msgid "Let's take a very basic configuration file that looks like this:" msgstr "" -#: library/configparser.rst:79 +#: library/configparser.rst:65 +msgid "" +"[DEFAULT]\n" +"ServerAliveInterval = 45\n" +"Compression = yes\n" +"CompressionLevel = 9\n" +"ForwardX11 = yes\n" +"\n" +"[forge.example]\n" +"User = hg\n" +"\n" +"[topsecret.server.example]\n" +"Port = 50022\n" +"ForwardX11 = no" +msgstr "" + +#: library/configparser.rst:80 msgid "" "The structure of INI files is described `in the following section " "<#supported-ini-file-structure>`_. Essentially, the file consists of " @@ -85,20 +101,72 @@ msgid "" "configuration file programmatically." msgstr "" -#: library/configparser.rst:103 +#: library/configparser.rst:86 +msgid "" +">>> import configparser\n" +">>> config = configparser.ConfigParser()\n" +">>> config['DEFAULT'] = {'ServerAliveInterval': '45',\n" +"... 'Compression': 'yes',\n" +"... 'CompressionLevel': '9'}\n" +">>> config['forge.example'] = {}\n" +">>> config['forge.example']['User'] = 'hg'\n" +">>> config['topsecret.server.example'] = {}\n" +">>> topsecret = config['topsecret.server.example']\n" +">>> topsecret['Port'] = '50022' # mutates the parser\n" +">>> topsecret['ForwardX11'] = 'no' # same here\n" +">>> config['DEFAULT']['ForwardX11'] = 'yes'\n" +">>> with open('example.ini', 'w') as configfile:\n" +"... config.write(configfile)\n" +"..." +msgstr "" + +#: library/configparser.rst:104 msgid "" "As you can see, we can treat a config parser much like a dictionary. There " "are differences, `outlined later <#mapping-protocol-access>`_, but the " "behavior is very close to what you would expect from a dictionary." msgstr "" -#: library/configparser.rst:107 +#: library/configparser.rst:108 msgid "" "Now that we have created and saved a configuration file, let's read it back " "and explore the data it holds." msgstr "" -#: library/configparser.rst:142 +#: library/configparser.rst:111 +msgid "" +">>> config = configparser.ConfigParser()\n" +">>> config.sections()\n" +"[]\n" +">>> config.read('example.ini')\n" +"['example.ini']\n" +">>> config.sections()\n" +"['forge.example', 'topsecret.server.example']\n" +">>> 'forge.example' in config\n" +"True\n" +">>> 'python.org' in config\n" +"False\n" +">>> config['forge.example']['User']\n" +"'hg'\n" +">>> config['DEFAULT']['Compression']\n" +"'yes'\n" +">>> topsecret = config['topsecret.server.example']\n" +">>> topsecret['ForwardX11']\n" +"'no'\n" +">>> topsecret['Port']\n" +"'50022'\n" +">>> for key in config['forge.example']: \n" +"... print(key)\n" +"user\n" +"compressionlevel\n" +"serveraliveinterval\n" +"compression\n" +"forwardx11\n" +">>> config['forge.example']['ForwardX11']\n" +"'yes'" +msgstr "" + +#: library/configparser.rst:143 msgid "" "As we can see above, the API is pretty straightforward. The only bit of " "magic involves the ``DEFAULT`` section which provides default values for all " @@ -106,7 +174,7 @@ msgid "" "and stored in lowercase [1]_." msgstr "" -#: library/configparser.rst:966 +#: library/configparser.rst:967 msgid "" "It is possible to read several configurations into a single :class:" "`ConfigParser`, where the most recently added configuration has the highest " @@ -116,24 +184,52 @@ msgid "" "``example.ini`` file." msgstr "" -#: library/configparser.rst:173 +#: library/configparser.rst:974 +msgid "" +"[DEFAULT]\n" +"ServerAliveInterval = -1" +msgstr "" + +#: library/configparser.rst:979 +msgid "" +">>> config_override = configparser.ConfigParser()\n" +">>> config_override['DEFAULT'] = {'ServerAliveInterval': '-1'}\n" +">>> with open('override.ini', 'w') as configfile:\n" +"... config_override.write(configfile)\n" +"...\n" +">>> config_override = configparser.ConfigParser()\n" +">>> config_override.read(['example.ini', 'override.ini'])\n" +"['example.ini', 'override.ini']\n" +">>> print(config_override.get('DEFAULT', 'ServerAliveInterval'))\n" +"-1" +msgstr "" + +#: library/configparser.rst:174 msgid "" "This behaviour is equivalent to a :meth:`ConfigParser.read` call with " "several files passed to the *filenames* parameter." msgstr "" -#: library/configparser.rst:178 +#: library/configparser.rst:179 msgid "Supported Datatypes" msgstr "" -#: library/configparser.rst:180 +#: library/configparser.rst:181 msgid "" "Config parsers do not guess datatypes of values in configuration files, " "always storing them internally as strings. This means that if you need " "other datatypes, you should convert on your own:" msgstr "" -#: library/configparser.rst:191 +#: library/configparser.rst:185 +msgid "" +">>> int(topsecret['Port'])\n" +"50022\n" +">>> float(topsecret['CompressionLevel'])\n" +"9.0" +msgstr "" + +#: library/configparser.rst:192 msgid "" "Since this task is so common, config parsers provide a range of handy getter " "methods to handle integers, floats and booleans. The last one is the most " @@ -144,7 +240,17 @@ msgid "" "``'true'``/``'false'`` and ``'1'``/``'0'`` [1]_. For example:" msgstr "" -#: library/configparser.rst:208 +#: library/configparser.rst:200 +msgid "" +">>> topsecret.getboolean('ForwardX11')\n" +"False\n" +">>> config['forge.example'].getboolean('ForwardX11')\n" +"True\n" +">>> config.getboolean('forge.example', 'Compression')\n" +"True" +msgstr "" + +#: library/configparser.rst:209 msgid "" "Apart from :meth:`~ConfigParser.getboolean`, config parsers also provide " "equivalent :meth:`~ConfigParser.getint` and :meth:`~ConfigParser.getfloat` " @@ -152,17 +258,28 @@ msgid "" "ones. [1]_" msgstr "" -#: library/configparser.rst:214 +#: library/configparser.rst:215 msgid "Fallback Values" msgstr "" -#: library/configparser.rst:216 +#: library/configparser.rst:217 msgid "" "As with a dictionary, you can use a section's :meth:`~ConfigParser.get` " "method to provide fallback values:" msgstr "" -#: library/configparser.rst:229 +#: library/configparser.rst:220 +msgid "" +">>> topsecret.get('Port')\n" +"'50022'\n" +">>> topsecret.get('CompressionLevel')\n" +"'9'\n" +">>> topsecret.get('Cipher')\n" +">>> topsecret.get('Cipher', '3des-cbc')\n" +"'3des-cbc'" +msgstr "" + +#: library/configparser.rst:230 msgid "" "Please note that default values have precedence over fallback values. For " "instance, in our example the ``'CompressionLevel'`` key was specified only " @@ -171,7 +288,13 @@ msgid "" "specify a fallback:" msgstr "" -#: library/configparser.rst:240 +#: library/configparser.rst:236 +msgid "" +">>> topsecret.get('CompressionLevel', '3')\n" +"'9'" +msgstr "" + +#: library/configparser.rst:241 msgid "" "One more thing to be aware of is that the parser-level :meth:`~ConfigParser." "get` method provides a custom, more complex interface, maintained for " @@ -179,18 +302,36 @@ msgid "" "provided via the ``fallback`` keyword-only argument:" msgstr "" -#: library/configparser.rst:251 +#: library/configparser.rst:246 +msgid "" +">>> config.get('forge.example', 'monster',\n" +"... fallback='No such things as monsters')\n" +"'No such things as monsters'" +msgstr "" + +#: library/configparser.rst:252 msgid "" "The same ``fallback`` argument can be used with the :meth:`~ConfigParser." "getint`, :meth:`~ConfigParser.getfloat` and :meth:`~ConfigParser.getboolean` " "methods, for example:" msgstr "" -#: library/configparser.rst:267 +#: library/configparser.rst:256 +msgid "" +">>> 'BatchMode' in topsecret\n" +"False\n" +">>> topsecret.getboolean('BatchMode', fallback=True)\n" +"True\n" +">>> config['DEFAULT']['BatchMode'] = 'no'\n" +">>> topsecret.getboolean('BatchMode', fallback=True)\n" +"False" +msgstr "" + +#: library/configparser.rst:268 msgid "Supported INI File Structure" msgstr "" -#: library/configparser.rst:269 +#: library/configparser.rst:270 msgid "" "A configuration file consists of sections, each led by a ``[section]`` " "header, followed by key/value entries separated by a specific string (``=`` " @@ -203,35 +344,80 @@ msgid "" "parts of multiline values or ignored." msgstr "" -#: library/configparser.rst:279 +#: library/configparser.rst:280 msgid "" "By default, a valid section name can be any string that does not contain '\\" "\\n'. To change this, see :attr:`ConfigParser.SECTCRE`." msgstr "" -#: library/configparser.rst:282 +#: library/configparser.rst:283 msgid "" "Configuration files may include comments, prefixed by specific characters " "(``#`` and ``;`` by default [1]_). Comments may appear on their own on an " "otherwise empty line, possibly indented. [1]_" msgstr "" -#: library/configparser.rst:349 +#: library/configparser.rst:350 msgid "For example:" msgstr "" -#: library/configparser.rst:334 +#: library/configparser.rst:289 +msgid "" +"[Simple Values]\n" +"key=value\n" +"spaces in keys=allowed\n" +"spaces in values=allowed as well\n" +"spaces around the delimiter = obviously\n" +"you can also use : to delimit keys from values\n" +"\n" +"[All Values Are Strings]\n" +"values like this: 1000000\n" +"or this: 3.14159265359\n" +"are they treated as numbers? : no\n" +"integers, floats and booleans are held as: strings\n" +"can use the API to get converted values directly: true\n" +"\n" +"[Multiline Values]\n" +"chorus: I'm a lumberjack, and I'm okay\n" +" I sleep all night and I work all day\n" +"\n" +"[No Values]\n" +"key_without_value\n" +"empty string value here =\n" +"\n" +"[You can use comments]\n" +"# like this\n" +"; or this\n" +"\n" +"# By default only in an empty line.\n" +"# Inline comments can be harmful because they prevent users\n" +"# from using the delimiting characters as parts of values.\n" +"# That being said, this can be customized.\n" +"\n" +" [Sections Can Be Indented]\n" +" can_values_be_as_well = True\n" +" does_that_mean_anything_special = False\n" +" purpose = formatting for readability\n" +" multiline_values = are\n" +" handled just fine as\n" +" long as they are indented\n" +" deeper than the first line\n" +" of a value\n" +" # Did I mention we can indent comments, too?" +msgstr "" + +#: library/configparser.rst:335 msgid "Interpolation of values" msgstr "" -#: library/configparser.rst:336 +#: library/configparser.rst:337 msgid "" "On top of the core functionality, :class:`ConfigParser` supports " "interpolation. This means values can be preprocessed before returning them " "from ``get()`` calls." msgstr "" -#: library/configparser.rst:344 +#: library/configparser.rst:345 msgid "" "The default implementation used by :class:`ConfigParser`. It enables values " "to contain format strings which refer to other values in the same section, " @@ -239,7 +425,20 @@ msgid "" "can be provided on initialization." msgstr "" -#: library/configparser.rst:362 +#: library/configparser.rst:352 +msgid "" +"[Paths]\n" +"home_dir: /Users\n" +"my_dir: %(home_dir)s/lumberjack\n" +"my_pictures: %(my_dir)s/Pictures\n" +"\n" +"[Escape]\n" +"# use a %% to escape the % sign (% is the only character that needs to be " +"escaped):\n" +"gain: 80%%" +msgstr "" + +#: library/configparser.rst:363 msgid "" "In the example above, :class:`ConfigParser` with *interpolation* set to " "``BasicInterpolation()`` would resolve ``%(home_dir)s`` to the value of " @@ -249,14 +448,14 @@ msgid "" "specific order in the configuration file." msgstr "" -#: library/configparser.rst:369 +#: library/configparser.rst:370 msgid "" "With ``interpolation`` set to ``None``, the parser would simply return " "``%(my_dir)s/Pictures`` as the value of ``my_pictures`` and ``%(home_dir)s/" "lumberjack`` as the value of ``my_dir``." msgstr "" -#: library/configparser.rst:377 +#: library/configparser.rst:378 msgid "" "An alternative handler for interpolation which implements a more advanced " "syntax, used for instance in ``zc.buildout``. Extended interpolation is " @@ -266,21 +465,54 @@ msgid "" "possibly the default values from the special section)." msgstr "" -#: library/configparser.rst:384 +#: library/configparser.rst:385 msgid "" "For example, the configuration specified above with basic interpolation, " "would look like this with extended interpolation:" msgstr "" -#: library/configparser.rst:398 +#: library/configparser.rst:388 +msgid "" +"[Paths]\n" +"home_dir: /Users\n" +"my_dir: ${home_dir}/lumberjack\n" +"my_pictures: ${my_dir}/Pictures\n" +"\n" +"[Escape]\n" +"# use a $$ to escape the $ sign ($ is the only character that needs to be " +"escaped):\n" +"cost: $$80" +msgstr "" + +#: library/configparser.rst:399 msgid "Values from other sections can be fetched as well:" msgstr "" -#: library/configparser.rst:420 +#: library/configparser.rst:401 +msgid "" +"[Common]\n" +"home_dir: /Users\n" +"library_dir: /Library\n" +"system_dir: /System\n" +"macports_dir: /opt/local\n" +"\n" +"[Frameworks]\n" +"Python: 3.2\n" +"path: ${Common:system_dir}/Library/Frameworks/\n" +"\n" +"[Arthur]\n" +"nickname: Two Sheds\n" +"last_name: Jackson\n" +"my_dir: ${Common:home_dir}/twosheds\n" +"my_pictures: ${my_dir}/Pictures\n" +"python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}" +msgstr "" + +#: library/configparser.rst:421 msgid "Mapping Protocol Access" msgstr "" -#: library/configparser.rst:424 +#: library/configparser.rst:425 msgid "" "Mapping protocol access is a generic name for functionality that enables " "using custom objects as if they were dictionaries. In case of :mod:" @@ -288,7 +520,7 @@ msgid "" "``parser['section']['option']`` notation." msgstr "" -#: library/configparser.rst:429 +#: library/configparser.rst:430 msgid "" "``parser['section']`` in particular returns a proxy for the section's data " "in the parser. This means that the values are not copied but they are taken " @@ -297,7 +529,7 @@ msgid "" "original parser." msgstr "" -#: library/configparser.rst:435 +#: library/configparser.rst:436 msgid "" ":mod:`configparser` objects behave as close to actual dictionaries as " "possible. The mapping interface is complete and adheres to the :class:" @@ -305,7 +537,7 @@ msgid "" "that should be taken into account:" msgstr "" -#: library/configparser.rst:440 +#: library/configparser.rst:441 msgid "" "By default, all keys in sections are accessible in a case-insensitive manner " "[1]_. E.g. ``for option in parser[\"section\"]`` yields only " @@ -314,7 +546,13 @@ msgid "" "expressions return ``True``::" msgstr "" -#: library/configparser.rst:448 +#: library/configparser.rst:446 +msgid "" +"\"a\" in parser[\"section\"]\n" +"\"A\" in parser[\"section\"]" +msgstr "" + +#: library/configparser.rst:449 msgid "" "All sections include ``DEFAULTSECT`` values as well which means that ``." "clear()`` on a section may not leave the section visibly empty. This is " @@ -324,30 +562,30 @@ msgid "" "default value causes a :exc:`KeyError`." msgstr "" -#: library/configparser.rst:455 +#: library/configparser.rst:456 msgid "``DEFAULTSECT`` cannot be removed from the parser:" msgstr "" -#: library/configparser.rst:457 +#: library/configparser.rst:458 msgid "trying to delete it raises :exc:`ValueError`," msgstr "" -#: library/configparser.rst:459 +#: library/configparser.rst:460 msgid "``parser.clear()`` leaves it intact," msgstr "" -#: library/configparser.rst:461 +#: library/configparser.rst:462 msgid "``parser.popitem()`` never returns it." msgstr "" -#: library/configparser.rst:463 +#: library/configparser.rst:464 msgid "" "``parser.get(section, option, **kwargs)`` - the second argument is **not** a " "fallback value. Note however that the section-level ``get()`` methods are " "compatible both with the mapping protocol and the classic configparser API." msgstr "" -#: library/configparser.rst:467 +#: library/configparser.rst:468 msgid "" "``parser.items()`` is compatible with the mapping protocol (returns a list " "of *section_name*, *section_proxy* pairs including the DEFAULTSECT). " @@ -357,18 +595,18 @@ msgid "" "(unless ``raw=True`` is provided)." msgstr "" -#: library/configparser.rst:474 +#: library/configparser.rst:475 msgid "" "The mapping protocol is implemented on top of the existing legacy API so " "that subclasses overriding the original interface still should have mappings " "working as expected." msgstr "" -#: library/configparser.rst:480 +#: library/configparser.rst:481 msgid "Customizing Parser Behaviour" msgstr "" -#: library/configparser.rst:482 +#: library/configparser.rst:483 msgid "" "There are nearly as many INI format variants as there are applications using " "it. :mod:`configparser` goes a long way to provide support for the largest " @@ -377,17 +615,17 @@ msgid "" "customize some of the features." msgstr "" -#: library/configparser.rst:488 +#: library/configparser.rst:489 msgid "" "The most common way to change the way a specific config parser works is to " "use the :meth:`!__init__` options:" msgstr "" -#: library/configparser.rst:491 +#: library/configparser.rst:492 msgid "*defaults*, default value: ``None``" msgstr "" -#: library/configparser.rst:493 +#: library/configparser.rst:494 msgid "" "This option accepts a dictionary of key-value pairs which will be initially " "put in the ``DEFAULT`` section. This makes for an elegant way to support " @@ -395,17 +633,17 @@ msgid "" "the documented default." msgstr "" -#: library/configparser.rst:498 +#: library/configparser.rst:499 msgid "" "Hint: if you want to specify default values for a specific section, use :" "meth:`~ConfigParser.read_dict` before you read the actual file." msgstr "" -#: library/configparser.rst:501 +#: library/configparser.rst:502 msgid "*dict_type*, default value: :class:`dict`" msgstr "" -#: library/configparser.rst:503 +#: library/configparser.rst:504 msgid "" "This option has a major impact on how the mapping protocol will behave and " "how the written configuration files look. With the standard dictionary, " @@ -413,24 +651,43 @@ msgid "" "goes for options within sections." msgstr "" -#: library/configparser.rst:508 +#: library/configparser.rst:509 msgid "" "An alternative dictionary type can be used for example to sort sections and " "options on write-back." msgstr "" -#: library/configparser.rst:511 +#: library/configparser.rst:512 msgid "" "Please note: there are ways to add a set of key-value pairs in a single " "operation. When you use a regular dictionary in those operations, the order " "of the keys will be ordered. For example:" msgstr "" -#: library/configparser.rst:533 +#: library/configparser.rst:516 +msgid "" +">>> parser = configparser.ConfigParser()\n" +">>> parser.read_dict({'section1': {'key1': 'value1',\n" +"... 'key2': 'value2',\n" +"... 'key3': 'value3'},\n" +"... 'section2': {'keyA': 'valueA',\n" +"... 'keyB': 'valueB',\n" +"... 'keyC': 'valueC'},\n" +"... 'section3': {'foo': 'x',\n" +"... 'bar': 'y',\n" +"... 'baz': 'z'}\n" +"... })\n" +">>> parser.sections()\n" +"['section1', 'section2', 'section3']\n" +">>> [option for option in parser['section3']]\n" +"['foo', 'bar', 'baz']" +msgstr "" + +#: library/configparser.rst:534 msgid "*allow_no_value*, default value: ``False``" msgstr "" -#: library/configparser.rst:535 +#: library/configparser.rst:536 msgid "" "Some configuration files are known to include settings without values, but " "which otherwise conform to the syntax supported by :mod:`configparser`. The " @@ -438,32 +695,63 @@ msgid "" "such values should be accepted:" msgstr "" -#: library/configparser.rst:570 +#: library/configparser.rst:541 +msgid "" +">>> import configparser\n" +"\n" +">>> sample_config = \"\"\"\n" +"... [mysqld]\n" +"... user = mysql\n" +"... pid-file = /var/run/mysqld/mysqld.pid\n" +"... skip-external-locking\n" +"... old_passwords = 1\n" +"... skip-bdb\n" +"... # we don't need ACID today\n" +"... skip-innodb\n" +"... \"\"\"\n" +">>> config = configparser.ConfigParser(allow_no_value=True)\n" +">>> config.read_string(sample_config)\n" +"\n" +">>> # Settings with values are treated as before:\n" +">>> config[\"mysqld\"][\"user\"]\n" +"'mysql'\n" +"\n" +">>> # Settings without values provide None:\n" +">>> config[\"mysqld\"][\"skip-bdb\"]\n" +"\n" +">>> # Settings which aren't specified still raise an error:\n" +">>> config[\"mysqld\"][\"does-not-exist\"]\n" +"Traceback (most recent call last):\n" +" ...\n" +"KeyError: 'does-not-exist'" +msgstr "" + +#: library/configparser.rst:571 msgid "*delimiters*, default value: ``('=', ':')``" msgstr "" -#: library/configparser.rst:572 +#: library/configparser.rst:573 msgid "" "Delimiters are substrings that delimit keys from values within a section. " "The first occurrence of a delimiting substring on a line is considered a " "delimiter. This means values (but not keys) can contain the delimiters." msgstr "" -#: library/configparser.rst:576 +#: library/configparser.rst:577 msgid "" "See also the *space_around_delimiters* argument to :meth:`ConfigParser." "write`." msgstr "" -#: library/configparser.rst:579 +#: library/configparser.rst:580 msgid "*comment_prefixes*, default value: ``('#', ';')``" msgstr "" -#: library/configparser.rst:581 +#: library/configparser.rst:582 msgid "*inline_comment_prefixes*, default value: ``None``" msgstr "" -#: library/configparser.rst:583 +#: library/configparser.rst:584 msgid "" "Comment prefixes are strings that indicate the start of a valid comment " "within a config file. *comment_prefixes* are used only on otherwise empty " @@ -473,13 +761,13 @@ msgid "" "used as prefixes for whole line comments." msgstr "" -#: library/configparser.rst:590 +#: library/configparser.rst:591 msgid "" "In previous versions of :mod:`configparser` behaviour matched " "``comment_prefixes=('#',';')`` and ``inline_comment_prefixes=(';',)``." msgstr "" -#: library/configparser.rst:594 +#: library/configparser.rst:595 msgid "" "Please note that config parsers don't support escaping of comment prefixes " "so using *inline_comment_prefixes* may prevent users from specifying option " @@ -489,11 +777,53 @@ msgid "" "values is to interpolate the prefix, for example::" msgstr "" -#: library/configparser.rst:640 +#: library/configparser.rst:602 +msgid "" +">>> from configparser import ConfigParser, ExtendedInterpolation\n" +">>> parser = ConfigParser(interpolation=ExtendedInterpolation())\n" +">>> # the default BasicInterpolation could be used as well\n" +">>> parser.read_string(\"\"\"\n" +"... [DEFAULT]\n" +"... hash = #\n" +"...\n" +"... [hashes]\n" +"... shebang =\n" +"... ${hash}!/usr/bin/env python\n" +"... ${hash} -*- coding: utf-8 -*-\n" +"...\n" +"... extensions =\n" +"... enabled_extension\n" +"... another_extension\n" +"... #disabled_by_comment\n" +"... yet_another_extension\n" +"...\n" +"... interpolation not necessary = if # is not at line start\n" +"... even in multiline values = line #1\n" +"... line #2\n" +"... line #3\n" +"... \"\"\")\n" +">>> print(parser['hashes']['shebang'])\n" +"\n" +"#!/usr/bin/env python\n" +"# -*- coding: utf-8 -*-\n" +">>> print(parser['hashes']['extensions'])\n" +"\n" +"enabled_extension\n" +"another_extension\n" +"yet_another_extension\n" +">>> print(parser['hashes']['interpolation not necessary'])\n" +"if # is not at line start\n" +">>> print(parser['hashes']['even in multiline values'])\n" +"line #1\n" +"line #2\n" +"line #3" +msgstr "" + +#: library/configparser.rst:641 msgid "*strict*, default value: ``True``" msgstr "" -#: library/configparser.rst:642 +#: library/configparser.rst:643 msgid "" "When set to ``True``, the parser will not allow for any section or option " "duplicates while reading from a single source (using :meth:`~ConfigParser." @@ -501,17 +831,17 @@ msgid "" "read_dict`). It is recommended to use strict parsers in new applications." msgstr "" -#: library/configparser.rst:647 +#: library/configparser.rst:648 msgid "" "In previous versions of :mod:`configparser` behaviour matched " "``strict=False``." msgstr "" -#: library/configparser.rst:651 +#: library/configparser.rst:652 msgid "*empty_lines_in_values*, default value: ``True``" msgstr "" -#: library/configparser.rst:653 +#: library/configparser.rst:654 msgid "" "In config parsers, values can span multiple lines as long as they are " "indented more than the key that holds them. By default parsers also let " @@ -521,7 +851,16 @@ msgid "" "lose track of the file structure. Take for instance:" msgstr "" -#: library/configparser.rst:668 +#: library/configparser.rst:661 +msgid "" +"[Section]\n" +"key = multiline\n" +" value with a gotcha\n" +"\n" +" this = is still a part of the multiline value of 'key'" +msgstr "" + +#: library/configparser.rst:669 msgid "" "This can be especially problematic for the user to see if she's using a " "proportional font to edit the file. That is why when your application does " @@ -530,13 +869,13 @@ msgid "" "would produce two keys, ``key`` and ``this``." msgstr "" -#: library/configparser.rst:674 +#: library/configparser.rst:675 msgid "" "*default_section*, default value: ``configparser.DEFAULTSECT`` (that is: " "``\"DEFAULT\"``)" msgstr "" -#: library/configparser.rst:677 +#: library/configparser.rst:678 msgid "" "The convention of allowing a special section of default values for other " "sections or interpolation purposes is a powerful concept of this library, " @@ -550,11 +889,11 @@ msgid "" "files from one format to another)." msgstr "" -#: library/configparser.rst:688 +#: library/configparser.rst:689 msgid "*interpolation*, default value: ``configparser.BasicInterpolation``" msgstr "" -#: library/configparser.rst:690 +#: library/configparser.rst:691 msgid "" "Interpolation behaviour may be customized by providing a custom handler " "through the *interpolation* argument. ``None`` can be used to turn off " @@ -564,11 +903,11 @@ msgid "" "`RawConfigParser` has a default value of ``None``." msgstr "" -#: library/configparser.rst:697 +#: library/configparser.rst:698 msgid "*converters*, default value: not set" msgstr "" -#: library/configparser.rst:699 +#: library/configparser.rst:700 msgid "" "Config parsers provide option value getters that perform type conversion. " "By default :meth:`~ConfigParser.getint`, :meth:`~ConfigParser.getfloat`, " @@ -582,7 +921,7 @@ msgid "" "``parser_instance['section'].getdecimal('key', 0)``." msgstr "" -#: library/configparser.rst:710 +#: library/configparser.rst:711 msgid "" "If the converter needs to access the state of the parser, it can be " "implemented as a method on a config parser subclass. If the name of this " @@ -590,14 +929,14 @@ msgid "" "the dict-compatible form (see the ``getdecimal()`` example above)." msgstr "" -#: library/configparser.rst:715 +#: library/configparser.rst:716 msgid "" "More advanced customization may be achieved by overriding default values of " "these parser attributes. The defaults are defined on the classes, so they " "may be overridden by subclasses or by attribute assignment." msgstr "" -#: library/configparser.rst:721 +#: library/configparser.rst:722 msgid "" "By default when using :meth:`~ConfigParser.getboolean`, config parsers " "consider the following values ``True``: ``'1'``, ``'yes'``, ``'true'``, " @@ -606,13 +945,26 @@ msgid "" "strings and their Boolean outcomes. For example:" msgstr "" -#: library/configparser.rst:739 +#: library/configparser.rst:728 +msgid "" +">>> custom = configparser.ConfigParser()\n" +">>> custom['section1'] = {'funky': 'nope'}\n" +">>> custom['section1'].getboolean('funky')\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: Not a boolean: nope\n" +">>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}\n" +">>> custom['section1'].getboolean('funky')\n" +"False" +msgstr "" + +#: library/configparser.rst:740 msgid "" "Other typical Boolean pairs include ``accept``/``reject`` or ``enabled``/" "``disabled``." msgstr "" -#: library/configparser.rst:745 +#: library/configparser.rst:746 msgid "" "This method transforms option names on every read, get, or set operation. " "The default converts the name to lowercase. This also means that when a " @@ -620,14 +972,38 @@ msgid "" "method if that's unsuitable. For example:" msgstr "" -#: library/configparser.rst:775 +#: library/configparser.rst:752 +msgid "" +">>> config = \"\"\"\n" +"... [Section1]\n" +"... Key = Value\n" +"...\n" +"... [Section2]\n" +"... AnotherKey = Value\n" +"... \"\"\"\n" +">>> typical = configparser.ConfigParser()\n" +">>> typical.read_string(config)\n" +">>> list(typical['Section1'].keys())\n" +"['key']\n" +">>> list(typical['Section2'].keys())\n" +"['anotherkey']\n" +">>> custom = configparser.RawConfigParser()\n" +">>> custom.optionxform = lambda option: option\n" +">>> custom.read_string(config)\n" +">>> list(custom['Section1'].keys())\n" +"['Key']\n" +">>> list(custom['Section2'].keys())\n" +"['AnotherKey']" +msgstr "" + +#: library/configparser.rst:776 msgid "" "The optionxform function transforms option names to a canonical form. This " "should be an idempotent function: if the name is already in canonical form, " "it should be returned unchanged." msgstr "" -#: library/configparser.rst:782 +#: library/configparser.rst:783 msgid "" "A compiled regular expression used to parse section headers. The default " "matches ``[section]`` to the name ``\"section\"``. Whitespace is considered " @@ -636,18 +1012,39 @@ msgid "" "example:" msgstr "" -#: library/configparser.rst:810 +#: library/configparser.rst:789 +msgid "" +">>> import re\n" +">>> config = \"\"\"\n" +"... [Section 1]\n" +"... option = value\n" +"...\n" +"... [ Section 2 ]\n" +"... another = val\n" +"... \"\"\"\n" +">>> typical = configparser.ConfigParser()\n" +">>> typical.read_string(config)\n" +">>> typical.sections()\n" +"['Section 1', ' Section 2 ']\n" +">>> custom = configparser.ConfigParser()\n" +">>> custom.SECTCRE = re.compile(r\"\\[ *(?P

[^]]+?) *\\]\")\n" +">>> custom.read_string(config)\n" +">>> custom.sections()\n" +"['Section 1', 'Section 2']" +msgstr "" + +#: library/configparser.rst:811 msgid "" "While ConfigParser objects also use an ``OPTCRE`` attribute for recognizing " "option lines, it's not recommended to override it because that would " "interfere with constructor options *allow_no_value* and *delimiters*." msgstr "" -#: library/configparser.rst:816 +#: library/configparser.rst:817 msgid "Legacy API Examples" msgstr "" -#: library/configparser.rst:818 +#: library/configparser.rst:819 msgid "" "Mainly because of backwards compatibility concerns, :mod:`configparser` " "provides also a legacy API with explicit ``get``/``set`` methods. While " @@ -656,29 +1053,121 @@ msgid "" "advanced, low-level and downright counterintuitive." msgstr "" -#: library/configparser.rst:824 +#: library/configparser.rst:825 msgid "An example of writing to a configuration file::" msgstr "" -#: library/configparser.rst:847 +#: library/configparser.rst:827 +msgid "" +"import configparser\n" +"\n" +"config = configparser.RawConfigParser()\n" +"\n" +"# Please note that using RawConfigParser's set functions, you can assign\n" +"# non-string values to keys internally, but will receive an error when\n" +"# attempting to write to a file or when you get it in non-raw mode. Setting\n" +"# values using the mapping protocol or ConfigParser's set() does not allow\n" +"# such assignments to take place.\n" +"config.add_section('Section1')\n" +"config.set('Section1', 'an_int', '15')\n" +"config.set('Section1', 'a_bool', 'true')\n" +"config.set('Section1', 'a_float', '3.1415')\n" +"config.set('Section1', 'baz', 'fun')\n" +"config.set('Section1', 'bar', 'Python')\n" +"config.set('Section1', 'foo', '%(bar)s is %(baz)s!')\n" +"\n" +"# Writing our configuration file to 'example.cfg'\n" +"with open('example.cfg', 'w') as configfile:\n" +" config.write(configfile)" +msgstr "" + +#: library/configparser.rst:848 msgid "An example of reading the configuration file again::" msgstr "" -#: library/configparser.rst:865 +#: library/configparser.rst:850 +msgid "" +"import configparser\n" +"\n" +"config = configparser.RawConfigParser()\n" +"config.read('example.cfg')\n" +"\n" +"# getfloat() raises an exception if the value is not a float\n" +"# getint() and getboolean() also do this for their respective types\n" +"a_float = config.getfloat('Section1', 'a_float')\n" +"an_int = config.getint('Section1', 'an_int')\n" +"print(a_float + an_int)\n" +"\n" +"# Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.\n" +"# This is because we are using a RawConfigParser().\n" +"if config.getboolean('Section1', 'a_bool'):\n" +" print(config.get('Section1', 'foo'))" +msgstr "" + +#: library/configparser.rst:866 msgid "To get interpolation, use :class:`ConfigParser`::" msgstr "" -#: library/configparser.rst:898 +#: library/configparser.rst:868 +msgid "" +"import configparser\n" +"\n" +"cfg = configparser.ConfigParser()\n" +"cfg.read('example.cfg')\n" +"\n" +"# Set the optional *raw* argument of get() to True if you wish to disable\n" +"# interpolation in a single get operation.\n" +"print(cfg.get('Section1', 'foo', raw=False)) # -> \"Python is fun!\"\n" +"print(cfg.get('Section1', 'foo', raw=True)) # -> \"%(bar)s is %(baz)s!\"\n" +"\n" +"# The optional *vars* argument is a dict with members that will take\n" +"# precedence in interpolation.\n" +"print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',\n" +" 'baz': 'evil'}))\n" +"\n" +"# The optional *fallback* argument can be used to provide a fallback value\n" +"print(cfg.get('Section1', 'foo'))\n" +" # -> \"Python is fun!\"\n" +"\n" +"print(cfg.get('Section1', 'foo', fallback='Monty is not.'))\n" +" # -> \"Python is fun!\"\n" +"\n" +"print(cfg.get('Section1', 'monster', fallback='No such things as " +"monsters.'))\n" +" # -> \"No such things as monsters.\"\n" +"\n" +"# A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError\n" +"# but we can also use:\n" +"\n" +"print(cfg.get('Section1', 'monster', fallback=None))\n" +" # -> None" +msgstr "" + +#: library/configparser.rst:899 msgid "" "Default values are available in both types of ConfigParsers. They are used " "in interpolation if an option used is not defined elsewhere. ::" msgstr "" -#: library/configparser.rst:916 +#: library/configparser.rst:902 +msgid "" +"import configparser\n" +"\n" +"# New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each\n" +"config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})\n" +"config.read('example.cfg')\n" +"\n" +"print(config.get('Section1', 'foo')) # -> \"Python is fun!\"\n" +"config.remove_option('Section1', 'bar')\n" +"config.remove_option('Section1', 'baz')\n" +"print(config.get('Section1', 'foo')) # -> \"Life is hard!\"" +msgstr "" + +#: library/configparser.rst:917 msgid "ConfigParser Objects" msgstr "" -#: library/configparser.rst:920 +#: library/configparser.rst:921 msgid "" "The main configuration parser. When *defaults* is given, it is initialized " "into the dictionary of intrinsic defaults. When *dict_type* is given, it " @@ -686,7 +1175,7 @@ msgid "" "the options within a section, and for the default values." msgstr "" -#: library/configparser.rst:925 +#: library/configparser.rst:926 msgid "" "When *delimiters* is given, it is used as the set of substrings that divide " "keys from values. When *comment_prefixes* is given, it will be used as the " @@ -695,7 +1184,7 @@ msgid "" "as the set of substrings that prefix comments in non-empty lines." msgstr "" -#: library/configparser.rst:931 +#: library/configparser.rst:932 msgid "" "When *strict* is ``True`` (the default), the parser won't allow for any " "section or option duplicates while reading from a single source (file, " @@ -708,7 +1197,7 @@ msgid "" "without the trailing delimiter." msgstr "" -#: library/configparser.rst:941 +#: library/configparser.rst:942 msgid "" "When *default_section* is given, it specifies the name for the special " "section holding default values for other sections and interpolation purposes " @@ -718,7 +1207,7 @@ msgid "" "settings to a new config file." msgstr "" -#: library/configparser.rst:948 +#: library/configparser.rst:949 msgid "" "Interpolation behaviour may be customized by providing a custom handler " "through the *interpolation* argument. ``None`` can be used to turn off " @@ -727,7 +1216,7 @@ msgid "" "`dedicated documentation section <#interpolation-of-values>`_." msgstr "" -#: library/configparser.rst:954 +#: library/configparser.rst:955 msgid "" "All option names used in interpolation will be passed through the :meth:" "`optionxform` method just like any other option name reference. For " @@ -736,53 +1225,53 @@ msgid "" "%(BAR)s`` are equivalent." msgstr "" -#: library/configparser.rst:960 +#: library/configparser.rst:961 msgid "" "When *converters* is given, it should be a dictionary where each key " "represents the name of a type converter and each value is a callable " "implementing the conversion from string to the desired datatype. Every " -"converter gets its own corresponding :meth:`!get*()` method on the parser " +"converter gets its own corresponding :meth:`!get*` method on the parser " "object and section proxies." msgstr "" -#: library/configparser.rst:991 +#: library/configparser.rst:992 msgid "The default *dict_type* is :class:`collections.OrderedDict`." msgstr "" -#: library/configparser.rst:994 +#: library/configparser.rst:995 msgid "" "*allow_no_value*, *delimiters*, *comment_prefixes*, *strict*, " "*empty_lines_in_values*, *default_section* and *interpolation* were added." msgstr "" -#: library/configparser.rst:999 +#: library/configparser.rst:1000 msgid "The *converters* argument was added." msgstr "" -#: library/configparser.rst:1002 +#: library/configparser.rst:1003 msgid "" -"The *defaults* argument is read with :meth:`read_dict()`, providing " -"consistent behavior across the parser: non-string keys and values are " -"implicitly converted to strings." +"The *defaults* argument is read with :meth:`read_dict`, providing consistent " +"behavior across the parser: non-string keys and values are implicitly " +"converted to strings." msgstr "" -#: library/configparser.rst:1270 +#: library/configparser.rst:1271 msgid "" "The default *dict_type* is :class:`dict`, since it now preserves insertion " "order." msgstr "" -#: library/configparser.rst:1013 +#: library/configparser.rst:1014 msgid "Return a dictionary containing the instance-wide defaults." msgstr "" -#: library/configparser.rst:1018 +#: library/configparser.rst:1019 msgid "" "Return a list of the sections available; the *default section* is not " "included in the list." msgstr "" -#: library/configparser.rst:1024 +#: library/configparser.rst:1025 msgid "" "Add a section named *section* to the instance. If a section by the given " "name already exists, :exc:`DuplicateSectionError` is raised. If the " @@ -790,34 +1279,34 @@ msgid "" "the section must be a string; if not, :exc:`TypeError` is raised." msgstr "" -#: library/configparser.rst:1029 +#: library/configparser.rst:1030 msgid "Non-string section names raise :exc:`TypeError`." msgstr "" -#: library/configparser.rst:1035 +#: library/configparser.rst:1036 msgid "" "Indicates whether the named *section* is present in the configuration. The " "*default section* is not acknowledged." msgstr "" -#: library/configparser.rst:1041 +#: library/configparser.rst:1042 msgid "Return a list of options available in the specified *section*." msgstr "" -#: library/configparser.rst:1046 +#: library/configparser.rst:1047 msgid "" "If the given *section* exists, and contains the given *option*, return :" "const:`True`; otherwise return :const:`False`. If the specified *section* " "is :const:`None` or an empty string, DEFAULT is assumed." msgstr "" -#: library/configparser.rst:1053 +#: library/configparser.rst:1054 msgid "" "Attempt to read and parse an iterable of filenames, returning a list of " "filenames which were successfully parsed." msgstr "" -#: library/configparser.rst:1056 +#: library/configparser.rst:1057 msgid "" "If *filenames* is a string, a :class:`bytes` object or a :term:`path-like " "object`, it is treated as a single filename. If a file named in *filenames* " @@ -828,7 +1317,7 @@ msgid "" "be read." msgstr "" -#: library/configparser.rst:1065 +#: library/configparser.rst:1066 msgid "" "If none of the named files exist, the :class:`ConfigParser` instance will " "contain an empty dataset. An application which requires initial values to " @@ -836,49 +1325,59 @@ msgid "" "`read_file` before calling :meth:`read` for any optional files::" msgstr "" -#: library/configparser.rst:1078 +#: library/configparser.rst:1072 +msgid "" +"import configparser, os\n" +"\n" +"config = configparser.ConfigParser()\n" +"config.read_file(open('defaults.cfg'))\n" +"config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],\n" +" encoding='cp1250')" +msgstr "" + +#: library/configparser.rst:1079 msgid "" "Added the *encoding* parameter. Previously, all files were read using the " "default encoding for :func:`open`." msgstr "" -#: library/configparser.rst:1082 +#: library/configparser.rst:1083 msgid "The *filenames* parameter accepts a :term:`path-like object`." msgstr "" -#: library/configparser.rst:1085 +#: library/configparser.rst:1086 msgid "The *filenames* parameter accepts a :class:`bytes` object." msgstr "" -#: library/configparser.rst:1091 +#: library/configparser.rst:1092 msgid "" "Read and parse configuration data from *f* which must be an iterable " "yielding Unicode strings (for example files opened in text mode)." msgstr "" -#: library/configparser.rst:1094 +#: library/configparser.rst:1095 msgid "" "Optional argument *source* specifies the name of the file being read. If " "not given and *f* has a :attr:`!name` attribute, that is used for *source*; " "the default is ``''``." msgstr "" -#: library/configparser.rst:1098 +#: library/configparser.rst:1099 msgid "Replaces :meth:`!readfp`." msgstr "" -#: library/configparser.rst:1103 +#: library/configparser.rst:1104 msgid "Parse configuration data from a string." msgstr "" -#: library/configparser.rst:1105 +#: library/configparser.rst:1106 msgid "" "Optional argument *source* specifies a context-specific name of the string " "passed. If not given, ``''`` is used. This should commonly be a " "filesystem path or a URL." msgstr "" -#: library/configparser.rst:1114 +#: library/configparser.rst:1115 msgid "" "Load configuration from any object that provides a dict-like ``items()`` " "method. Keys are section names, values are dictionaries with keys and " @@ -887,17 +1386,17 @@ msgid "" "automatically converted to strings." msgstr "" -#: library/configparser.rst:1120 +#: library/configparser.rst:1121 msgid "" "Optional argument *source* specifies a context-specific name of the " "dictionary passed. If not given, ```` is used." msgstr "" -#: library/configparser.rst:1123 +#: library/configparser.rst:1124 msgid "This method can be used to copy state between parsers." msgstr "" -#: library/configparser.rst:1130 +#: library/configparser.rst:1131 msgid "" "Get an *option* value for the named *section*. If *vars* is provided, it " "must be a dictionary. The *option* is looked up in *vars* (if provided), " @@ -906,35 +1405,35 @@ msgid "" "provided as a *fallback* value." msgstr "" -#: library/configparser.rst:1136 +#: library/configparser.rst:1137 msgid "" "All the ``'%'`` interpolations are expanded in the return values, unless the " "*raw* argument is true. Values for interpolation keys are looked up in the " "same manner as the option." msgstr "" -#: library/configparser.rst:1140 +#: library/configparser.rst:1141 msgid "" "Arguments *raw*, *vars* and *fallback* are keyword only to protect users " "from trying to use the third argument as the *fallback* fallback (especially " "when using the mapping protocol)." msgstr "" -#: library/configparser.rst:1148 +#: library/configparser.rst:1149 msgid "" "A convenience method which coerces the *option* in the specified *section* " "to an integer. See :meth:`get` for explanation of *raw*, *vars* and " "*fallback*." msgstr "" -#: library/configparser.rst:1155 +#: library/configparser.rst:1156 msgid "" "A convenience method which coerces the *option* in the specified *section* " "to a floating-point number. See :meth:`get` for explanation of *raw*, " "*vars* and *fallback*." msgstr "" -#: library/configparser.rst:1162 +#: library/configparser.rst:1163 msgid "" "A convenience method which coerces the *option* in the specified *section* " "to a Boolean value. Note that the accepted values for the option are " @@ -946,34 +1445,34 @@ msgid "" "*fallback*." msgstr "" -#: library/configparser.rst:1175 +#: library/configparser.rst:1176 msgid "" "When *section* is not given, return a list of *section_name*, " "*section_proxy* pairs, including DEFAULTSECT." msgstr "" -#: library/configparser.rst:1178 +#: library/configparser.rst:1179 msgid "" "Otherwise, return a list of *name*, *value* pairs for the options in the " "given *section*. Optional arguments have the same meaning as for the :meth:" "`get` method." msgstr "" -#: library/configparser.rst:1182 +#: library/configparser.rst:1183 msgid "" "Items present in *vars* no longer appear in the result. The previous " "behaviour mixed actual parser options with variables provided for " "interpolation." msgstr "" -#: library/configparser.rst:1190 +#: library/configparser.rst:1191 msgid "" "If the given section exists, set the given option to the specified value; " "otherwise raise :exc:`NoSectionError`. *option* and *value* must be " "strings; if not, :exc:`TypeError` is raised." msgstr "" -#: library/configparser.rst:1197 +#: library/configparser.rst:1198 msgid "" "Write a representation of the configuration to the specified :term:`file " "object`, which must be opened in text mode (accepting strings). This " @@ -982,27 +1481,27 @@ msgid "" "surrounded by spaces." msgstr "" -#: library/configparser.rst:1205 +#: library/configparser.rst:1206 msgid "" "Comments in the original configuration file are not preserved when writing " "the configuration back. What is considered a comment, depends on the given " "values for *comment_prefix* and *inline_comment_prefix*." msgstr "" -#: library/configparser.rst:1213 +#: library/configparser.rst:1214 msgid "" "Remove the specified *option* from the specified *section*. If the section " "does not exist, raise :exc:`NoSectionError`. If the option existed to be " "removed, return :const:`True`; otherwise return :const:`False`." msgstr "" -#: library/configparser.rst:1221 +#: library/configparser.rst:1222 msgid "" "Remove the specified *section* from the configuration. If the section in " "fact existed, return ``True``. Otherwise return ``False``." msgstr "" -#: library/configparser.rst:1227 +#: library/configparser.rst:1228 msgid "" "Transforms the option name *option* as found in an input file or as passed " "in by client code to the form that should be used in the internal " @@ -1011,7 +1510,7 @@ msgid "" "of this name on instances to affect this behavior." msgstr "" -#: library/configparser.rst:1233 +#: library/configparser.rst:1234 msgid "" "You don't need to subclass the parser to use this method, you can also set " "it on an instance, to a function that takes a string argument and returns a " @@ -1019,24 +1518,30 @@ msgid "" "sensitive::" msgstr "" -#: library/configparser.rst:1241 +#: library/configparser.rst:1239 +msgid "" +"cfgparser = ConfigParser()\n" +"cfgparser.optionxform = str" +msgstr "" + +#: library/configparser.rst:1242 msgid "" "Note that when reading configuration files, whitespace around the option " "names is stripped before :meth:`optionxform` is called." msgstr "" -#: library/configparser.rst:1247 +#: library/configparser.rst:1248 msgid "" "The maximum depth for recursive interpolation for :meth:`~configparser." "ConfigParser.get` when the *raw* parameter is false. This is relevant only " "when the default *interpolation* is used." msgstr "" -#: library/configparser.rst:1255 +#: library/configparser.rst:1256 msgid "RawConfigParser Objects" msgstr "" -#: library/configparser.rst:1265 +#: library/configparser.rst:1266 msgid "" "Legacy variant of the :class:`ConfigParser`. It has interpolation disabled " "by default and allows for non-string section names, option names, and values " @@ -1044,27 +1549,27 @@ msgid "" "``defaults=`` keyword argument handling." msgstr "" -#: library/configparser.rst:1275 +#: library/configparser.rst:1276 msgid "" "Consider using :class:`ConfigParser` instead which checks types of the " "values to be stored internally. If you don't want interpolation, you can " "use ``ConfigParser(interpolation=None)``." msgstr "" -#: library/configparser.rst:1282 +#: library/configparser.rst:1283 msgid "" "Add a section named *section* to the instance. If a section by the given " "name already exists, :exc:`DuplicateSectionError` is raised. If the " "*default section* name is passed, :exc:`ValueError` is raised." msgstr "" -#: library/configparser.rst:1286 +#: library/configparser.rst:1287 msgid "" "Type of *section* is not checked which lets users create non-string named " "sections. This behaviour is unsupported and may cause internal errors." msgstr "" -#: library/configparser.rst:1292 +#: library/configparser.rst:1293 msgid "" "If the given section exists, set the given option to the specified value; " "otherwise raise :exc:`NoSectionError`. While it is possible to use :class:" @@ -1074,7 +1579,7 @@ msgid "" "string values." msgstr "" -#: library/configparser.rst:1299 +#: library/configparser.rst:1300 msgid "" "This method lets users assign non-string values to keys internally. This " "behaviour is unsupported and will cause errors when attempting to write to a " @@ -1082,32 +1587,32 @@ msgid "" "not allow such assignments to take place." msgstr "" -#: library/configparser.rst:1306 +#: library/configparser.rst:1307 msgid "Exceptions" msgstr "" -#: library/configparser.rst:1310 +#: library/configparser.rst:1311 msgid "Base class for all other :mod:`configparser` exceptions." msgstr "" -#: library/configparser.rst:1315 +#: library/configparser.rst:1316 msgid "Exception raised when a specified section is not found." msgstr "" -#: library/configparser.rst:1320 +#: library/configparser.rst:1321 msgid "" "Exception raised if :meth:`~ConfigParser.add_section` is called with the " "name of a section that is already present or in strict parsers when a " "section if found more than once in a single input file, string or dictionary." msgstr "" -#: library/configparser.rst:1324 +#: library/configparser.rst:1325 msgid "" "Added the optional *source* and *lineno* attributes and parameters to :meth:" "`!__init__`." msgstr "" -#: library/configparser.rst:1331 +#: library/configparser.rst:1332 msgid "" "Exception raised by strict parsers if a single option appears twice during " "reading from a single file, string or dictionary. This catches misspellings " @@ -1115,58 +1620,58 @@ msgid "" "representing the same case-insensitive configuration key." msgstr "" -#: library/configparser.rst:1339 +#: library/configparser.rst:1340 msgid "" "Exception raised when a specified option is not found in the specified " "section." msgstr "" -#: library/configparser.rst:1345 +#: library/configparser.rst:1346 msgid "" "Base class for exceptions raised when problems occur performing string " "interpolation." msgstr "" -#: library/configparser.rst:1351 +#: library/configparser.rst:1352 msgid "" "Exception raised when string interpolation cannot be completed because the " "number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of :" "exc:`InterpolationError`." msgstr "" -#: library/configparser.rst:1358 +#: library/configparser.rst:1359 msgid "" "Exception raised when an option referenced from a value does not exist. " "Subclass of :exc:`InterpolationError`." msgstr "" -#: library/configparser.rst:1364 +#: library/configparser.rst:1365 msgid "" "Exception raised when the source text into which substitutions are made does " "not conform to the required syntax. Subclass of :exc:`InterpolationError`." msgstr "" -#: library/configparser.rst:1370 +#: library/configparser.rst:1371 msgid "" "Exception raised when attempting to parse a file which has no section " "headers." msgstr "" -#: library/configparser.rst:1376 +#: library/configparser.rst:1377 msgid "Exception raised when errors occur attempting to parse a file." msgstr "" -#: library/configparser.rst:1378 +#: library/configparser.rst:1379 msgid "" "The ``filename`` attribute and :meth:`!__init__` constructor argument were " "removed. They have been available using the name ``source`` since 3.2." msgstr "" -#: library/configparser.rst:1383 +#: library/configparser.rst:1384 msgid "Footnotes" msgstr "" -#: library/configparser.rst:1384 +#: library/configparser.rst:1385 msgid "" "Config parsers allow for heavy customization. If you are interested in " "changing the behaviour outlined by the footnote reference, consult the " @@ -1193,14 +1698,14 @@ msgstr "" msgid "Windows ini file" msgstr "" -#: library/configparser.rst:340 +#: library/configparser.rst:341 msgid "% (percent)" msgstr "" -#: library/configparser.rst:373 +#: library/configparser.rst:374 msgid "interpolation in configuration files" msgstr "" -#: library/configparser.rst:373 +#: library/configparser.rst:374 msgid "$ (dollar)" msgstr "" diff --git a/library/constants.po b/library/constants.po index 63cbd3577..22f3607c2 100644 --- a/library/constants.po +++ b/library/constants.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-03-01 20:27+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -106,11 +106,11 @@ msgid "" "exc:`SyntaxError`), so they can be considered \"true\" constants." msgstr "" -#: library/constants.rst:83 +#: library/constants.rst:85 msgid "Constants added by the :mod:`site` module" msgstr "" -#: library/constants.rst:85 +#: library/constants.rst:87 msgid "" "The :mod:`site` module (which is imported automatically during startup, " "except if the :option:`-S` command-line option is given) adds several " @@ -118,20 +118,27 @@ msgid "" "interpreter shell and should not be used in programs." msgstr "" -#: library/constants.rst:93 +#: library/constants.rst:95 msgid "" "Objects that when printed, print a message like \"Use quit() or Ctrl-D (i.e. " "EOF) to exit\", and when called, raise :exc:`SystemExit` with the specified " "exit code." msgstr "" -#: library/constants.rst:100 +#: library/constants.rst:102 +msgid "" +"Object that when printed, prints the message \"Type help() for interactive " +"help, or help(object) for help about object.\", and when called, acts as " +"described :func:`elsewhere `." +msgstr "" + +#: library/constants.rst:109 msgid "" "Objects that when printed or called, print the text of copyright or credits, " "respectively." msgstr "" -#: library/constants.rst:105 +#: library/constants.rst:114 msgid "" "Object that when printed, prints the message \"Type license() to see the " "full license text\", and when called, displays the full license text in a " diff --git a/library/contextlib.po b/library/contextlib.po index 8e5de90d2..f65e99d39 100644 --- a/library/contextlib.po +++ b/library/contextlib.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -80,10 +80,32 @@ msgid "" "management::" msgstr "" +#: library/contextlib.rst:57 +msgid "" +"from contextlib import contextmanager\n" +"\n" +"@contextmanager\n" +"def managed_resource(*args, **kwds):\n" +" # Code to acquire resource, e.g.:\n" +" resource = acquire_resource(*args, **kwds)\n" +" try:\n" +" yield resource\n" +" finally:\n" +" # Code to release resource, e.g.:\n" +" release_resource(resource)" +msgstr "" + #: library/contextlib.rst:69 msgid "The function can then be used like this::" msgstr "" +#: library/contextlib.rst:71 +msgid "" +">>> with managed_resource(timeout=3600) as resource:\n" +"... # Resource is released at the end of this block,\n" +"... # even if code in the block raises an exception" +msgstr "" + #: library/contextlib.rst:75 msgid "" "The function being decorated must return a :term:`generator`-iterator when " @@ -141,12 +163,47 @@ msgstr "" msgid "A simple example::" msgstr "" +#: library/contextlib.rst:115 +msgid "" +"from contextlib import asynccontextmanager\n" +"\n" +"@asynccontextmanager\n" +"async def get_connection():\n" +" conn = await acquire_db_connection()\n" +" try:\n" +" yield conn\n" +" finally:\n" +" await release_db_connection(conn)\n" +"\n" +"async def get_all_users():\n" +" async with get_connection() as conn:\n" +" return conn.query('SELECT ...')" +msgstr "" + #: library/contextlib.rst:131 msgid "" "Context managers defined with :func:`asynccontextmanager` can be used either " "as decorators or with :keyword:`async with` statements::" msgstr "" +#: library/contextlib.rst:134 +msgid "" +"import time\n" +"from contextlib import asynccontextmanager\n" +"\n" +"@asynccontextmanager\n" +"async def timeit():\n" +" now = time.monotonic()\n" +" try:\n" +" yield\n" +" finally:\n" +" print(f'it took {time.monotonic() - now}s to run')\n" +"\n" +"@timeit()\n" +"async def main():\n" +" # ... async code ..." +msgstr "" + #: library/contextlib.rst:149 msgid "" "When used as a decorator, a new generator instance is implicitly created on " @@ -167,10 +224,32 @@ msgid "" "This is basically equivalent to::" msgstr "" +#: library/contextlib.rst:164 +msgid "" +"from contextlib import contextmanager\n" +"\n" +"@contextmanager\n" +"def closing(thing):\n" +" try:\n" +" yield thing\n" +" finally:\n" +" thing.close()" +msgstr "" + #: library/contextlib.rst:173 msgid "And lets you write code like this::" msgstr "" +#: library/contextlib.rst:175 +msgid "" +"from contextlib import closing\n" +"from urllib.request import urlopen\n" +"\n" +"with closing(urlopen('https://www.python.org')) as page:\n" +" for line in page:\n" +" print(line)" +msgstr "" + #: library/contextlib.rst:182 msgid "" "without needing to explicitly close ``page``. Even if an error occurs, " @@ -192,6 +271,18 @@ msgid "" "*thing* upon completion of the block. This is basically equivalent to::" msgstr "" +#: library/contextlib.rst:199 +msgid "" +"from contextlib import asynccontextmanager\n" +"\n" +"@asynccontextmanager\n" +"async def aclosing(thing):\n" +" try:\n" +" yield thing\n" +" finally:\n" +" await thing.aclose()" +msgstr "" + #: library/contextlib.rst:208 msgid "" "Significantly, ``aclosing()`` supports deterministic cleanup of async " @@ -199,6 +290,16 @@ msgid "" "exception. For example::" msgstr "" +#: library/contextlib.rst:212 +msgid "" +"from contextlib import aclosing\n" +"\n" +"async with aclosing(my_generator()) as values:\n" +" async for value in values:\n" +" if value == 42:\n" +" break" +msgstr "" + #: library/contextlib.rst:219 msgid "" "This pattern ensures that the generator's async exit code is executed in the " @@ -214,16 +315,57 @@ msgid "" "optional context manager, for example::" msgstr "" +#: library/contextlib.rst:235 +msgid "" +"def myfunction(arg, ignore_exceptions=False):\n" +" if ignore_exceptions:\n" +" # Use suppress to ignore all exceptions.\n" +" cm = contextlib.suppress(Exception)\n" +" else:\n" +" # Do not ignore any exceptions, cm has no effect.\n" +" cm = contextlib.nullcontext()\n" +" with cm:\n" +" # Do something" +msgstr "" + #: library/contextlib.rst:245 msgid "An example using *enter_result*::" msgstr "" +#: library/contextlib.rst:247 +msgid "" +"def process_file(file_or_path):\n" +" if isinstance(file_or_path, str):\n" +" # If string, open file\n" +" cm = open(file_or_path)\n" +" else:\n" +" # Caller is responsible for closing file\n" +" cm = nullcontext(file_or_path)\n" +"\n" +" with cm as file:\n" +" # Perform processing on the file" +msgstr "" + #: library/contextlib.rst:258 msgid "" "It can also be used as a stand-in for :ref:`asynchronous context managers " "`::" msgstr "" +#: library/contextlib.rst:261 +msgid "" +"async def send_http(session=None):\n" +" if not session:\n" +" # If no http session, create it with aiohttp\n" +" cm = aiohttp.ClientSession()\n" +" else:\n" +" # Caller is responsible for closing the session\n" +" cm = nullcontext(session)\n" +"\n" +" async with cm as session:\n" +" # Send http requests with session" +msgstr "" + #: library/contextlib.rst:274 msgid ":term:`asynchronous context manager` support was added." msgstr "" @@ -248,10 +390,34 @@ msgstr "" msgid "For example::" msgstr "" +#: library/contextlib.rst:293 +msgid "" +"from contextlib import suppress\n" +"\n" +"with suppress(FileNotFoundError):\n" +" os.remove('somefile.tmp')\n" +"\n" +"with suppress(FileNotFoundError):\n" +" os.remove('someotherfile.tmp')" +msgstr "" + #: library/contextlib.rst:301 msgid "This code is equivalent to::" msgstr "" +#: library/contextlib.rst:303 +msgid "" +"try:\n" +" os.remove('somefile.tmp')\n" +"except FileNotFoundError:\n" +" pass\n" +"\n" +"try:\n" +" os.remove('someotherfile.tmp')\n" +"except FileNotFoundError:\n" +" pass" +msgstr "" + #: library/contextlib.rst:362 library/contextlib.rst:389 msgid "This context manager is :ref:`reentrant `." msgstr "" @@ -292,16 +458,36 @@ msgid "" "`with` statement::" msgstr "" +#: library/contextlib.rst:341 +msgid "" +"with redirect_stdout(io.StringIO()) as f:\n" +" help(pow)\n" +"s = f.getvalue()" +msgstr "" + #: library/contextlib.rst:345 msgid "" "To send the output of :func:`help` to a file on disk, redirect the output to " "a regular file::" msgstr "" +#: library/contextlib.rst:348 +msgid "" +"with open('help.txt', 'w') as f:\n" +" with redirect_stdout(f):\n" +" help(pow)" +msgstr "" + #: library/contextlib.rst:352 msgid "To send the output of :func:`help` to *sys.stderr*::" msgstr "" +#: library/contextlib.rst:354 +msgid "" +"with redirect_stdout(sys.stderr):\n" +" help(pow)" +msgstr "" + #: library/contextlib.rst:357 msgid "" "Note that the global side effect on :data:`sys.stdout` means that this " @@ -354,19 +540,66 @@ msgstr "" msgid "Example of ``ContextDecorator``::" msgstr "" +#: library/contextlib.rst:407 +msgid "" +"from contextlib import ContextDecorator\n" +"\n" +"class mycontext(ContextDecorator):\n" +" def __enter__(self):\n" +" print('Starting')\n" +" return self\n" +"\n" +" def __exit__(self, *exc):\n" +" print('Finishing')\n" +" return False" +msgstr "" + #: library/contextlib.rst:490 msgid "The class can then be used like this::" msgstr "" +#: library/contextlib.rst:420 +msgid "" +">>> @mycontext()\n" +"... def function():\n" +"... print('The bit in the middle')\n" +"...\n" +">>> function()\n" +"Starting\n" +"The bit in the middle\n" +"Finishing\n" +"\n" +">>> with mycontext():\n" +"... print('The bit in the middle')\n" +"...\n" +"Starting\n" +"The bit in the middle\n" +"Finishing" +msgstr "" + #: library/contextlib.rst:436 msgid "" "This change is just syntactic sugar for any construct of the following form::" msgstr "" +#: library/contextlib.rst:438 +msgid "" +"def f():\n" +" with cm():\n" +" # Do stuff" +msgstr "" + #: library/contextlib.rst:442 msgid "``ContextDecorator`` lets you instead write::" msgstr "" +#: library/contextlib.rst:444 +msgid "" +"@cm()\n" +"def f():\n" +" # Do stuff" +msgstr "" + #: library/contextlib.rst:448 msgid "" "It makes it clear that the ``cm`` applies to the whole function, rather than " @@ -379,6 +612,18 @@ msgid "" "using ``ContextDecorator`` as a mixin class::" msgstr "" +#: library/contextlib.rst:454 +msgid "" +"from contextlib import ContextDecorator\n" +"\n" +"class mycontext(ContextBaseClass, ContextDecorator):\n" +" def __enter__(self):\n" +" return self\n" +"\n" +" def __exit__(self, *exc):\n" +" return False" +msgstr "" + #: library/contextlib.rst:464 msgid "" "As the decorated function must be able to be called multiple times, the " @@ -396,6 +641,42 @@ msgstr "" msgid "Example of ``AsyncContextDecorator``::" msgstr "" +#: library/contextlib.rst:478 +msgid "" +"from asyncio import run\n" +"from contextlib import AsyncContextDecorator\n" +"\n" +"class mycontext(AsyncContextDecorator):\n" +" async def __aenter__(self):\n" +" print('Starting')\n" +" return self\n" +"\n" +" async def __aexit__(self, *exc):\n" +" print('Finishing')\n" +" return False" +msgstr "" + +#: library/contextlib.rst:492 +msgid "" +">>> @mycontext()\n" +"... async def function():\n" +"... print('The bit in the middle')\n" +"...\n" +">>> run(function())\n" +"Starting\n" +"The bit in the middle\n" +"Finishing\n" +"\n" +">>> async def function():\n" +"... async with mycontext():\n" +"... print('The bit in the middle')\n" +"...\n" +">>> run(function())\n" +"Starting\n" +"The bit in the middle\n" +"Finishing" +msgstr "" + #: library/contextlib.rst:515 msgid "" "A context manager that is designed to make it easy to programmatically " @@ -409,6 +690,15 @@ msgid "" "as follows::" msgstr "" +#: library/contextlib.rst:522 +msgid "" +"with ExitStack() as stack:\n" +" files = [stack.enter_context(open(fname)) for fname in filenames]\n" +" # All opened files will automatically be closed at the end of\n" +" # the with statement, even if attempts to open files later\n" +" # in the list raise an exception" +msgstr "" + #: library/contextlib.rst:528 msgid "" "The :meth:`~object.__enter__` method returns the :class:`ExitStack` " @@ -531,6 +821,18 @@ msgid "" "operation as follows::" msgstr "" +#: library/contextlib.rst:606 +msgid "" +"with ExitStack() as stack:\n" +" files = [stack.enter_context(open(fname)) for fname in filenames]\n" +" # Hold onto the close method, but don't call it yet.\n" +" close_files = stack.pop_all().close\n" +" # If opening any file fails, all previously opened files will be\n" +" # closed automatically. If all files are opened successfully,\n" +" # they will remain open even after the with statement ends.\n" +" # close_files() can then be invoked explicitly to close them all." +msgstr "" + #: library/contextlib.rst:617 msgid "" "Immediately unwinds the callback stack, invoking callbacks in the reverse " @@ -581,6 +883,16 @@ msgstr "" msgid "Continuing the example for :func:`asynccontextmanager`::" msgstr "" +#: library/contextlib.rst:656 +msgid "" +"async with AsyncExitStack() as stack:\n" +" connections = [await stack.enter_async_context(get_connection())\n" +" for i in range(5)]\n" +" # All opened connections will automatically be released at the end of\n" +" # the async with statement, even if attempts to open a connection\n" +" # later in the list raise an exception." +msgstr "" + #: library/contextlib.rst:666 msgid "Examples and Recipes" msgstr "" @@ -605,6 +917,17 @@ msgid "" "of the context managers being optional::" msgstr "" +#: library/contextlib.rst:682 +msgid "" +"with ExitStack() as stack:\n" +" for resource in resources:\n" +" stack.enter_context(resource)\n" +" if need_special_resource():\n" +" special = acquire_special_resource()\n" +" stack.callback(release_special_resource, special)\n" +" # Perform operations that use the acquired resources" +msgstr "" + #: library/contextlib.rst:690 msgid "" "As shown, :class:`ExitStack` also makes it quite easy to use :keyword:`with` " @@ -625,6 +948,18 @@ msgid "" "be separated slightly in order to allow this::" msgstr "" +#: library/contextlib.rst:704 +msgid "" +"stack = ExitStack()\n" +"try:\n" +" x = stack.enter_context(cm)\n" +"except Exception:\n" +" # handle __enter__ exception\n" +"else:\n" +" with stack:\n" +" # Handle normal case" +msgstr "" + #: library/contextlib.rst:713 msgid "" "Actually needing to do this is likely to indicate that the underlying API " @@ -654,6 +989,44 @@ msgid "" "function, and maps them to the context management protocol::" msgstr "" +#: library/contextlib.rst:733 +msgid "" +"from contextlib import contextmanager, AbstractContextManager, ExitStack\n" +"\n" +"class ResourceManager(AbstractContextManager):\n" +"\n" +" def __init__(self, acquire_resource, release_resource, " +"check_resource_ok=None):\n" +" self.acquire_resource = acquire_resource\n" +" self.release_resource = release_resource\n" +" if check_resource_ok is None:\n" +" def check_resource_ok(resource):\n" +" return True\n" +" self.check_resource_ok = check_resource_ok\n" +"\n" +" @contextmanager\n" +" def _cleanup_on_error(self):\n" +" with ExitStack() as stack:\n" +" stack.push(self)\n" +" yield\n" +" # The validation check passed and didn't raise an exception\n" +" # Accordingly, we want to keep the resource, and pass it\n" +" # back to our caller\n" +" stack.pop_all()\n" +"\n" +" def __enter__(self):\n" +" resource = self.acquire_resource()\n" +" with self._cleanup_on_error():\n" +" if not self.check_resource_ok(resource):\n" +" msg = \"Failed validation for {!r}\"\n" +" raise RuntimeError(msg.format(resource))\n" +" return resource\n" +"\n" +" def __exit__(self, *exc_details):\n" +" # We don't need to duplicate any of our resource release logic\n" +" self.release_resource()" +msgstr "" + #: library/contextlib.rst:769 msgid "Replacing any use of ``try-finally`` and flag variables" msgstr "" @@ -666,6 +1039,18 @@ msgid "" "by using an ``except`` clause instead), it looks something like this::" msgstr "" +#: library/contextlib.rst:776 +msgid "" +"cleanup_needed = True\n" +"try:\n" +" result = perform_operation()\n" +" if result:\n" +" cleanup_needed = False\n" +"finally:\n" +" if cleanup_needed:\n" +" cleanup_resources()" +msgstr "" + #: library/contextlib.rst:785 msgid "" "As with any ``try`` statement based code, this can cause problems for " @@ -680,6 +1065,17 @@ msgid "" "executing that callback::" msgstr "" +#: library/contextlib.rst:793 +msgid "" +"from contextlib import ExitStack\n" +"\n" +"with ExitStack() as stack:\n" +" stack.callback(cleanup_resources)\n" +" result = perform_operation()\n" +" if result:\n" +" stack.pop_all()" +msgstr "" + #: library/contextlib.rst:801 msgid "" "This allows the intended cleanup behaviour to be made explicit up front, " @@ -692,6 +1088,24 @@ msgid "" "even further by means of a small helper class::" msgstr "" +#: library/contextlib.rst:807 +msgid "" +"from contextlib import ExitStack\n" +"\n" +"class Callback(ExitStack):\n" +" def __init__(self, callback, /, *args, **kwds):\n" +" super().__init__()\n" +" self.callback(callback, *args, **kwds)\n" +"\n" +" def cancel(self):\n" +" self.pop_all()\n" +"\n" +"with Callback(cleanup_resources) as cb:\n" +" result = perform_operation()\n" +" if result:\n" +" cb.cancel()" +msgstr "" + #: library/contextlib.rst:822 msgid "" "If the resource cleanup isn't already neatly bundled into a standalone " @@ -699,6 +1113,19 @@ msgid "" "`ExitStack.callback` to declare the resource cleanup in advance::" msgstr "" +#: library/contextlib.rst:827 +msgid "" +"from contextlib import ExitStack\n" +"\n" +"with ExitStack() as stack:\n" +" @stack.callback\n" +" def cleanup_resources():\n" +" ...\n" +" result = perform_operation()\n" +" if result:\n" +" stack.pop_all()" +msgstr "" + #: library/contextlib.rst:837 msgid "" "Due to the way the decorator protocol works, a callback function declared " @@ -725,14 +1152,47 @@ msgid "" "in a single definition::" msgstr "" +#: library/contextlib.rst:854 +msgid "" +"from contextlib import ContextDecorator\n" +"import logging\n" +"\n" +"logging.basicConfig(level=logging.INFO)\n" +"\n" +"class track_entry_and_exit(ContextDecorator):\n" +" def __init__(self, name):\n" +" self.name = name\n" +"\n" +" def __enter__(self):\n" +" logging.info('Entering: %s', self.name)\n" +"\n" +" def __exit__(self, exc_type, exc, exc_tb):\n" +" logging.info('Exiting: %s', self.name)" +msgstr "" + #: library/contextlib.rst:869 msgid "Instances of this class can be used as both a context manager::" msgstr "" +#: library/contextlib.rst:871 +msgid "" +"with track_entry_and_exit('widget loader'):\n" +" print('Some time consuming activity goes here')\n" +" load_widget()" +msgstr "" + #: library/contextlib.rst:875 msgid "And also as a function decorator::" msgstr "" +#: library/contextlib.rst:877 +msgid "" +"@track_entry_and_exit('widget loader')\n" +"def activity():\n" +" print('Some time consuming activity goes here')\n" +" load_widget()" +msgstr "" + #: library/contextlib.rst:882 msgid "" "Note that there is one additional limitation when using context managers as " @@ -784,6 +1244,29 @@ msgid "" "to yield if an attempt is made to use them a second time::" msgstr "" +#: library/contextlib.rst:916 +msgid "" +">>> from contextlib import contextmanager\n" +">>> @contextmanager\n" +"... def singleuse():\n" +"... print(\"Before\")\n" +"... yield\n" +"... print(\"After\")\n" +"...\n" +">>> cm = singleuse()\n" +">>> with cm:\n" +"... pass\n" +"...\n" +"Before\n" +"After\n" +">>> with cm:\n" +"... pass\n" +"...\n" +"Traceback (most recent call last):\n" +" ...\n" +"RuntimeError: generator didn't yield" +msgstr "" + #: library/contextlib.rst:940 msgid "Reentrant context managers" msgstr "" @@ -803,6 +1286,24 @@ msgid "" "very simple example of reentrant use::" msgstr "" +#: library/contextlib.rst:951 +msgid "" +">>> from contextlib import redirect_stdout\n" +">>> from io import StringIO\n" +">>> stream = StringIO()\n" +">>> write_to_stream = redirect_stdout(stream)\n" +">>> with write_to_stream:\n" +"... print(\"This is written to the stream rather than stdout\")\n" +"... with write_to_stream:\n" +"... print(\"This is also written to the stream\")\n" +"...\n" +">>> print(\"This is written directly to stdout\")\n" +"This is written directly to stdout\n" +">>> print(stream.getvalue())\n" +"This is written to the stream rather than stdout\n" +"This is also written to the stream" +msgstr "" + #: library/contextlib.rst:966 msgid "" "Real world examples of reentrancy are more likely to involve multiple " @@ -846,6 +1347,35 @@ msgid "" "any with statement, regardless of where those callbacks were added::" msgstr "" +#: library/contextlib.rst:997 +msgid "" +">>> from contextlib import ExitStack\n" +">>> stack = ExitStack()\n" +">>> with stack:\n" +"... stack.callback(print, \"Callback: from first context\")\n" +"... print(\"Leaving first context\")\n" +"...\n" +"Leaving first context\n" +"Callback: from first context\n" +">>> with stack:\n" +"... stack.callback(print, \"Callback: from second context\")\n" +"... print(\"Leaving second context\")\n" +"...\n" +"Leaving second context\n" +"Callback: from second context\n" +">>> with stack:\n" +"... stack.callback(print, \"Callback: from outer context\")\n" +"... with stack:\n" +"... stack.callback(print, \"Callback: from inner context\")\n" +"... print(\"Leaving inner context\")\n" +"... print(\"Leaving outer context\")\n" +"...\n" +"Leaving inner context\n" +"Callback: from inner context\n" +"Callback: from outer context\n" +"Leaving outer context" +msgstr "" + #: library/contextlib.rst:1023 msgid "" "As the output from the example shows, reusing a single stack object across " @@ -859,3 +1389,19 @@ msgid "" "Using separate :class:`ExitStack` instances instead of reusing a single " "instance avoids that problem::" msgstr "" + +#: library/contextlib.rst:1031 +msgid "" +">>> from contextlib import ExitStack\n" +">>> with ExitStack() as outer_stack:\n" +"... outer_stack.callback(print, \"Callback: from outer context\")\n" +"... with ExitStack() as inner_stack:\n" +"... inner_stack.callback(print, \"Callback: from inner context\")\n" +"... print(\"Leaving inner context\")\n" +"... print(\"Leaving outer context\")\n" +"...\n" +"Leaving inner context\n" +"Callback: from inner context\n" +"Leaving outer context\n" +"Callback: from outer context" +msgstr "" diff --git a/library/contextvars.po b/library/contextvars.po index c1b3b27fd..38d42bfdc 100644 --- a/library/contextvars.po +++ b/library/contextvars.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -32,7 +32,7 @@ msgstr "" #: library/contextvars.rst:17 msgid "" "Context managers that have state should use Context Variables instead of :" -"func:`threading.local()` to prevent their state from bleeding to other code " +"func:`threading.local` to prevent their state from bleeding to other code " "unexpectedly, when used in concurrent code." msgstr "" @@ -48,6 +48,10 @@ msgstr "" msgid "This class is used to declare a new Context Variable, e.g.::" msgstr "" +#: library/contextvars.rst:33 +msgid "var: ContextVar[int] = ContextVar('var', default=42)" +msgstr "" + #: library/contextvars.rst:35 msgid "" "The required *name* parameter is used for introspection and debug purposes." @@ -123,6 +127,18 @@ msgstr "" msgid "For example::" msgstr "" +#: library/contextvars.rst:87 +msgid "" +"var = ContextVar('var')\n" +"\n" +"token = var.set('new value')\n" +"# code that uses 'var'; var.get() returns 'new value'.\n" +"var.reset(token)\n" +"\n" +"# After the reset call the var has no value again, so\n" +"# var.get() would raise a LookupError." +msgstr "" + #: library/contextvars.rst:99 msgid "" "*Token* objects are returned by the :meth:`ContextVar.set` method. They can " @@ -161,6 +177,12 @@ msgid "" "variables and their values that are set in it::" msgstr "" +#: library/contextvars.rst:131 +msgid "" +"ctx: Context = copy_context()\n" +"print(list(ctx.items()))" +msgstr "" + #: library/contextvars.rst:134 msgid "" "The function has an *O*\\ (1) complexity, i.e. works equally fast for " @@ -182,7 +204,7 @@ msgstr "" msgid "" "Every thread will have a different top-level :class:`~contextvars.Context` " "object. This means that a :class:`ContextVar` object behaves in a similar " -"fashion to :func:`threading.local()` when values are assigned in different " +"fashion to :func:`threading.local` when values are assigned in different " "threads." msgstr "" @@ -203,6 +225,35 @@ msgid "" "in the context object::" msgstr "" +#: library/contextvars.rst:163 +msgid "" +"var = ContextVar('var')\n" +"var.set('spam')\n" +"\n" +"def main():\n" +" # 'var' was set to 'spam' before\n" +" # calling 'copy_context()' and 'ctx.run(main)', so:\n" +" # var.get() == ctx[var] == 'spam'\n" +"\n" +" var.set('ham')\n" +"\n" +" # Now, after setting 'var' to 'ham':\n" +" # var.get() == ctx[var] == 'ham'\n" +"\n" +"ctx = copy_context()\n" +"\n" +"# Any changes that the 'main' function makes to 'var'\n" +"# will be contained in 'ctx'.\n" +"ctx.run(main)\n" +"\n" +"# The 'main()' function was run in the 'ctx' context,\n" +"# so changes to 'var' are contained in it:\n" +"# ctx[var] == 'ham'\n" +"\n" +"# However, outside of 'ctx', 'var' is still set to 'spam':\n" +"# var.get() == 'spam'" +msgstr "" + #: library/contextvars.rst:189 msgid "" "The method raises a :exc:`RuntimeError` when called on the same context " @@ -264,3 +315,49 @@ msgid "" "server, that uses a context variable to make the address of a remote client " "available in the Task that handles that client::" msgstr "" + +#: library/contextvars.rst:247 +msgid "" +"import asyncio\n" +"import contextvars\n" +"\n" +"client_addr_var = contextvars.ContextVar('client_addr')\n" +"\n" +"def render_goodbye():\n" +" # The address of the currently handled client can be accessed\n" +" # without passing it explicitly to this function.\n" +"\n" +" client_addr = client_addr_var.get()\n" +" return f'Good bye, client @ {client_addr}\\r\\n'.encode()\n" +"\n" +"async def handle_request(reader, writer):\n" +" addr = writer.transport.get_extra_info('socket').getpeername()\n" +" client_addr_var.set(addr)\n" +"\n" +" # In any code that we call is now possible to get\n" +" # client's address by calling 'client_addr_var.get()'.\n" +"\n" +" while True:\n" +" line = await reader.readline()\n" +" print(line)\n" +" if not line.strip():\n" +" break\n" +"\n" +" writer.write(b'HTTP/1.1 200 OK\\r\\n') # status line\n" +" writer.write(b'\\r\\n') # headers\n" +" writer.write(render_goodbye()) # body\n" +" writer.close()\n" +"\n" +"async def main():\n" +" srv = await asyncio.start_server(\n" +" handle_request, '127.0.0.1', 8081)\n" +"\n" +" async with srv:\n" +" await srv.serve_forever()\n" +"\n" +"asyncio.run(main())\n" +"\n" +"# To test it you can use telnet or curl:\n" +"# telnet 127.0.0.1 8081\n" +"# curl 127.0.0.1:8081" +msgstr "" diff --git a/library/crypt.po b/library/crypt.po index ff0fc95d1..f3c55a8c2 100644 --- a/library/crypt.po +++ b/library/crypt.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -49,12 +49,8 @@ msgid "" "be available on this module." msgstr "" -#: library/crypt.rst:40 -msgid ":ref:`Availability `: Unix, not VxWorks." -msgstr "" - #: includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not Emscripten, not WASI." +msgid "Availability" msgstr "" #: includes/wasm-notavail.rst:5 @@ -202,12 +198,42 @@ msgid "" "compare_digest` is suitable for this purpose)::" msgstr "" +#: library/crypt.rst:159 +msgid "" +"import pwd\n" +"import crypt\n" +"import getpass\n" +"from hmac import compare_digest as compare_hash\n" +"\n" +"def login():\n" +" username = input('Python login: ')\n" +" cryptedpasswd = pwd.getpwnam(username)[1]\n" +" if cryptedpasswd:\n" +" if cryptedpasswd == 'x' or cryptedpasswd == '*':\n" +" raise ValueError('no support for shadow passwords')\n" +" cleartext = getpass.getpass()\n" +" return compare_hash(crypt.crypt(cleartext, cryptedpasswd), " +"cryptedpasswd)\n" +" else:\n" +" return True" +msgstr "" + #: library/crypt.rst:175 msgid "" "To generate a hash of a password using the strongest available method and " "check it against the original::" msgstr "" +#: library/crypt.rst:178 +msgid "" +"import crypt\n" +"from hmac import compare_digest as compare_hash\n" +"\n" +"hashed = crypt.crypt(plaintext)\n" +"if not compare_hash(hashed, crypt.crypt(plaintext, hashed)):\n" +" raise ValueError(\"hashed version doesn't validate against original\")" +msgstr "" + #: library/crypt.rst:33 library/crypt.rst:119 msgid "crypt(3)" msgstr "" diff --git a/library/csv.po b/library/csv.po index d5ae67916..7cbcc1188 100644 --- a/library/csv.po +++ b/library/csv.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -98,6 +98,17 @@ msgstr "" msgid "A short usage example::" msgstr "" +#: library/csv.rst:78 +msgid "" +">>> import csv\n" +">>> with open('eggs.csv', newline='') as csvfile:\n" +"... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')\n" +"... for row in spamreader:\n" +"... print(', '.join(row))\n" +"Spam, Spam, Spam, Spam, Spam, Baked Beans\n" +"Spam, Lovely Spam, Wonderful Spam" +msgstr "" + #: library/csv.rst:89 msgid "" "Return a writer object responsible for converting the user's data into " @@ -118,6 +129,16 @@ msgid "" "other non-string data are stringified with :func:`str` before being written." msgstr "" +#: library/csv.rst:108 +msgid "" +"import csv\n" +"with open('eggs.csv', 'w', newline='') as csvfile:\n" +" spamwriter = csv.writer(csvfile, delimiter=' ',\n" +" quotechar='|', quoting=csv.QUOTE_MINIMAL)\n" +" spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])\n" +" spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])" +msgstr "" + #: library/csv.rst:118 msgid "" "Associate *dialect* with *name*. *name* must be a string. The dialect can " @@ -200,6 +221,21 @@ msgstr "" msgid "Returned rows are now of type :class:`dict`." msgstr "" +#: library/csv.rst:183 +msgid "" +">>> import csv\n" +">>> with open('names.csv', newline='') as csvfile:\n" +"... reader = csv.DictReader(csvfile)\n" +"... for row in reader:\n" +"... print(row['first_name'], row['last_name'])\n" +"...\n" +"Eric Idle\n" +"John Cleese\n" +"\n" +">>> print(row)\n" +"{'first_name': 'John', 'last_name': 'Cleese'}" +msgstr "" + #: library/csv.rst:199 msgid "" "Create an object which operates like a regular writer but maps dictionaries " @@ -222,6 +258,20 @@ msgid "" "of the :class:`DictWriter` class is not optional." msgstr "" +#: library/csv.rst:221 +msgid "" +"import csv\n" +"\n" +"with open('names.csv', 'w', newline='') as csvfile:\n" +" fieldnames = ['first_name', 'last_name']\n" +" writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n" +"\n" +" writer.writeheader()\n" +" writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})\n" +" writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})\n" +" writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})" +msgstr "" + #: library/csv.rst:235 msgid "" "The :class:`Dialect` class is a container class whose attributes contain " @@ -238,6 +288,14 @@ msgid "" "classes through their initializer (``__init__``) functions like this::" msgstr "" +#: library/csv.rst:245 +msgid "" +"import csv\n" +"\n" +"with open('students.csv', 'w', newline='') as csvfile:\n" +" writer = csv.writer(csvfile, dialect='unix')" +msgstr "" + #: library/csv.rst:253 msgid "" "The :class:`excel` class defines the usual properties of an Excel-generated " @@ -307,6 +365,15 @@ msgstr "" msgid "An example for :class:`Sniffer` use::" msgstr "" +#: library/csv.rst:307 +msgid "" +"with open('example.csv', newline='') as csvfile:\n" +" dialect = csv.Sniffer().sniff(csvfile.read(1024))\n" +" csvfile.seek(0)\n" +" reader = csv.reader(csvfile, dialect)\n" +" # ... process CSV file contents here ..." +msgstr "" + #: library/csv.rst:316 msgid "The :mod:`csv` module defines the following constants:" msgstr "" @@ -372,19 +439,26 @@ msgid "" "``None`` and to otherwise behave as :data:`QUOTE_NONNUMERIC`." msgstr "" -#: library/csv.rst:368 +#: library/csv.rst:370 +msgid "" +"Due to a bug, constants :data:`QUOTE_NOTNULL` and :data:`QUOTE_STRINGS` do " +"not affect behaviour of :class:`reader` objects. This bug is fixed in Python " +"3.13." +msgstr "" + +#: library/csv.rst:374 msgid "The :mod:`csv` module defines the following exception:" msgstr "" -#: library/csv.rst:373 +#: library/csv.rst:379 msgid "Raised by any of the functions when an error is detected." msgstr "" -#: library/csv.rst:378 +#: library/csv.rst:384 msgid "Dialects and Formatting Parameters" msgstr "" -#: library/csv.rst:380 +#: library/csv.rst:386 msgid "" "To make it easier to specify the format of input and output records, " "specific formatting parameters are grouped together into dialects. A " @@ -397,16 +471,16 @@ msgid "" "attributes defined below for the :class:`Dialect` class." msgstr "" -#: library/csv.rst:390 +#: library/csv.rst:396 msgid "Dialects support the following attributes:" msgstr "" -#: library/csv.rst:395 +#: library/csv.rst:401 msgid "" "A one-character string used to separate fields. It defaults to ``','``." msgstr "" -#: library/csv.rst:400 +#: library/csv.rst:406 msgid "" "Controls how instances of *quotechar* appearing inside a field should " "themselves be quoted. When :const:`True`, the character is doubled. When :" @@ -414,13 +488,13 @@ msgid "" "defaults to :const:`True`." msgstr "" -#: library/csv.rst:405 +#: library/csv.rst:411 msgid "" "On output, if *doublequote* is :const:`False` and no *escapechar* is set, :" "exc:`Error` is raised if a *quotechar* is found in a field." msgstr "" -#: library/csv.rst:411 +#: library/csv.rst:417 msgid "" "A one-character string used by the writer to escape the *delimiter* if " "*quoting* is set to :const:`QUOTE_NONE` and the *quotechar* if *doublequote* " @@ -429,64 +503,64 @@ msgid "" "escaping." msgstr "" -#: library/csv.rst:416 +#: library/csv.rst:422 msgid "An empty *escapechar* is not allowed." msgstr "" -#: library/csv.rst:421 +#: library/csv.rst:427 msgid "" "The string used to terminate lines produced by the :class:`writer`. It " "defaults to ``'\\r\\n'``." msgstr "" -#: library/csv.rst:426 +#: library/csv.rst:432 msgid "" "The :class:`reader` is hard-coded to recognise either ``'\\r'`` or ``'\\n'`` " "as end-of-line, and ignores *lineterminator*. This behavior may change in " "the future." msgstr "" -#: library/csv.rst:433 +#: library/csv.rst:439 msgid "" "A one-character string used to quote fields containing special characters, " "such as the *delimiter* or *quotechar*, or which contain new-line " "characters. It defaults to ``'\"'``." msgstr "" -#: library/csv.rst:437 +#: library/csv.rst:443 msgid "An empty *quotechar* is not allowed." msgstr "" -#: library/csv.rst:442 +#: library/csv.rst:448 msgid "" "Controls when quotes should be generated by the writer and recognised by the " "reader. It can take on any of the :ref:`QUOTE_\\* constants ` and defaults to :const:`QUOTE_MINIMAL`." msgstr "" -#: library/csv.rst:449 +#: library/csv.rst:455 msgid "" "When :const:`True`, spaces immediately following the *delimiter* are " "ignored. The default is :const:`False`." msgstr "" -#: library/csv.rst:455 +#: library/csv.rst:461 msgid "" "When ``True``, raise exception :exc:`Error` on bad CSV input. The default is " "``False``." msgstr "" -#: library/csv.rst:461 +#: library/csv.rst:467 msgid "Reader Objects" msgstr "" -#: library/csv.rst:463 +#: library/csv.rst:469 msgid "" "Reader objects (:class:`DictReader` instances and objects returned by the :" "func:`reader` function) have the following public methods:" msgstr "" -#: library/csv.rst:468 +#: library/csv.rst:474 msgid "" "Return the next row of the reader's iterable object as a list (if the object " "was returned from :func:`reader`) or a dict (if it is a :class:`DictReader` " @@ -494,35 +568,35 @@ msgid "" "should call this as ``next(reader)``." msgstr "" -#: library/csv.rst:474 +#: library/csv.rst:480 msgid "Reader objects have the following public attributes:" msgstr "" -#: library/csv.rst:478 +#: library/csv.rst:484 msgid "A read-only description of the dialect in use by the parser." msgstr "" -#: library/csv.rst:483 +#: library/csv.rst:489 msgid "" "The number of lines read from the source iterator. This is not the same as " "the number of records returned, as records can span multiple lines." msgstr "" -#: library/csv.rst:487 +#: library/csv.rst:493 msgid "DictReader objects have the following public attribute:" msgstr "" -#: library/csv.rst:491 +#: library/csv.rst:497 msgid "" "If not passed as a parameter when creating the object, this attribute is " "initialized upon first access or when the first record is read from the file." msgstr "" -#: library/csv.rst:498 +#: library/csv.rst:504 msgid "Writer Objects" msgstr "" -#: library/csv.rst:500 +#: library/csv.rst:506 msgid "" ":class:`writer` objects (:class:`DictWriter` instances and objects returned " "by the :func:`writer` function) have the following public methods. A *row* " @@ -534,66 +608,92 @@ msgid "" "complex numbers at all)." msgstr "" -#: library/csv.rst:511 +#: library/csv.rst:517 msgid "" "Write the *row* parameter to the writer's file object, formatted according " "to the current :class:`Dialect`. Return the return value of the call to the " "*write* method of the underlying file object." msgstr "" -#: library/csv.rst:515 +#: library/csv.rst:521 msgid "Added support of arbitrary iterables." msgstr "" -#: library/csv.rst:520 +#: library/csv.rst:526 msgid "" "Write all elements in *rows* (an iterable of *row* objects as described " "above) to the writer's file object, formatted according to the current " "dialect." msgstr "" -#: library/csv.rst:524 +#: library/csv.rst:530 msgid "Writer objects have the following public attribute:" msgstr "" -#: library/csv.rst:529 +#: library/csv.rst:535 msgid "A read-only description of the dialect in use by the writer." msgstr "" -#: library/csv.rst:532 +#: library/csv.rst:538 msgid "DictWriter objects have the following public method:" msgstr "" -#: library/csv.rst:537 +#: library/csv.rst:543 msgid "" "Write a row with the field names (as specified in the constructor) to the " "writer's file object, formatted according to the current dialect. Return the " "return value of the :meth:`csvwriter.writerow` call used internally." msgstr "" -#: library/csv.rst:542 +#: library/csv.rst:548 msgid "" ":meth:`writeheader` now also returns the value returned by the :meth:" "`csvwriter.writerow` method it uses internally." msgstr "" -#: library/csv.rst:550 +#: library/csv.rst:556 msgid "Examples" msgstr "" -#: library/csv.rst:552 +#: library/csv.rst:558 msgid "The simplest example of reading a CSV file::" msgstr "" #: library/csv.rst:560 +msgid "" +"import csv\n" +"with open('some.csv', newline='') as f:\n" +" reader = csv.reader(f)\n" +" for row in reader:\n" +" print(row)" +msgstr "" + +#: library/csv.rst:566 msgid "Reading a file with an alternate format::" msgstr "" #: library/csv.rst:568 +msgid "" +"import csv\n" +"with open('passwd', newline='') as f:\n" +" reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)\n" +" for row in reader:\n" +" print(row)" +msgstr "" + +#: library/csv.rst:574 msgid "The corresponding simplest possible writing example is::" msgstr "" -#: library/csv.rst:575 +#: library/csv.rst:576 +msgid "" +"import csv\n" +"with open('some.csv', 'w', newline='') as f:\n" +" writer = csv.writer(f)\n" +" writer.writerows(someiterable)" +msgstr "" + +#: library/csv.rst:581 msgid "" "Since :func:`open` is used to open a CSV file for reading, the file will by " "default be decoded into unicode using the system default encoding (see :func:" @@ -603,31 +703,68 @@ msgstr "" #: library/csv.rst:586 msgid "" +"import csv\n" +"with open('some.csv', newline='', encoding='utf-8') as f:\n" +" reader = csv.reader(f)\n" +" for row in reader:\n" +" print(row)" +msgstr "" + +#: library/csv.rst:592 +msgid "" "The same applies to writing in something other than the system default " "encoding: specify the encoding argument when opening the output file." msgstr "" -#: library/csv.rst:589 +#: library/csv.rst:595 msgid "Registering a new dialect::" msgstr "" -#: library/csv.rst:596 +#: library/csv.rst:597 +msgid "" +"import csv\n" +"csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)\n" +"with open('passwd', newline='') as f:\n" +" reader = csv.reader(f, 'unixpwd')" +msgstr "" + +#: library/csv.rst:602 msgid "" "A slightly more advanced use of the reader --- catching and reporting " "errors::" msgstr "" -#: library/csv.rst:608 +#: library/csv.rst:604 +msgid "" +"import csv, sys\n" +"filename = 'some.csv'\n" +"with open(filename, newline='') as f:\n" +" reader = csv.reader(f)\n" +" try:\n" +" for row in reader:\n" +" print(row)\n" +" except csv.Error as e:\n" +" sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e))" +msgstr "" + +#: library/csv.rst:614 msgid "" "And while the module doesn't directly support parsing strings, it can easily " "be done::" msgstr "" #: library/csv.rst:617 +msgid "" +"import csv\n" +"for row in csv.reader(['one,two,three']):\n" +" print(row)" +msgstr "" + +#: library/csv.rst:623 msgid "Footnotes" msgstr "" -#: library/csv.rst:618 +#: library/csv.rst:624 msgid "" "If ``newline=''`` is not specified, newlines embedded inside quoted fields " "will not be interpreted correctly, and on platforms that use ``\\r\\n`` " diff --git a/library/ctypes.po b/library/ctypes.po index c0e881f63..8a16f99e3 100644 --- a/library/ctypes.po +++ b/library/ctypes.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -80,8 +80,19 @@ msgstr "" #: library/ctypes.rst:53 msgid "" "Here are some examples for Windows. Note that ``msvcrt`` is the MS standard " -"C library containing most standard C functions, and uses the cdecl calling " -"convention::" +"C library containing most standard C functions, and uses the ``cdecl`` " +"calling convention::" +msgstr "" + +#: library/ctypes.rst:57 +msgid "" +">>> from ctypes import *\n" +">>> print(windll.kernel32) \n" +"\n" +">>> print(cdll.msvcrt) \n" +"\n" +">>> libc = cdll.msvcrt \n" +">>>" msgstr "" #: library/ctypes.rst:65 @@ -105,6 +116,16 @@ msgid "" "CDLL by calling the constructor::" msgstr "" +#: library/ctypes.rst:79 +msgid "" +">>> cdll.LoadLibrary(\"libc.so.6\") \n" +"\n" +">>> libc = CDLL(\"libc.so.6\") \n" +">>> libc \n" +"\n" +">>>" +msgstr "" + #: library/ctypes.rst:92 msgid "Accessing functions from loaded dlls" msgstr "" @@ -113,6 +134,21 @@ msgstr "" msgid "Functions are accessed as attributes of dll objects::" msgstr "" +#: library/ctypes.rst:96 +msgid "" +">>> libc.printf\n" +"<_FuncPtr object at 0x...>\n" +">>> print(windll.kernel32.GetModuleHandleA) \n" +"<_FuncPtr object at 0x...>\n" +">>> print(windll.kernel32.MyOwnFunction) \n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" File \"ctypes.py\", line 239, in __getattr__\n" +" func = _StdcallFuncPtr(name, self)\n" +"AttributeError: function 'MyOwnFunction' not found\n" +">>>" +msgstr "" + #: library/ctypes.rst:108 msgid "" "Note that win32 system dlls like ``kernel32`` and ``user32`` often export " @@ -124,6 +160,14 @@ msgid "" "``GetModuleHandle`` depending on whether UNICODE is defined or not::" msgstr "" +#: library/ctypes.rst:116 +msgid "" +"/* ANSI version */\n" +"HMODULE GetModuleHandleA(LPCSTR lpModuleName);\n" +"/* UNICODE version */\n" +"HMODULE GetModuleHandleW(LPCWSTR lpModuleName);" +msgstr "" + #: library/ctypes.rst:121 msgid "" "*windll* does not try to select one of them by magic, you must access the " @@ -138,6 +182,13 @@ msgid "" "`getattr` to retrieve the function::" msgstr "" +#: library/ctypes.rst:129 +msgid "" +">>> getattr(cdll.msvcrt, \"??2@YAPAXI@Z\") \n" +"<_FuncPtr object at 0x...>\n" +">>>" +msgstr "" + #: library/ctypes.rst:133 msgid "" "On Windows, some dlls export functions not by name but by ordinal. These " @@ -145,6 +196,19 @@ msgid "" "number::" msgstr "" +#: library/ctypes.rst:136 +msgid "" +">>> cdll.kernel32[1] \n" +"<_FuncPtr object at 0x...>\n" +">>> cdll.kernel32[0] \n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" File \"ctypes.py\", line 310, in __getitem__\n" +" func = _StdcallFuncPtr(name, self)\n" +"AttributeError: function ordinal 0 not found\n" +">>>" +msgstr "" + #: library/ctypes.rst:150 msgid "Calling functions" msgstr "" @@ -156,6 +220,12 @@ msgid "" "random integer::" msgstr "" +#: library/ctypes.rst:155 +msgid "" +">>> print(libc.rand()) \n" +"1804289383" +msgstr "" + #: library/ctypes.rst:158 msgid "" "On Windows, you can call the ``GetModuleHandleA()`` function, which returns " @@ -163,12 +233,36 @@ msgid "" "``NULL`` pointer)::" msgstr "" +#: library/ctypes.rst:161 +msgid "" +">>> print(hex(windll.kernel32.GetModuleHandleA(None))) \n" +"0x1d000000\n" +">>>" +msgstr "" + #: library/ctypes.rst:165 msgid "" ":exc:`ValueError` is raised when you call an ``stdcall`` function with the " "``cdecl`` calling convention, or vice versa::" msgstr "" +#: library/ctypes.rst:168 +msgid "" +">>> cdll.kernel32.GetModuleHandleA(None) \n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ValueError: Procedure probably called with not enough arguments (4 bytes " +"missing)\n" +">>>\n" +"\n" +">>> windll.msvcrt.printf(b\"spam\") \n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ValueError: Procedure probably called with too many arguments (4 bytes in " +"excess)\n" +">>>" +msgstr "" + #: library/ctypes.rst:180 msgid "" "To find out the correct calling convention you have to look into the C " @@ -182,6 +276,15 @@ msgid "" "with invalid argument values::" msgstr "" +#: library/ctypes.rst:187 +msgid "" +">>> windll.kernel32.GetModuleHandleA(32) \n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"OSError: exception: access violation reading 0x00000020\n" +">>>" +msgstr "" + #: library/ctypes.rst:193 msgid "" "There are, however, enough ways to crash Python with :mod:`ctypes`, so you " @@ -207,7 +310,7 @@ msgid "" "learn more about :mod:`ctypes` data types." msgstr "" -#: library/ctypes.rst:2198 +#: library/ctypes.rst:2208 msgid "Fundamental data types" msgstr "" @@ -443,11 +546,35 @@ msgid "" "of the correct type and value::" msgstr "" +#: library/ctypes.rst:272 +msgid "" +">>> c_int()\n" +"c_long(0)\n" +">>> c_wchar_p(\"Hello, World\")\n" +"c_wchar_p(140018365411392)\n" +">>> c_ushort(-3)\n" +"c_ushort(65533)\n" +">>>" +msgstr "" + #: library/ctypes.rst:280 msgid "" "Since these types are mutable, their value can also be changed afterwards::" msgstr "" +#: library/ctypes.rst:282 +msgid "" +">>> i = c_int(42)\n" +">>> print(i)\n" +"c_long(42)\n" +">>> print(i.value)\n" +"42\n" +">>> i.value = -99\n" +">>> print(i.value)\n" +"-99\n" +">>>" +msgstr "" + #: library/ctypes.rst:292 msgid "" "Assigning a new value to instances of the pointer types :class:`c_char_p`, :" @@ -456,6 +583,24 @@ msgid "" "Python bytes objects are immutable)::" msgstr "" +#: library/ctypes.rst:297 +msgid "" +">>> s = \"Hello, World\"\n" +">>> c_s = c_wchar_p(s)\n" +">>> print(c_s)\n" +"c_wchar_p(139966785747344)\n" +">>> print(c_s.value)\n" +"Hello World\n" +">>> c_s.value = \"Hi, there\"\n" +">>> print(c_s) # the memory location has changed\n" +"c_wchar_p(139966783348904)\n" +">>> print(c_s.value)\n" +"Hi, there\n" +">>> print(s) # first object is unchanged\n" +"Hello, World\n" +">>>" +msgstr "" + #: library/ctypes.rst:312 msgid "" "You should be careful, however, not to pass them to functions expecting " @@ -466,6 +611,28 @@ msgid "" "``value`` property::" msgstr "" +#: library/ctypes.rst:319 +msgid "" +">>> from ctypes import *\n" +">>> p = create_string_buffer(3) # create a 3 byte buffer, " +"initialized to NUL bytes\n" +">>> print(sizeof(p), repr(p.raw))\n" +"3 b'\\x00\\x00\\x00'\n" +">>> p = create_string_buffer(b\"Hello\") # create a buffer containing a " +"NUL terminated string\n" +">>> print(sizeof(p), repr(p.raw))\n" +"6 b'Hello\\x00'\n" +">>> print(repr(p.value))\n" +"b'Hello'\n" +">>> p = create_string_buffer(b\"Hello\", 10) # create a 10 byte buffer\n" +">>> print(sizeof(p), repr(p.raw))\n" +"10 b'Hello\\x00\\x00\\x00\\x00\\x00'\n" +">>> p.value = b\"Hi\"\n" +">>> print(sizeof(p), repr(p.raw))\n" +"10 b'Hi\\x00lo\\x00\\x00\\x00\\x00\\x00'\n" +">>>" +msgstr "" + #: library/ctypes.rst:336 msgid "" "The :func:`create_string_buffer` function replaces the old :func:`!c_buffer` " @@ -485,6 +652,25 @@ msgid "" "from within *IDLE* or *PythonWin*::" msgstr "" +#: library/ctypes.rst:351 +msgid "" +">>> printf = libc.printf\n" +">>> printf(b\"Hello, %s\\n\", b\"World!\")\n" +"Hello, World!\n" +"14\n" +">>> printf(b\"Hello, %S\\n\", \"World!\")\n" +"Hello, World!\n" +"14\n" +">>> printf(b\"%d bottles of beer\\n\", 42)\n" +"42 bottles of beer\n" +"19\n" +">>> printf(b\"%f bottles of beer\\n\", 42.5)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ArgumentError: argument 2: TypeError: Don't know how to convert parameter 2\n" +">>>" +msgstr "" + #: library/ctypes.rst:367 msgid "" "As has been mentioned before, all Python types except integers, strings, and " @@ -492,6 +678,14 @@ msgid "" "so that they can be converted to the required C data type::" msgstr "" +#: library/ctypes.rst:371 +msgid "" +">>> printf(b\"An int %d, a double %f\\n\", 1234, c_double(3.14))\n" +"An int 1234, a double 3.140000\n" +"31\n" +">>>" +msgstr "" + #: library/ctypes.rst:379 msgid "Calling variadic functions" msgstr "" @@ -507,14 +701,18 @@ msgstr "" #: library/ctypes.rst:386 msgid "" -"On those platforms it is required to specify the :attr:`~_FuncPtr.argtypes` " +"On those platforms it is required to specify the :attr:`~_CFuncPtr.argtypes` " "attribute for the regular, non-variadic, function arguments:" msgstr "" +#: library/ctypes.rst:389 +msgid "libc.printf.argtypes = [ctypes.c_char_p]" +msgstr "" + #: library/ctypes.rst:393 msgid "" "Because specifying the attribute does not inhibit portability it is advised " -"to always specify :attr:`~_FuncPtr.argtypes` for all variadic functions." +"to always specify :attr:`~_CFuncPtr.argtypes` for all variadic functions." msgstr "" #: library/ctypes.rst:400 @@ -530,6 +728,19 @@ msgid "" "or an object with an :attr:`!_as_parameter_` attribute::" msgstr "" +#: library/ctypes.rst:408 +msgid "" +">>> class Bottles:\n" +"... def __init__(self, number):\n" +"... self._as_parameter_ = number\n" +"...\n" +">>> bottles = Bottles(42)\n" +">>> printf(b\"%d bottles of beer\\n\", bottles)\n" +"42 bottles of beer\n" +"19\n" +">>>" +msgstr "" + #: library/ctypes.rst:418 msgid "" "If you don't want to store the instance's data in the :attr:`!" @@ -544,18 +755,27 @@ msgstr "" #: library/ctypes.rst:428 msgid "" "It is possible to specify the required argument types of functions exported " -"from DLLs by setting the :attr:`~_FuncPtr.argtypes` attribute." +"from DLLs by setting the :attr:`~_CFuncPtr.argtypes` attribute." msgstr "" #: library/ctypes.rst:431 msgid "" -":attr:`~_FuncPtr.argtypes` must be a sequence of C data types (the :func:`!" +":attr:`~_CFuncPtr.argtypes` must be a sequence of C data types (the :func:`!" "printf` function is probably not a good example here, because it takes a " "variable number and different types of parameters depending on the format " "string, on the other hand this is quite handy to experiment with this " "feature)::" msgstr "" +#: library/ctypes.rst:436 +msgid "" +">>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]\n" +">>> printf(b\"String '%s', Int %d, Double %f\\n\", b\"Hi\", 10, 2.2)\n" +"String 'Hi', Int 10, Double 2.200000\n" +"37\n" +">>>" +msgstr "" + #: library/ctypes.rst:442 msgid "" "Specifying a format protects against incompatible argument types (just as a " @@ -563,11 +783,23 @@ msgid "" "types::" msgstr "" +#: library/ctypes.rst:445 +msgid "" +">>> printf(b\"%d %d %d\", 1, 2, 3)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ArgumentError: argument 2: TypeError: wrong type\n" +">>> printf(b\"%s %d %f\\n\", b\"X\", 2, 3)\n" +"X 2 3.000000\n" +"13\n" +">>>" +msgstr "" + #: library/ctypes.rst:454 msgid "" "If you have defined your own classes which you pass to function calls, you " "have to implement a :meth:`~_CData.from_param` class method for them to be " -"able to use them in the :attr:`~_FuncPtr.argtypes` sequence. The :meth:" +"able to use them in the :attr:`~_CFuncPtr.argtypes` sequence. The :meth:" "`~_CData.from_param` class method receives the Python object passed to the " "function call, it should do a typecheck or whatever is needed to make sure " "this object is acceptable, and then return the object itself, its :attr:`!" @@ -584,7 +816,7 @@ msgstr "" #: library/ctypes.rst:478 msgid "" "By default functions are assumed to return the C :c:expr:`int` type. Other " -"return types can be specified by setting the :attr:`~_FuncPtr.restype` " +"return types can be specified by setting the :attr:`~_CFuncPtr.restype` " "attribute of the function object." msgstr "" @@ -595,8 +827,16 @@ msgid "" "expr:`int`, you should specify the :attr:`!restype` attribute::" msgstr "" +#: library/ctypes.rst:486 +msgid ">>> libc.time.restype = c_time_t" +msgstr "" + #: library/ctypes.rst:488 -msgid "The argument types can be specified using :attr:`~_FuncPtr.argtypes`::" +msgid "The argument types can be specified using :attr:`~_CFuncPtr.argtypes`::" +msgstr "" + +#: library/ctypes.rst:490 +msgid ">>> libc.time.argtypes = (POINTER(c_time_t),)" msgstr "" #: library/ctypes.rst:492 @@ -605,27 +845,83 @@ msgid "" "``None``::" msgstr "" +#: library/ctypes.rst:494 +msgid "" +">>> print(libc.time(None)) \n" +"1150640792" +msgstr "" + #: library/ctypes.rst:497 msgid "" "Here is a more advanced example, it uses the :func:`!strchr` function, which " "expects a string pointer and a char, and returns a pointer to a string::" msgstr "" +#: library/ctypes.rst:500 +msgid "" +">>> strchr = libc.strchr\n" +">>> strchr(b\"abcdef\", ord(\"d\")) \n" +"8059983\n" +">>> strchr.restype = c_char_p # c_char_p is a pointer to a string\n" +">>> strchr(b\"abcdef\", ord(\"d\"))\n" +"b'def'\n" +">>> print(strchr(b\"abcdef\", ord(\"x\")))\n" +"None\n" +">>>" +msgstr "" + #: library/ctypes.rst:510 msgid "" "If you want to avoid the :func:`ord(\"x\") ` calls above, you can set " -"the :attr:`~_FuncPtr.argtypes` attribute, and the second argument will be " +"the :attr:`~_CFuncPtr.argtypes` attribute, and the second argument will be " "converted from a single character Python bytes object into a C char:" msgstr "" +#: library/ctypes.rst:514 +msgid "" +">>> strchr.restype = c_char_p\n" +">>> strchr.argtypes = [c_char_p, c_char]\n" +">>> strchr(b\"abcdef\", b\"d\")\n" +"b'def'\n" +">>> strchr(b\"abcdef\", b\"def\")\n" +"Traceback (most recent call last):\n" +"ctypes.ArgumentError: argument 2: TypeError: one character bytes, bytearray " +"or integer expected\n" +">>> print(strchr(b\"abcdef\", b\"x\"))\n" +"None\n" +">>> strchr(b\"abcdef\", b\"d\")\n" +"b'def'\n" +">>>" +msgstr "" + #: library/ctypes.rst:529 msgid "" "You can also use a callable Python object (a function or a class for " -"example) as the :attr:`~_FuncPtr.restype` attribute, if the foreign function " -"returns an integer. The callable will be called with the *integer* the C " -"function returns, and the result of this call will be used as the result of " -"your function call. This is useful to check for error return values and " -"automatically raise an exception::" +"example) as the :attr:`~_CFuncPtr.restype` attribute, if the foreign " +"function returns an integer. The callable will be called with the *integer* " +"the C function returns, and the result of this call will be used as the " +"result of your function call. This is useful to check for error return " +"values and automatically raise an exception::" +msgstr "" + +#: library/ctypes.rst:535 +msgid "" +">>> GetModuleHandle = windll.kernel32.GetModuleHandleA \n" +">>> def ValidHandle(value):\n" +"... if value == 0:\n" +"... raise WinError()\n" +"... return value\n" +"...\n" +">>>\n" +">>> GetModuleHandle.restype = ValidHandle \n" +">>> GetModuleHandle(None) \n" +"486539264\n" +">>> GetModuleHandle(\"something silly\") \n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" File \"\", line 3, in ValidHandle\n" +"OSError: [Errno 126] The specified module could not be found.\n" +">>>" msgstr "" #: library/ctypes.rst:552 @@ -639,7 +935,7 @@ msgstr "" #: library/ctypes.rst:557 msgid "" "Please note that a much more powerful error checking mechanism is available " -"through the :attr:`~_FuncPtr.errcheck` attribute; see the reference manual " +"through the :attr:`~_CFuncPtr.errcheck` attribute; see the reference manual " "for details." msgstr "" @@ -664,6 +960,21 @@ msgid "" "you don't need the pointer object in Python itself::" msgstr "" +#: library/ctypes.rst:577 +msgid "" +">>> i = c_int()\n" +">>> f = c_float()\n" +">>> s = create_string_buffer(b'\\000' * 32)\n" +">>> print(i.value, f.value, repr(s.value))\n" +"0 0.0 b''\n" +">>> libc.sscanf(b\"1 3.14 Hello\", b\"%d %f %s\",\n" +"... byref(i), byref(f), s)\n" +"3\n" +">>> print(i.value, f.value, repr(s.value))\n" +"1 3.1400001049 b'Hello'\n" +">>>" +msgstr "" + #: library/ctypes.rst:593 msgid "Structures and unions" msgstr "" @@ -690,6 +1001,26 @@ msgid "" "constructor::" msgstr "" +#: library/ctypes.rst:606 +msgid "" +">>> from ctypes import *\n" +">>> class POINT(Structure):\n" +"... _fields_ = [(\"x\", c_int),\n" +"... (\"y\", c_int)]\n" +"...\n" +">>> point = POINT(10, 20)\n" +">>> print(point.x, point.y)\n" +"10 20\n" +">>> point = POINT(y=5)\n" +">>> print(point.x, point.y)\n" +"0 5\n" +">>> POINT(1, 2, 3)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: too many initializers\n" +">>>" +msgstr "" + #: library/ctypes.rst:623 msgid "" "You can, however, build much more complicated structures. A structure can " @@ -702,18 +1033,47 @@ msgid "" "*lowerright*::" msgstr "" +#: library/ctypes.rst:629 +msgid "" +">>> class RECT(Structure):\n" +"... _fields_ = [(\"upperleft\", POINT),\n" +"... (\"lowerright\", POINT)]\n" +"...\n" +">>> rc = RECT(point)\n" +">>> print(rc.upperleft.x, rc.upperleft.y)\n" +"0 5\n" +">>> print(rc.lowerright.x, rc.lowerright.y)\n" +"0 0\n" +">>>" +msgstr "" + #: library/ctypes.rst:640 msgid "" "Nested structures can also be initialized in the constructor in several " "ways::" msgstr "" +#: library/ctypes.rst:642 +msgid "" +">>> r = RECT(POINT(1, 2), POINT(3, 4))\n" +">>> r = RECT((1, 2), (3, 4))" +msgstr "" + #: library/ctypes.rst:645 msgid "" "Field :term:`descriptor`\\s can be retrieved from the *class*, they are " "useful for debugging because they can provide useful information::" msgstr "" +#: library/ctypes.rst:648 +msgid "" +">>> print(POINT.x)\n" +"\n" +">>> print(POINT.y)\n" +"\n" +">>>" +msgstr "" + #: library/ctypes.rst:659 msgid "" ":mod:`ctypes` does not support passing unions or structures with bit-fields " @@ -755,6 +1115,19 @@ msgid "" "the third item in the :attr:`~Structure._fields_` tuples::" msgstr "" +#: library/ctypes.rst:689 +msgid "" +">>> class Int(Structure):\n" +"... _fields_ = [(\"first_16\", c_int, 16),\n" +"... (\"second_16\", c_int, 16)]\n" +"...\n" +">>> print(Int.first_16)\n" +"\n" +">>> print(Int.second_16)\n" +"\n" +">>>" +msgstr "" + #: library/ctypes.rst:703 msgid "Arrays" msgstr "" @@ -771,16 +1144,43 @@ msgid "" "a positive integer::" msgstr "" +#: library/ctypes.rst:710 +msgid "TenPointsArrayType = POINT * 10" +msgstr "" + #: library/ctypes.rst:712 msgid "" "Here is an example of a somewhat artificial data type, a structure " "containing 4 POINTs among other stuff::" msgstr "" +#: library/ctypes.rst:715 +msgid "" +">>> from ctypes import *\n" +">>> class POINT(Structure):\n" +"... _fields_ = (\"x\", c_int), (\"y\", c_int)\n" +"...\n" +">>> class MyStruct(Structure):\n" +"... _fields_ = [(\"a\", c_int),\n" +"... (\"b\", c_float),\n" +"... (\"point_array\", POINT * 4)]\n" +">>>\n" +">>> print(len(MyStruct().point_array))\n" +"4\n" +">>>" +msgstr "" + #: library/ctypes.rst:728 msgid "Instances are created in the usual way, by calling the class::" msgstr "" +#: library/ctypes.rst:730 +msgid "" +"arr = TenPointsArrayType()\n" +"for pt in arr:\n" +" print(pt.x, pt.y)" +msgstr "" + #: library/ctypes.rst:734 msgid "" "The above code print a series of ``0 0`` lines, because the array contents " @@ -791,6 +1191,19 @@ msgstr "" msgid "Initializers of the correct type can also be specified::" msgstr "" +#: library/ctypes.rst:739 +msgid "" +">>> from ctypes import *\n" +">>> TenIntegers = c_int * 10\n" +">>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n" +">>> print(ii)\n" +"\n" +">>> for i in ii: print(i, end=\" \")\n" +"...\n" +"1 2 3 4 5 6 7 8 9 10\n" +">>>" +msgstr "" + #: library/ctypes.rst:753 msgid "Pointers" msgstr "" @@ -801,18 +1214,42 @@ msgid "" "mod:`ctypes` type::" msgstr "" +#: library/ctypes.rst:758 +msgid "" +">>> from ctypes import *\n" +">>> i = c_int(42)\n" +">>> pi = pointer(i)\n" +">>>" +msgstr "" + #: library/ctypes.rst:763 msgid "" "Pointer instances have a :attr:`~_Pointer.contents` attribute which returns " "the object to which the pointer points, the ``i`` object above::" msgstr "" +#: library/ctypes.rst:766 +msgid "" +">>> pi.contents\n" +"c_long(42)\n" +">>>" +msgstr "" + #: library/ctypes.rst:770 msgid "" "Note that :mod:`ctypes` does not have OOR (original object return), it " "constructs a new, equivalent object each time you retrieve an attribute::" msgstr "" +#: library/ctypes.rst:773 +msgid "" +">>> pi.contents is i\n" +"False\n" +">>> pi.contents is pi.contents\n" +"False\n" +">>>" +msgstr "" + #: library/ctypes.rst:779 msgid "" "Assigning another :class:`c_int` instance to the pointer's contents " @@ -820,14 +1257,40 @@ msgid "" "is stored::" msgstr "" +#: library/ctypes.rst:782 +msgid "" +">>> i = c_int(99)\n" +">>> pi.contents = i\n" +">>> pi.contents\n" +"c_long(99)\n" +">>>" +msgstr "" + #: library/ctypes.rst:791 msgid "Pointer instances can also be indexed with integers::" msgstr "" +#: library/ctypes.rst:793 +msgid "" +">>> pi[0]\n" +"99\n" +">>>" +msgstr "" + #: library/ctypes.rst:797 msgid "Assigning to an integer index changes the pointed to value::" msgstr "" +#: library/ctypes.rst:799 +msgid "" +">>> print(i)\n" +"c_long(99)\n" +">>> pi[0] = 22\n" +">>> print(i)\n" +"c_long(22)\n" +">>>" +msgstr "" + #: library/ctypes.rst:806 msgid "" "It is also possible to use indexes different from 0, but you must know what " @@ -845,18 +1308,55 @@ msgid "" "returns a new type::" msgstr "" +#: library/ctypes.rst:817 +msgid "" +">>> PI = POINTER(c_int)\n" +">>> PI\n" +"\n" +">>> PI(42)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: expected c_long instead of int\n" +">>> PI(c_int(42))\n" +"\n" +">>>" +msgstr "" + #: library/ctypes.rst:828 msgid "" "Calling the pointer type without an argument creates a ``NULL`` pointer. " "``NULL`` pointers have a ``False`` boolean value::" msgstr "" +#: library/ctypes.rst:831 +msgid "" +">>> null_ptr = POINTER(c_int)()\n" +">>> print(bool(null_ptr))\n" +"False\n" +">>>" +msgstr "" + #: library/ctypes.rst:836 msgid "" ":mod:`ctypes` checks for ``NULL`` when dereferencing pointers (but " "dereferencing invalid non-\\ ``NULL`` pointers would crash Python)::" msgstr "" +#: library/ctypes.rst:839 +msgid "" +">>> null_ptr[0]\n" +"Traceback (most recent call last):\n" +" ....\n" +"ValueError: NULL pointer access\n" +">>>\n" +"\n" +">>> null_ptr[0] = 1234\n" +"Traceback (most recent call last):\n" +" ....\n" +"ValueError: NULL pointer access\n" +">>>" +msgstr "" + #: library/ctypes.rst:855 msgid "Type conversions" msgstr "" @@ -864,7 +1364,7 @@ msgstr "" #: library/ctypes.rst:857 msgid "" "Usually, ctypes does strict type checking. This means, if you have " -"``POINTER(c_int)`` in the :attr:`~_FuncPtr.argtypes` list of a function or " +"``POINTER(c_int)`` in the :attr:`~_CFuncPtr.argtypes` list of a function or " "as the type of a member field in a structure definition, only instances of " "exactly the same type are accepted. There are some exceptions to this rule, " "where ctypes accepts other objects. For example, you can pass compatible " @@ -872,10 +1372,27 @@ msgid "" "ctypes accepts an array of c_int::" msgstr "" +#: library/ctypes.rst:864 +msgid "" +">>> class Bar(Structure):\n" +"... _fields_ = [(\"count\", c_int), (\"values\", POINTER(c_int))]\n" +"...\n" +">>> bar = Bar()\n" +">>> bar.values = (c_int * 3)(1, 2, 3)\n" +">>> bar.count = 3\n" +">>> for i in range(bar.count):\n" +"... print(bar.values[i])\n" +"...\n" +"1\n" +"2\n" +"3\n" +">>>" +msgstr "" + #: library/ctypes.rst:878 msgid "" "In addition, if a function argument is explicitly declared to be a pointer " -"type (such as ``POINTER(c_int)``) in :attr:`~_FuncPtr.argtypes`, an object " +"type (such as ``POINTER(c_int)``) in :attr:`~_CFuncPtr.argtypes`, an object " "of the pointed type (``c_int`` in this case) can be passed to the function. " "ctypes will apply the required :func:`byref` conversion in this case " "automatically." @@ -885,6 +1402,12 @@ msgstr "" msgid "To set a POINTER type field to ``NULL``, you can assign ``None``::" msgstr "" +#: library/ctypes.rst:885 +msgid "" +">>> bar.values = None\n" +">>>" +msgstr "" + #: library/ctypes.rst:890 msgid "" "Sometimes you have instances of incompatible types. In C, you can cast one " @@ -894,6 +1417,16 @@ msgid "" "``values`` field, but not instances of other types::" msgstr "" +#: library/ctypes.rst:896 +msgid "" +">>> bar.values = (c_byte * 4)()\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long " +"instance\n" +">>>" +msgstr "" + #: library/ctypes.rst:902 msgid "For these cases, the :func:`cast` function is handy." msgstr "" @@ -907,12 +1440,29 @@ msgid "" "references the same memory block as the first argument::" msgstr "" +#: library/ctypes.rst:910 +msgid "" +">>> a = (c_byte * 4)()\n" +">>> cast(a, POINTER(c_int))\n" +"\n" +">>>" +msgstr "" + #: library/ctypes.rst:915 msgid "" "So, :func:`cast` can be used to assign to the ``values`` field of ``Bar`` " "the structure::" msgstr "" +#: library/ctypes.rst:918 +msgid "" +">>> bar = Bar()\n" +">>> bar.values = cast((c_byte * 4)(), POINTER(c_int))\n" +">>> print(bar.values[0])\n" +"0\n" +">>>" +msgstr "" + #: library/ctypes.rst:928 msgid "Incomplete Types" msgstr "" @@ -924,12 +1474,35 @@ msgid "" "defined later::" msgstr "" +#: library/ctypes.rst:934 +msgid "" +"struct cell; /* forward declaration */\n" +"\n" +"struct cell {\n" +" char *name;\n" +" struct cell *next;\n" +"};" +msgstr "" + #: library/ctypes.rst:941 msgid "" "The straightforward translation into ctypes code would be this, but it does " "not work::" msgstr "" +#: library/ctypes.rst:944 +msgid "" +">>> class cell(Structure):\n" +"... _fields_ = [(\"name\", c_char_p),\n" +"... (\"next\", POINTER(cell))]\n" +"...\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" File \"\", line 2, in cell\n" +"NameError: name 'cell' is not defined\n" +">>>" +msgstr "" + #: library/ctypes.rst:954 msgid "" "because the new ``class cell`` is not available in the class statement " @@ -937,12 +1510,40 @@ msgid "" "`~Structure._fields_` attribute later, after the class statement::" msgstr "" +#: library/ctypes.rst:958 +msgid "" +">>> from ctypes import *\n" +">>> class cell(Structure):\n" +"... pass\n" +"...\n" +">>> cell._fields_ = [(\"name\", c_char_p),\n" +"... (\"next\", POINTER(cell))]\n" +">>>" +msgstr "" + #: library/ctypes.rst:966 msgid "" "Let's try it. We create two instances of ``cell``, and let them point to " "each other, and finally follow the pointer chain a few times::" msgstr "" +#: library/ctypes.rst:969 +msgid "" +">>> c1 = cell()\n" +">>> c1.name = b\"foo\"\n" +">>> c2 = cell()\n" +">>> c2.name = b\"bar\"\n" +">>> c1.next = pointer(c2)\n" +">>> c2.next = pointer(c1)\n" +">>> p = c1\n" +">>> for i in range(8):\n" +"... print(p.name, end=\" \")\n" +"... p = p.next[0]\n" +"...\n" +"foo bar foo bar foo bar foo bar\n" +">>>" +msgstr "" + #: library/ctypes.rst:987 msgid "Callback functions" msgstr "" @@ -982,6 +1583,15 @@ msgid "" "function. :c:func:`!qsort` will be used to sort an array of integers::" msgstr "" +#: library/ctypes.rst:1009 +msgid "" +">>> IntArray5 = c_int * 5\n" +">>> ia = IntArray5(5, 1, 7, 33, 99)\n" +">>> qsort = libc.qsort\n" +">>> qsort.restype = None\n" +">>>" +msgstr "" + #: library/ctypes.rst:1015 msgid "" ":func:`!qsort` must be called with a pointer to the data to sort, the number " @@ -998,30 +1608,97 @@ msgid "" "integer. First we create the ``type`` for the callback function::" msgstr "" +#: library/ctypes.rst:1024 +msgid "" +">>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))\n" +">>>" +msgstr "" + #: library/ctypes.rst:1027 msgid "" "To get started, here is a simple callback that shows the values it gets " "passed::" msgstr "" +#: library/ctypes.rst:1030 +msgid "" +">>> def py_cmp_func(a, b):\n" +"... print(\"py_cmp_func\", a[0], b[0])\n" +"... return 0\n" +"...\n" +">>> cmp_func = CMPFUNC(py_cmp_func)\n" +">>>" +msgstr "" + #: library/ctypes.rst:1037 msgid "The result::" msgstr "" +#: library/ctypes.rst:1039 +msgid "" +">>> qsort(ia, len(ia), sizeof(c_int), cmp_func) \n" +"py_cmp_func 5 1\n" +"py_cmp_func 33 99\n" +"py_cmp_func 7 33\n" +"py_cmp_func 5 7\n" +"py_cmp_func 1 7\n" +">>>" +msgstr "" + #: library/ctypes.rst:1047 msgid "Now we can actually compare the two items and return a useful result::" msgstr "" +#: library/ctypes.rst:1049 +msgid "" +">>> def py_cmp_func(a, b):\n" +"... print(\"py_cmp_func\", a[0], b[0])\n" +"... return a[0] - b[0]\n" +"...\n" +">>>\n" +">>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) \n" +"py_cmp_func 5 1\n" +"py_cmp_func 33 99\n" +"py_cmp_func 7 33\n" +"py_cmp_func 1 7\n" +"py_cmp_func 5 7\n" +">>>" +msgstr "" + #: library/ctypes.rst:1062 msgid "As we can easily check, our array is sorted now::" msgstr "" +#: library/ctypes.rst:1064 +msgid "" +">>> for i in ia: print(i, end=\" \")\n" +"...\n" +"1 5 7 33 99\n" +">>>" +msgstr "" + #: library/ctypes.rst:1069 msgid "" "The function factories can be used as decorator factories, so we may as well " "write::" msgstr "" +#: library/ctypes.rst:1072 +msgid "" +">>> @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))\n" +"... def py_cmp_func(a, b):\n" +"... print(\"py_cmp_func\", a[0], b[0])\n" +"... return a[0] - b[0]\n" +"...\n" +">>> qsort(ia, len(ia), sizeof(c_int), py_cmp_func)\n" +"py_cmp_func 5 1\n" +"py_cmp_func 33 99\n" +"py_cmp_func 7 33\n" +"py_cmp_func 1 7\n" +"py_cmp_func 5 7\n" +">>>" +msgstr "" + #: library/ctypes.rst:1087 msgid "" "Make sure you keep references to :func:`CFUNCTYPE` objects as long as they " @@ -1057,6 +1734,13 @@ msgid "" "to the Python C api::" msgstr "" +#: library/ctypes.rst:1111 +msgid "" +">>> version = ctypes.c_int.in_dll(ctypes.pythonapi, \"Py_Version\")\n" +">>> print(hex(version.value))\n" +"0x30c00a0" +msgstr "" + #: library/ctypes.rst:1115 msgid "" "An extended example which also demonstrates the use of pointers accesses " @@ -1082,12 +1766,33 @@ msgid "" "example size, we show only how this table can be read with :mod:`ctypes`::" msgstr "" +#: library/ctypes.rst:1128 +msgid "" +">>> from ctypes import *\n" +">>>\n" +">>> class struct_frozen(Structure):\n" +"... _fields_ = [(\"name\", c_char_p),\n" +"... (\"code\", POINTER(c_ubyte)),\n" +"... (\"size\", c_int),\n" +"... (\"get_code\", POINTER(c_ubyte)), # Function pointer\n" +"... ]\n" +"...\n" +">>>" +msgstr "" + #: library/ctypes.rst:1139 msgid "" "We have defined the :c:struct:`_frozen` data type, so we can get the pointer " "to the table::" msgstr "" +#: library/ctypes.rst:1142 +msgid "" +">>> FrozenTable = POINTER(struct_frozen)\n" +">>> table = FrozenTable.in_dll(pythonapi, \"_PyImport_FrozenBootstrap\")\n" +">>>" +msgstr "" + #: library/ctypes.rst:1146 msgid "" "Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, " @@ -1097,6 +1802,19 @@ msgid "" "the loop when we hit the ``NULL`` entry::" msgstr "" +#: library/ctypes.rst:1152 +msgid "" +">>> for item in table:\n" +"... if item.name is None:\n" +"... break\n" +"... print(item.name.decode(\"ascii\"), item.size)\n" +"...\n" +"_frozen_importlib 31764\n" +"_frozen_importlib_external 41499\n" +"zipimport 12345\n" +">>>" +msgstr "" + #: library/ctypes.rst:1162 msgid "" "The fact that standard Python has a frozen module and a frozen package " @@ -1118,12 +1836,41 @@ msgstr "" msgid "Consider the following example::" msgstr "" +#: library/ctypes.rst:1177 +msgid "" +">>> from ctypes import *\n" +">>> class POINT(Structure):\n" +"... _fields_ = (\"x\", c_int), (\"y\", c_int)\n" +"...\n" +">>> class RECT(Structure):\n" +"... _fields_ = (\"a\", POINT), (\"b\", POINT)\n" +"...\n" +">>> p1 = POINT(1, 2)\n" +">>> p2 = POINT(3, 4)\n" +">>> rc = RECT(p1, p2)\n" +">>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)\n" +"1 2 3 4\n" +">>> # now swap the two points\n" +">>> rc.a, rc.b = rc.b, rc.a\n" +">>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)\n" +"3 4 3 4\n" +">>>" +msgstr "" + #: library/ctypes.rst:1195 msgid "" "Hm. We certainly expected the last statement to print ``3 4 1 2``. What " "happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::" msgstr "" +#: library/ctypes.rst:1198 +msgid "" +">>> temp0, temp1 = rc.b, rc.a\n" +">>> rc.a = temp0\n" +">>> rc.b = temp1\n" +">>>" +msgstr "" + #: library/ctypes.rst:1203 msgid "" "Note that ``temp0`` and ``temp1`` are objects still using the internal " @@ -1146,6 +1893,17 @@ msgid "" "this::" msgstr "" +#: library/ctypes.rst:1215 +msgid "" +">>> s = c_char_p()\n" +">>> s.value = b\"abc def ghi\"\n" +">>> s.value\n" +"b'abc def ghi'\n" +">>> s.value is s.value\n" +"False\n" +">>>" +msgstr "" + #: library/ctypes.rst:1225 msgid "" "Objects instantiated from :class:`c_char_p` can only have their value set to " @@ -1179,6 +1937,23 @@ msgid "" "objects type, a :exc:`ValueError` is raised if this is tried::" msgstr "" +#: library/ctypes.rst:1248 +msgid "" +">>> short_array = (c_short * 4)()\n" +">>> print(sizeof(short_array))\n" +"8\n" +">>> resize(short_array, 4)\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: minimum size is 8\n" +">>> resize(short_array, 32)\n" +">>> sizeof(short_array)\n" +"32\n" +">>> sizeof(type(short_array))\n" +"8\n" +">>>" +msgstr "" + #: library/ctypes.rst:1262 msgid "" "This is nice and fine, but how would one access the additional elements " @@ -1186,6 +1961,17 @@ msgid "" "we get errors accessing other elements::" msgstr "" +#: library/ctypes.rst:1266 +msgid "" +">>> short_array[:]\n" +"[0, 0, 0, 0]\n" +">>> short_array[7]\n" +"Traceback (most recent call last):\n" +" ...\n" +"IndexError: invalid index\n" +">>>" +msgstr "" + #: library/ctypes.rst:1274 msgid "" "Another way to use variable-sized data types with :mod:`ctypes` is to use " @@ -1230,7 +2016,7 @@ msgid "" "If no library can be found, returns ``None``." msgstr "" -#: library/ctypes.rst:1972 +#: library/ctypes.rst:1982 msgid "The exact functionality is system dependent." msgstr "" @@ -1252,6 +2038,18 @@ msgstr "" msgid "Here are some examples::" msgstr "" +#: library/ctypes.rst:1324 +msgid "" +">>> from ctypes.util import find_library\n" +">>> find_library(\"m\")\n" +"'libm.so.6'\n" +">>> find_library(\"c\")\n" +"'libc.so.6'\n" +">>> find_library(\"bz2\")\n" +"'libbz2.so.1.0'\n" +">>>" +msgstr "" + #: library/ctypes.rst:1333 msgid "" "On macOS, :func:`~ctypes.util.find_library` tries several predefined naming " @@ -1259,6 +2057,20 @@ msgid "" "successful::" msgstr "" +#: library/ctypes.rst:1336 +msgid "" +">>> from ctypes.util import find_library\n" +">>> find_library(\"c\")\n" +"'/usr/lib/libc.dylib'\n" +">>> find_library(\"m\")\n" +"'/usr/lib/libm.dylib'\n" +">>> find_library(\"bz2\")\n" +"'/usr/lib/libbz2.dylib'\n" +">>> find_library(\"AGL\")\n" +"'/System/Library/Frameworks/AGL.framework/AGL'\n" +">>>" +msgstr "" + #: library/ctypes.rst:1347 msgid "" "On Windows, :func:`~ctypes.util.find_library` searches along the system " @@ -1440,6 +2252,16 @@ msgid "" "other hand, accessing it through an index returns a new object each time::" msgstr "" +#: library/ctypes.rst:1502 +msgid "" +">>> from ctypes import CDLL\n" +">>> libc = CDLL(\"libc.so.6\") # On Linux\n" +">>> libc.time == libc.time\n" +"True\n" +">>> libc['time'] == libc['time']\n" +"False" +msgstr "" + #: library/ctypes.rst:1509 msgid "" "The following public attributes are available, their name starts with an " @@ -1516,12 +2338,6 @@ msgid "" "correct :attr:`!restype` attribute to use these functions." msgstr "" -#: library/ctypes.rst:1580 -msgid "" -"Loading a library through any of these objects raises an auditing event " -"ctypes.dlopen with string argument name, the name used to load the library." -msgstr "" - #: library/ctypes.rst:1582 msgid "" "Loading a library through any of these objects raises an :ref:`auditing " @@ -1529,13 +2345,6 @@ msgid "" "used to load the library." msgstr "" -#: library/ctypes.rst:1586 -msgid "" -"Accessing a function on a loaded library raises an auditing event ctypes." -"dlsym with arguments library (the library object) and name (the symbol's " -"name as a string or integer)." -msgstr "" - #: library/ctypes.rst:1588 msgid "" "Accessing a function on a loaded library raises an auditing event ``ctypes." @@ -1543,13 +2352,6 @@ msgid "" "symbol's name as a string or integer)." msgstr "" -#: library/ctypes.rst:1592 -msgid "" -"In cases when only the library handle is available rather than the object, " -"accessing a function raises an auditing event ctypes.dlsym/handle with " -"arguments handle (the raw library handle) and name." -msgstr "" - #: library/ctypes.rst:1594 msgid "" "In cases when only the library handle is available rather than the object, " @@ -1567,32 +2369,48 @@ msgid "" "attributes of loaded shared libraries. The function objects created in this " "way by default accept any number of arguments, accept any ctypes data " "instances as arguments, and return the default result type specified by the " -"library loader. They are instances of a private class:" +"library loader." +msgstr "" + +#: library/ctypes.rst:1608 +msgid "" +"They are instances of a private local class :class:`!_FuncPtr` (not exposed " +"in :mod:`!ctypes`) which inherits from the private :class:`_CFuncPtr` class:" +msgstr "" + +#: library/ctypes.rst:1611 +msgid "" +">>> import ctypes\n" +">>> lib = ctypes.CDLL(None)\n" +">>> issubclass(lib._FuncPtr, ctypes._CFuncPtr)\n" +"True\n" +">>> lib._FuncPtr is ctypes._CFuncPtr\n" +"False" msgstr "" -#: library/ctypes.rst:1612 +#: library/ctypes.rst:1622 msgid "Base class for C callable foreign functions." msgstr "" -#: library/ctypes.rst:1614 +#: library/ctypes.rst:1624 msgid "" "Instances of foreign functions are also C compatible data types; they " "represent C function pointers." msgstr "" -#: library/ctypes.rst:1617 +#: library/ctypes.rst:1627 msgid "" "This behavior can be customized by assigning to special attributes of the " "foreign function object." msgstr "" -#: library/ctypes.rst:1622 +#: library/ctypes.rst:1632 msgid "" "Assign a ctypes type to specify the result type of the foreign function. Use " "``None`` for :c:expr:`void`, a function not returning anything." msgstr "" -#: library/ctypes.rst:1625 +#: library/ctypes.rst:1635 msgid "" "It is possible to assign a callable Python object that is not a ctypes type, " "in this case the function is assumed to return a C :c:expr:`int`, and the " @@ -1602,7 +2420,7 @@ msgid "" "callable to the :attr:`errcheck` attribute." msgstr "" -#: library/ctypes.rst:1634 +#: library/ctypes.rst:1644 msgid "" "Assign a tuple of ctypes types to specify the argument types that the " "function accepts. Functions using the ``stdcall`` calling convention can " @@ -1611,7 +2429,7 @@ msgid "" "unspecified arguments as well." msgstr "" -#: library/ctypes.rst:1640 +#: library/ctypes.rst:1650 msgid "" "When a foreign function is called, each actual argument is passed to the :" "meth:`~_CData.from_param` class method of the items in the :attr:`argtypes` " @@ -1621,7 +2439,7 @@ msgid "" "object using ctypes conversion rules." msgstr "" -#: library/ctypes.rst:1647 +#: library/ctypes.rst:1657 msgid "" "New: It is now possible to put items in argtypes which are not ctypes types, " "but each item must have a :meth:`~_CData.from_param` method which returns a " @@ -1629,53 +2447,44 @@ msgid "" "defining adapters that can adapt custom objects as function parameters." msgstr "" -#: library/ctypes.rst:1654 +#: library/ctypes.rst:1664 msgid "" "Assign a Python function or another callable to this attribute. The callable " "will be called with three or more arguments:" msgstr "" -#: library/ctypes.rst:1661 +#: library/ctypes.rst:1671 msgid "" "*result* is what the foreign function returns, as specified by the :attr:`!" "restype` attribute." msgstr "" -#: library/ctypes.rst:1664 +#: library/ctypes.rst:1674 msgid "" "*func* is the foreign function object itself, this allows reusing the same " "callable object to check or post process the results of several functions." msgstr "" -#: library/ctypes.rst:1668 +#: library/ctypes.rst:1678 msgid "" "*arguments* is a tuple containing the parameters originally passed to the " "function call, this allows specializing the behavior on the arguments used." msgstr "" -#: library/ctypes.rst:1672 +#: library/ctypes.rst:1682 msgid "" "The object that this function returns will be returned from the foreign " "function call, but it can also check the result value and raise an exception " "if the foreign function call failed." msgstr "" -#: library/ctypes.rst:1679 +#: library/ctypes.rst:1689 msgid "" "This exception is raised when a foreign function call cannot convert one of " "the passed arguments." msgstr "" -#: library/ctypes.rst:1683 -msgid "" -"On Windows, when a foreign function call raises a system exception (for " -"example, due to an access violation), it will be captured and replaced with " -"a suitable Python exception. Further, an auditing event ctypes.set_exception " -"with argument code will be raised, allowing an audit hook to replace the " -"exception with its own." -msgstr "" - -#: library/ctypes.rst:1685 +#: library/ctypes.rst:1695 msgid "" "On Windows, when a foreign function call raises a system exception (for " "example, due to an access violation), it will be captured and replaced with " @@ -1684,24 +2493,18 @@ msgid "" "hook to replace the exception with its own." msgstr "" -#: library/ctypes.rst:1691 -msgid "" -"Some ways to invoke foreign function calls may raise an auditing event " -"ctypes.call_function with arguments function pointer and arguments." -msgstr "" - -#: library/ctypes.rst:1693 +#: library/ctypes.rst:1703 msgid "" "Some ways to invoke foreign function calls may raise an auditing event " "``ctypes.call_function`` with arguments ``function pointer`` and " "``arguments``." msgstr "" -#: library/ctypes.rst:1699 +#: library/ctypes.rst:1709 msgid "Function prototypes" msgstr "" -#: library/ctypes.rst:1701 +#: library/ctypes.rst:1711 msgid "" "Foreign functions can also be created by instantiating function prototypes. " "Function prototypes are similar to function prototypes in C; they describe a " @@ -1712,7 +2515,7 @@ msgid "" "``@wrapper`` syntax. See :ref:`ctypes-callback-functions` for examples." msgstr "" -#: library/ctypes.rst:1712 +#: library/ctypes.rst:1722 msgid "" "The returned function prototype creates functions that use the standard C " "calling convention. The function will release the GIL during the call. If " @@ -1721,37 +2524,37 @@ msgid "" "after the call; *use_last_error* does the same for the Windows error code." msgstr "" -#: library/ctypes.rst:1722 +#: library/ctypes.rst:1732 msgid "" "Windows only: The returned function prototype creates functions that use the " "``stdcall`` calling convention. The function will release the GIL during " "the call. *use_errno* and *use_last_error* have the same meaning as above." msgstr "" -#: library/ctypes.rst:1730 +#: library/ctypes.rst:1740 msgid "" "The returned function prototype creates functions that use the Python " "calling convention. The function will *not* release the GIL during the call." msgstr "" -#: library/ctypes.rst:1733 +#: library/ctypes.rst:1743 msgid "" "Function prototypes created by these factory functions can be instantiated " "in different ways, depending on the type and number of the parameters in the " "call:" msgstr "" -#: library/ctypes.rst:1740 +#: library/ctypes.rst:1750 msgid "" "Returns a foreign function at the specified address which must be an integer." msgstr "" -#: library/ctypes.rst:1747 +#: library/ctypes.rst:1757 msgid "" "Create a C callable function (a callback function) from a Python *callable*." msgstr "" -#: library/ctypes.rst:1754 +#: library/ctypes.rst:1764 msgid "" "Returns a foreign function exported by a shared library. *func_spec* must be " "a 2-tuple ``(name_or_ordinal, library)``. The first item is the name of the " @@ -1759,7 +2562,7 @@ msgid "" "small integer. The second item is the shared library instance." msgstr "" -#: library/ctypes.rst:1764 +#: library/ctypes.rst:1774 msgid "" "Returns a foreign function that will call a COM method. *vtbl_index* is the " "index into the virtual function table, a small non-negative integer. *name* " @@ -1767,87 +2570,114 @@ msgid "" "identifier which is used in extended error reporting." msgstr "" -#: library/ctypes.rst:1769 +#: library/ctypes.rst:1779 msgid "" "COM methods use a special calling convention: They require a pointer to the " "COM interface as first argument, in addition to those parameters that are " "specified in the :attr:`!argtypes` tuple." msgstr "" -#: library/ctypes.rst:1773 +#: library/ctypes.rst:1783 msgid "" "The optional *paramflags* parameter creates foreign function wrappers with " "much more functionality than the features described above." msgstr "" -#: library/ctypes.rst:1776 +#: library/ctypes.rst:1786 msgid "" -"*paramflags* must be a tuple of the same length as :attr:`~_FuncPtr." +"*paramflags* must be a tuple of the same length as :attr:`~_CFuncPtr." "argtypes`." msgstr "" -#: library/ctypes.rst:1778 +#: library/ctypes.rst:1788 msgid "" "Each item in this tuple contains further information about a parameter, it " "must be a tuple containing one, two, or three items." msgstr "" -#: library/ctypes.rst:1781 +#: library/ctypes.rst:1791 msgid "" "The first item is an integer containing a combination of direction flags for " "the parameter:" msgstr "" -#: library/ctypes.rst:1784 +#: library/ctypes.rst:1794 msgid "1" msgstr "" -#: library/ctypes.rst:1785 +#: library/ctypes.rst:1795 msgid "Specifies an input parameter to the function." msgstr "" -#: library/ctypes.rst:1787 +#: library/ctypes.rst:1797 msgid "2" msgstr "" -#: library/ctypes.rst:1788 +#: library/ctypes.rst:1798 msgid "Output parameter. The foreign function fills in a value." msgstr "" -#: library/ctypes.rst:1790 +#: library/ctypes.rst:1800 msgid "4" msgstr "" -#: library/ctypes.rst:1791 +#: library/ctypes.rst:1801 msgid "Input parameter which defaults to the integer zero." msgstr "" -#: library/ctypes.rst:1793 +#: library/ctypes.rst:1803 msgid "" "The optional second item is the parameter name as string. If this is " "specified, the foreign function can be called with named parameters." msgstr "" -#: library/ctypes.rst:1796 +#: library/ctypes.rst:1806 msgid "The optional third item is the default value for this parameter." msgstr "" -#: library/ctypes.rst:1799 +#: library/ctypes.rst:1809 msgid "" "The following example demonstrates how to wrap the Windows ``MessageBoxW`` " "function so that it supports default parameters and named arguments. The C " "declaration from the windows header file is this::" msgstr "" -#: library/ctypes.rst:1833 +#: library/ctypes.rst:1813 +msgid "" +"WINUSERAPI int WINAPI\n" +"MessageBoxW(\n" +" HWND hWnd,\n" +" LPCWSTR lpText,\n" +" LPCWSTR lpCaption,\n" +" UINT uType);" +msgstr "" + +#: library/ctypes.rst:1843 msgid "Here is the wrapping with :mod:`ctypes`::" msgstr "" -#: library/ctypes.rst:1818 +#: library/ctypes.rst:1822 +msgid "" +">>> from ctypes import c_int, WINFUNCTYPE, windll\n" +">>> from ctypes.wintypes import HWND, LPCWSTR, UINT\n" +">>> prototype = WINFUNCTYPE(c_int, HWND, LPCWSTR, LPCWSTR, UINT)\n" +">>> paramflags = (1, \"hwnd\", 0), (1, \"text\", \"Hi\"), (1, \"caption\", " +"\"Hello from ctypes\"), (1, \"flags\", 0)\n" +">>> MessageBox = prototype((\"MessageBoxW\", windll.user32), paramflags)" +msgstr "" + +#: library/ctypes.rst:1828 msgid "The ``MessageBox`` foreign function can now be called in these ways::" msgstr "" -#: library/ctypes.rst:1824 +#: library/ctypes.rst:1830 +msgid "" +">>> MessageBox()\n" +">>> MessageBox(text=\"Spam, spam, spam\")\n" +">>> MessageBox(flags=2, text=\"foo bar\")" +msgstr "" + +#: library/ctypes.rst:1834 msgid "" "A second example demonstrates output parameters. The win32 " "``GetWindowRect`` function retrieves the dimensions of a specified window by " @@ -1855,7 +2685,26 @@ msgid "" "the C declaration::" msgstr "" -#: library/ctypes.rst:1842 +#: library/ctypes.rst:1838 +msgid "" +"WINUSERAPI BOOL WINAPI\n" +"GetWindowRect(\n" +" HWND hWnd,\n" +" LPRECT lpRect);" +msgstr "" + +#: library/ctypes.rst:1845 +msgid "" +">>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError\n" +">>> from ctypes.wintypes import BOOL, HWND, RECT\n" +">>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))\n" +">>> paramflags = (1, \"hwnd\"), (2, \"lprect\")\n" +">>> GetWindowRect = prototype((\"GetWindowRect\", windll.user32), " +"paramflags)\n" +">>>" +msgstr "" + +#: library/ctypes.rst:1852 msgid "" "Functions with output parameters will automatically return the output " "parameter value if there is a single one, or a tuple containing the output " @@ -1863,62 +2712,91 @@ msgid "" "now returns a RECT instance, when called." msgstr "" -#: library/ctypes.rst:1847 +#: library/ctypes.rst:1857 msgid "" -"Output parameters can be combined with the :attr:`~_FuncPtr.errcheck` " +"Output parameters can be combined with the :attr:`~_CFuncPtr.errcheck` " "protocol to do further output processing and error checking. The win32 " "``GetWindowRect`` api function returns a ``BOOL`` to signal success or " "failure, so this function could do the error checking, and raises an " "exception when the api call failed::" msgstr "" -#: library/ctypes.rst:1860 +#: library/ctypes.rst:1862 +msgid "" +">>> def errcheck(result, func, args):\n" +"... if not result:\n" +"... raise WinError()\n" +"... return args\n" +"...\n" +">>> GetWindowRect.errcheck = errcheck\n" +">>>" +msgstr "" + +#: library/ctypes.rst:1870 msgid "" -"If the :attr:`~_FuncPtr.errcheck` function returns the argument tuple it " +"If the :attr:`~_CFuncPtr.errcheck` function returns the argument tuple it " "receives unchanged, :mod:`ctypes` continues the normal processing it does on " "the output parameters. If you want to return a tuple of window coordinates " "instead of a ``RECT`` instance, you can retrieve the fields in the function " "and return them instead, the normal processing will no longer take place::" msgstr "" -#: library/ctypes.rst:1879 +#: library/ctypes.rst:1876 +msgid "" +">>> def errcheck(result, func, args):\n" +"... if not result:\n" +"... raise WinError()\n" +"... rc = args[1]\n" +"... return rc.left, rc.top, rc.bottom, rc.right\n" +"...\n" +">>> GetWindowRect.errcheck = errcheck\n" +">>>" +msgstr "" + +#: library/ctypes.rst:1889 msgid "Utility functions" msgstr "" -#: library/ctypes.rst:1883 +#: library/ctypes.rst:1893 msgid "" "Returns the address of the memory buffer as integer. *obj* must be an " "instance of a ctypes type." msgstr "" -#: library/ctypes.rst:1886 -msgid "Raises an auditing event ctypes.addressof with argument obj." +#: library/ctypes.rst:1896 +msgid "" +"Raises an :ref:`auditing event ` ``ctypes.addressof`` with " +"argument ``obj``." msgstr "" -#: library/ctypes.rst:1891 +#: library/ctypes.rst:1901 msgid "" "Returns the alignment requirements of a ctypes type. *obj_or_type* must be a " "ctypes type or instance." msgstr "" -#: library/ctypes.rst:1897 +#: library/ctypes.rst:1907 msgid "" "Returns a light-weight pointer to *obj*, which must be an instance of a " "ctypes type. *offset* defaults to zero, and must be an integer that will be " "added to the internal pointer value." msgstr "" -#: library/ctypes.rst:1901 +#: library/ctypes.rst:1911 msgid "``byref(obj, offset)`` corresponds to this C code::" msgstr "" -#: library/ctypes.rst:1905 +#: library/ctypes.rst:1913 +msgid "(((char *)&obj) + offset)" +msgstr "" + +#: library/ctypes.rst:1915 msgid "" "The returned object can only be used as a foreign function call parameter. " "It behaves similar to ``pointer(obj)``, but the construction is a lot faster." msgstr "" -#: library/ctypes.rst:1911 +#: library/ctypes.rst:1921 msgid "" "This function is similar to the cast operator in C. It returns a new " "instance of *type* which points to the same memory block as *obj*. *type* " @@ -1926,19 +2804,19 @@ msgid "" "as a pointer." msgstr "" -#: library/ctypes.rst:1919 +#: library/ctypes.rst:1929 msgid "" "This function creates a mutable character buffer. The returned object is a " "ctypes array of :class:`c_char`." msgstr "" -#: library/ctypes.rst:1922 +#: library/ctypes.rst:1932 msgid "" "*init_or_size* must be an integer which specifies the size of the array, or " "a bytes object which will be used to initialize the array items." msgstr "" -#: library/ctypes.rst:1925 +#: library/ctypes.rst:1935 msgid "" "If a bytes object is specified as first argument, the buffer is made one " "item larger than its length so that the last element in the array is a NUL " @@ -1947,25 +2825,25 @@ msgid "" "not be used." msgstr "" -#: library/ctypes.rst:1930 +#: library/ctypes.rst:1940 msgid "" -"Raises an auditing event ctypes.create_string_buffer with arguments init, " -"size." +"Raises an :ref:`auditing event ` ``ctypes.create_string_buffer`` " +"with arguments ``init``, ``size``." msgstr "" -#: library/ctypes.rst:1935 +#: library/ctypes.rst:1945 msgid "" "This function creates a mutable unicode character buffer. The returned " "object is a ctypes array of :class:`c_wchar`." msgstr "" -#: library/ctypes.rst:1938 +#: library/ctypes.rst:1948 msgid "" "*init_or_size* must be an integer which specifies the size of the array, or " "a string which will be used to initialize the array items." msgstr "" -#: library/ctypes.rst:1941 +#: library/ctypes.rst:1951 msgid "" "If a string is specified as first argument, the buffer is made one item " "larger than the length of the string so that the last element in the array " @@ -1974,27 +2852,27 @@ msgid "" "should not be used." msgstr "" -#: library/ctypes.rst:1947 +#: library/ctypes.rst:1957 msgid "" -"Raises an auditing event ctypes.create_unicode_buffer with arguments init, " -"size." +"Raises an :ref:`auditing event ` ``ctypes.create_unicode_buffer`` " +"with arguments ``init``, ``size``." msgstr "" -#: library/ctypes.rst:1952 +#: library/ctypes.rst:1962 msgid "" "Windows only: This function is a hook which allows implementing in-process " "COM servers with ctypes. It is called from the DllCanUnloadNow function " "that the _ctypes extension dll exports." msgstr "" -#: library/ctypes.rst:1959 +#: library/ctypes.rst:1969 msgid "" "Windows only: This function is a hook which allows implementing in-process " "COM servers with ctypes. It is called from the DllGetClassObject function " "that the ``_ctypes`` extension dll exports." msgstr "" -#: library/ctypes.rst:1967 +#: library/ctypes.rst:1977 msgid "" "Try to find a library and return a pathname. *name* is the library name " "without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version " @@ -2002,88 +2880,92 @@ msgid "" "If no library can be found, returns ``None``." msgstr "" -#: library/ctypes.rst:1978 +#: library/ctypes.rst:1988 msgid "" "Windows only: return the filename of the VC runtime library used by Python, " "and by the extension modules. If the name of the library cannot be " "determined, ``None`` is returned." msgstr "" -#: library/ctypes.rst:1982 +#: library/ctypes.rst:1992 msgid "" "If you need to free memory, for example, allocated by an extension module " "with a call to the ``free(void *)``, it is important that you use the " "function in the same library that allocated the memory." msgstr "" -#: library/ctypes.rst:1989 +#: library/ctypes.rst:1999 msgid "" "Windows only: Returns a textual description of the error code *code*. If no " "error code is specified, the last error code is used by calling the Windows " "api function GetLastError." msgstr "" -#: library/ctypes.rst:1996 +#: library/ctypes.rst:2006 msgid "" "Windows only: Returns the last error code set by Windows in the calling " "thread. This function calls the Windows ``GetLastError()`` function " "directly, it does not return the ctypes-private copy of the error code." msgstr "" -#: library/ctypes.rst:2002 +#: library/ctypes.rst:2012 msgid "" "Returns the current value of the ctypes-private copy of the system :data:" "`errno` variable in the calling thread." msgstr "" -#: library/ctypes.rst:2005 -msgid "Raises an auditing event ctypes.get_errno with no arguments." +#: library/ctypes.rst:2015 +msgid "" +"Raises an :ref:`auditing event ` ``ctypes.get_errno`` with no " +"arguments." msgstr "" -#: library/ctypes.rst:2009 +#: library/ctypes.rst:2019 msgid "" "Windows only: returns the current value of the ctypes-private copy of the " "system :data:`!LastError` variable in the calling thread." msgstr "" -#: library/ctypes.rst:2012 -msgid "Raises an auditing event ctypes.get_last_error with no arguments." +#: library/ctypes.rst:2022 +msgid "" +"Raises an :ref:`auditing event ` ``ctypes.get_last_error`` with no " +"arguments." msgstr "" -#: library/ctypes.rst:2016 +#: library/ctypes.rst:2026 msgid "" "Same as the standard C memmove library function: copies *count* bytes from " "*src* to *dst*. *dst* and *src* must be integers or ctypes instances that " "can be converted to pointers." msgstr "" -#: library/ctypes.rst:2023 +#: library/ctypes.rst:2033 msgid "" "Same as the standard C memset library function: fills the memory block at " "address *dst* with *count* bytes of value *c*. *dst* must be an integer " "specifying an address, or a ctypes instance." msgstr "" -#: library/ctypes.rst:2030 +#: library/ctypes.rst:2040 msgid "" "Create and return a new ctypes pointer type. Pointer types are cached and " "reused internally, so calling this function repeatedly is cheap. *type* must " "be a ctypes type." msgstr "" -#: library/ctypes.rst:2037 +#: library/ctypes.rst:2047 msgid "" "Create a new pointer instance, pointing to *obj*. The returned object is of " "the type ``POINTER(type(obj))``." msgstr "" -#: library/ctypes.rst:2040 +#: library/ctypes.rst:2050 msgid "" "Note: If you just want to pass a pointer to an object to a foreign function " "call, you should use ``byref(obj)`` which is much faster." msgstr "" -#: library/ctypes.rst:2046 +#: library/ctypes.rst:2056 msgid "" "This function resizes the internal memory buffer of *obj*, which must be an " "instance of a ctypes type. It is not possible to make the buffer smaller " @@ -2091,44 +2973,50 @@ msgid "" "but it is possible to enlarge the buffer." msgstr "" -#: library/ctypes.rst:2054 +#: library/ctypes.rst:2064 msgid "" "Set the current value of the ctypes-private copy of the system :data:`errno` " "variable in the calling thread to *value* and return the previous value." msgstr "" -#: library/ctypes.rst:2057 -msgid "Raises an auditing event ctypes.set_errno with argument errno." +#: library/ctypes.rst:2067 +msgid "" +"Raises an :ref:`auditing event ` ``ctypes.set_errno`` with " +"argument ``errno``." msgstr "" -#: library/ctypes.rst:2062 +#: library/ctypes.rst:2072 msgid "" "Windows only: set the current value of the ctypes-private copy of the " "system :data:`!LastError` variable in the calling thread to *value* and " "return the previous value." msgstr "" -#: library/ctypes.rst:2066 -msgid "Raises an auditing event ctypes.set_last_error with argument error." +#: library/ctypes.rst:2076 +msgid "" +"Raises an :ref:`auditing event ` ``ctypes.set_last_error`` with " +"argument ``error``." msgstr "" -#: library/ctypes.rst:2071 +#: library/ctypes.rst:2081 msgid "" "Returns the size in bytes of a ctypes type or instance memory buffer. Does " "the same as the C ``sizeof`` operator." msgstr "" -#: library/ctypes.rst:2077 +#: library/ctypes.rst:2087 msgid "" "Return the byte string at *void \\*ptr*. If *size* is specified, it is used " "as size, otherwise the string is assumed to be zero-terminated." msgstr "" -#: library/ctypes.rst:2081 -msgid "Raises an auditing event ctypes.string_at with arguments ptr, size." +#: library/ctypes.rst:2091 +msgid "" +"Raises an :ref:`auditing event ` ``ctypes.string_at`` with " +"arguments ``ptr``, ``size``." msgstr "" -#: library/ctypes.rst:2086 +#: library/ctypes.rst:2096 msgid "" "Windows only: this function is probably the worst-named thing in ctypes. It " "creates an instance of :exc:`OSError`. If *code* is not specified, " @@ -2137,28 +3025,30 @@ msgid "" "error." msgstr "" -#: library/ctypes.rst:2092 +#: library/ctypes.rst:2102 msgid "" "An instance of :exc:`WindowsError` used to be created, which is now an alias " "of :exc:`OSError`." msgstr "" -#: library/ctypes.rst:2099 +#: library/ctypes.rst:2109 msgid "" "Return the wide-character string at *void \\*ptr*. If *size* is specified, " "it is used as the number of characters of the string, otherwise the string " "is assumed to be zero-terminated." msgstr "" -#: library/ctypes.rst:2104 -msgid "Raises an auditing event ctypes.wstring_at with arguments ptr, size." +#: library/ctypes.rst:2114 +msgid "" +"Raises an :ref:`auditing event ` ``ctypes.wstring_at`` with " +"arguments ``ptr``, ``size``." msgstr "" -#: library/ctypes.rst:2110 +#: library/ctypes.rst:2120 msgid "Data types" msgstr "" -#: library/ctypes.rst:2115 +#: library/ctypes.rst:2125 msgid "" "This non-public class is the common base class of all ctypes data types. " "Among other things, all ctypes type instances contain a memory block that " @@ -2168,13 +3058,13 @@ msgid "" "alive in case the memory block contains pointers." msgstr "" -#: library/ctypes.rst:2122 +#: library/ctypes.rst:2132 msgid "" "Common methods of ctypes data types, these are all class methods (to be " "exact, they are methods of the :term:`metaclass`):" msgstr "" -#: library/ctypes.rst:2127 +#: library/ctypes.rst:2137 msgid "" "This method returns a ctypes instance that shares the buffer of the *source* " "object. The *source* object must support the writeable buffer interface. " @@ -2183,13 +3073,13 @@ msgid "" "exc:`ValueError` is raised." msgstr "" -#: library/ctypes.rst:2143 +#: library/ctypes.rst:2153 msgid "" -"Raises an auditing event ctypes.cdata/buffer with arguments pointer, size, " -"offset." +"Raises an :ref:`auditing event ` ``ctypes.cdata/buffer`` with " +"arguments ``pointer``, ``size``, ``offset``." msgstr "" -#: library/ctypes.rst:2137 +#: library/ctypes.rst:2147 msgid "" "This method creates a ctypes instance, copying the buffer from the *source* " "object buffer which must be readable. The optional *offset* parameter " @@ -2197,51 +3087,45 @@ msgid "" "If the source buffer is not large enough a :exc:`ValueError` is raised." msgstr "" -#: library/ctypes.rst:2147 +#: library/ctypes.rst:2157 msgid "" "This method returns a ctypes type instance using the memory specified by " "*address* which must be an integer." msgstr "" -#: library/ctypes.rst:2150 -msgid "" -"This method, and others that indirectly call this method, raises an auditing " -"event ctypes.cdata with argument address." -msgstr "" - -#: library/ctypes.rst:2152 +#: library/ctypes.rst:2162 msgid "" "This method, and others that indirectly call this method, raises an :ref:" "`auditing event ` ``ctypes.cdata`` with argument ``address``." msgstr "" -#: library/ctypes.rst:2158 +#: library/ctypes.rst:2168 msgid "" "This method adapts *obj* to a ctypes type. It is called with the actual " "object used in a foreign function call when the type is present in the " -"foreign function's :attr:`~_FuncPtr.argtypes` tuple; it must return an " +"foreign function's :attr:`~_CFuncPtr.argtypes` tuple; it must return an " "object that can be used as a function call parameter." msgstr "" -#: library/ctypes.rst:2163 +#: library/ctypes.rst:2173 msgid "" "All ctypes data types have a default implementation of this classmethod that " "normally returns *obj* if that is an instance of the type. Some types " "accept other objects as well." msgstr "" -#: library/ctypes.rst:2169 +#: library/ctypes.rst:2179 msgid "" "This method returns a ctypes type instance exported by a shared library. " "*name* is the name of the symbol that exports the data, *library* is the " "loaded shared library." msgstr "" -#: library/ctypes.rst:2173 +#: library/ctypes.rst:2183 msgid "Common instance variables of ctypes data types:" msgstr "" -#: library/ctypes.rst:2177 +#: library/ctypes.rst:2187 msgid "" "Sometimes ctypes data instances do not own the memory block they contain, " "instead they share part of the memory block of a base object. The :attr:" @@ -2249,13 +3133,13 @@ msgid "" "block." msgstr "" -#: library/ctypes.rst:2184 +#: library/ctypes.rst:2194 msgid "" "This read-only variable is true when the ctypes data instance has allocated " "the memory block itself, false otherwise." msgstr "" -#: library/ctypes.rst:2189 +#: library/ctypes.rst:2199 msgid "" "This member is either ``None`` or a dictionary containing Python objects " "that need to be kept alive so that the memory block contents is kept valid. " @@ -2263,7 +3147,7 @@ msgid "" "dictionary." msgstr "" -#: library/ctypes.rst:2202 +#: library/ctypes.rst:2212 msgid "" "This non-public class is the base class of all fundamental ctypes data " "types. It is mentioned here because it contains the common attributes of the " @@ -2272,11 +3156,11 @@ msgid "" "types that are not and do not contain pointers can now be pickled." msgstr "" -#: library/ctypes.rst:2208 +#: library/ctypes.rst:2218 msgid "Instances have a single attribute:" msgstr "" -#: library/ctypes.rst:2212 +#: library/ctypes.rst:2222 msgid "" "This attribute contains the actual value of the instance. For integer and " "pointer types, it is an integer, for character types, it is a single " @@ -2284,7 +3168,7 @@ msgid "" "bytes object or string." msgstr "" -#: library/ctypes.rst:2217 +#: library/ctypes.rst:2227 msgid "" "When the ``value`` attribute is retrieved from a ctypes instance, usually a " "new object is returned each time. :mod:`ctypes` does *not* implement " @@ -2292,17 +3176,17 @@ msgid "" "true for all other ctypes object instances." msgstr "" -#: library/ctypes.rst:2223 +#: library/ctypes.rst:2233 msgid "" "Fundamental data types, when returned as foreign function call results, or, " "for example, by retrieving structure field members or array items, are " "transparently converted to native Python types. In other words, if a " -"foreign function has a :attr:`~_FuncPtr.restype` of :class:`c_char_p`, you " +"foreign function has a :attr:`~_CFuncPtr.restype` of :class:`c_char_p`, you " "will always receive a Python bytes object, *not* a :class:`c_char_p` " "instance." msgstr "" -#: library/ctypes.rst:2231 +#: library/ctypes.rst:2241 msgid "" "Subclasses of fundamental data types do *not* inherit this behavior. So, if " "a foreign functions :attr:`!restype` is a subclass of :class:`c_void_p`, you " @@ -2310,25 +3194,25 @@ msgid "" "you can get the value of the pointer by accessing the ``value`` attribute." msgstr "" -#: library/ctypes.rst:2236 +#: library/ctypes.rst:2246 msgid "These are the fundamental ctypes data types:" msgstr "" -#: library/ctypes.rst:2240 +#: library/ctypes.rst:2250 msgid "" "Represents the C :c:expr:`signed char` datatype, and interprets the value as " "small integer. The constructor accepts an optional integer initializer; no " "overflow checking is done." msgstr "" -#: library/ctypes.rst:2247 +#: library/ctypes.rst:2257 msgid "" "Represents the C :c:expr:`char` datatype, and interprets the value as a " "single character. The constructor accepts an optional string initializer, " "the length of the string must be exactly one character." msgstr "" -#: library/ctypes.rst:2254 +#: library/ctypes.rst:2264 msgid "" "Represents the C :c:expr:`char *` datatype when it points to a zero-" "terminated string. For a general character pointer that may also point to " @@ -2336,182 +3220,182 @@ msgid "" "integer address, or a bytes object." msgstr "" -#: library/ctypes.rst:2262 +#: library/ctypes.rst:2272 msgid "" "Represents the C :c:expr:`double` datatype. The constructor accepts an " "optional float initializer." msgstr "" -#: library/ctypes.rst:2268 +#: library/ctypes.rst:2278 msgid "" "Represents the C :c:expr:`long double` datatype. The constructor accepts an " "optional float initializer. On platforms where ``sizeof(long double) == " "sizeof(double)`` it is an alias to :class:`c_double`." msgstr "" -#: library/ctypes.rst:2274 +#: library/ctypes.rst:2284 msgid "" "Represents the C :c:expr:`float` datatype. The constructor accepts an " "optional float initializer." msgstr "" -#: library/ctypes.rst:2280 +#: library/ctypes.rst:2290 msgid "" "Represents the C :c:expr:`signed int` datatype. The constructor accepts an " "optional integer initializer; no overflow checking is done. On platforms " "where ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`." msgstr "" -#: library/ctypes.rst:2287 +#: library/ctypes.rst:2297 msgid "" "Represents the C 8-bit :c:expr:`signed int` datatype. Usually an alias for :" "class:`c_byte`." msgstr "" -#: library/ctypes.rst:2293 +#: library/ctypes.rst:2303 msgid "" "Represents the C 16-bit :c:expr:`signed int` datatype. Usually an alias " "for :class:`c_short`." msgstr "" -#: library/ctypes.rst:2299 +#: library/ctypes.rst:2309 msgid "" "Represents the C 32-bit :c:expr:`signed int` datatype. Usually an alias " "for :class:`c_int`." msgstr "" -#: library/ctypes.rst:2305 +#: library/ctypes.rst:2315 msgid "" "Represents the C 64-bit :c:expr:`signed int` datatype. Usually an alias " "for :class:`c_longlong`." msgstr "" -#: library/ctypes.rst:2311 +#: library/ctypes.rst:2321 msgid "" "Represents the C :c:expr:`signed long` datatype. The constructor accepts an " "optional integer initializer; no overflow checking is done." msgstr "" -#: library/ctypes.rst:2317 +#: library/ctypes.rst:2327 msgid "" "Represents the C :c:expr:`signed long long` datatype. The constructor " "accepts an optional integer initializer; no overflow checking is done." msgstr "" -#: library/ctypes.rst:2323 +#: library/ctypes.rst:2333 msgid "" "Represents the C :c:expr:`signed short` datatype. The constructor accepts " "an optional integer initializer; no overflow checking is done." msgstr "" -#: library/ctypes.rst:2329 +#: library/ctypes.rst:2339 msgid "Represents the C :c:type:`size_t` datatype." msgstr "" -#: library/ctypes.rst:2334 +#: library/ctypes.rst:2344 msgid "Represents the C :c:type:`ssize_t` datatype." msgstr "" -#: library/ctypes.rst:2341 +#: library/ctypes.rst:2351 msgid "Represents the C :c:type:`time_t` datatype." msgstr "" -#: library/ctypes.rst:2348 +#: library/ctypes.rst:2358 msgid "" "Represents the C :c:expr:`unsigned char` datatype, it interprets the value " "as small integer. The constructor accepts an optional integer initializer; " "no overflow checking is done." msgstr "" -#: library/ctypes.rst:2355 +#: library/ctypes.rst:2365 msgid "" "Represents the C :c:expr:`unsigned int` datatype. The constructor accepts " "an optional integer initializer; no overflow checking is done. On platforms " "where ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`." msgstr "" -#: library/ctypes.rst:2362 +#: library/ctypes.rst:2372 msgid "" "Represents the C 8-bit :c:expr:`unsigned int` datatype. Usually an alias " "for :class:`c_ubyte`." msgstr "" -#: library/ctypes.rst:2368 +#: library/ctypes.rst:2378 msgid "" "Represents the C 16-bit :c:expr:`unsigned int` datatype. Usually an alias " "for :class:`c_ushort`." msgstr "" -#: library/ctypes.rst:2374 +#: library/ctypes.rst:2384 msgid "" "Represents the C 32-bit :c:expr:`unsigned int` datatype. Usually an alias " "for :class:`c_uint`." msgstr "" -#: library/ctypes.rst:2380 +#: library/ctypes.rst:2390 msgid "" "Represents the C 64-bit :c:expr:`unsigned int` datatype. Usually an alias " "for :class:`c_ulonglong`." msgstr "" -#: library/ctypes.rst:2386 +#: library/ctypes.rst:2396 msgid "" "Represents the C :c:expr:`unsigned long` datatype. The constructor accepts " "an optional integer initializer; no overflow checking is done." msgstr "" -#: library/ctypes.rst:2392 +#: library/ctypes.rst:2402 msgid "" "Represents the C :c:expr:`unsigned long long` datatype. The constructor " "accepts an optional integer initializer; no overflow checking is done." msgstr "" -#: library/ctypes.rst:2398 +#: library/ctypes.rst:2408 msgid "" "Represents the C :c:expr:`unsigned short` datatype. The constructor accepts " "an optional integer initializer; no overflow checking is done." msgstr "" -#: library/ctypes.rst:2404 +#: library/ctypes.rst:2414 msgid "" "Represents the C :c:expr:`void *` type. The value is represented as " "integer. The constructor accepts an optional integer initializer." msgstr "" -#: library/ctypes.rst:2410 +#: library/ctypes.rst:2420 msgid "" "Represents the C :c:type:`wchar_t` datatype, and interprets the value as a " "single character unicode string. The constructor accepts an optional string " "initializer, the length of the string must be exactly one character." msgstr "" -#: library/ctypes.rst:2417 +#: library/ctypes.rst:2427 msgid "" "Represents the C :c:expr:`wchar_t *` datatype, which must be a pointer to a " "zero-terminated wide character string. The constructor accepts an integer " "address, or a string." msgstr "" -#: library/ctypes.rst:2424 +#: library/ctypes.rst:2434 msgid "" "Represent the C :c:expr:`bool` datatype (more accurately, :c:expr:`_Bool` " "from C99). Its value can be ``True`` or ``False``, and the constructor " "accepts any object that has a truth value." msgstr "" -#: library/ctypes.rst:2431 +#: library/ctypes.rst:2441 msgid "" "Windows only: Represents a :c:type:`!HRESULT` value, which contains success " "or error information for a function or method call." msgstr "" -#: library/ctypes.rst:2437 +#: library/ctypes.rst:2447 msgid "" "Represents the C :c:expr:`PyObject *` datatype. Calling this without an " "argument creates a ``NULL`` :c:expr:`PyObject *` pointer." msgstr "" -#: library/ctypes.rst:2440 +#: library/ctypes.rst:2450 msgid "" "The :mod:`!ctypes.wintypes` module provides quite some other Windows " "specific data types, for example :c:type:`!HWND`, :c:type:`!WPARAM`, or :c:" @@ -2519,41 +3403,41 @@ msgid "" "are also defined." msgstr "" -#: library/ctypes.rst:2448 +#: library/ctypes.rst:2458 msgid "Structured data types" msgstr "" -#: library/ctypes.rst:2453 +#: library/ctypes.rst:2463 msgid "Abstract base class for unions in native byte order." msgstr "" -#: library/ctypes.rst:2458 +#: library/ctypes.rst:2468 msgid "Abstract base class for unions in *big endian* byte order." msgstr "" -#: library/ctypes.rst:2464 +#: library/ctypes.rst:2474 msgid "Abstract base class for unions in *little endian* byte order." msgstr "" -#: library/ctypes.rst:2470 +#: library/ctypes.rst:2480 msgid "Abstract base class for structures in *big endian* byte order." msgstr "" -#: library/ctypes.rst:2475 +#: library/ctypes.rst:2485 msgid "Abstract base class for structures in *little endian* byte order." msgstr "" -#: library/ctypes.rst:2477 +#: library/ctypes.rst:2487 msgid "" "Structures and unions with non-native byte order cannot contain pointer type " "fields, or any other data types containing pointer type fields." msgstr "" -#: library/ctypes.rst:2483 +#: library/ctypes.rst:2493 msgid "Abstract base class for structures in *native* byte order." msgstr "" -#: library/ctypes.rst:2485 +#: library/ctypes.rst:2495 msgid "" "Concrete structure and union types must be created by subclassing one of " "these types, and at least define a :attr:`_fields_` class variable. :mod:" @@ -2561,34 +3445,43 @@ msgid "" "the fields by direct attribute accesses. These are the" msgstr "" -#: library/ctypes.rst:2493 +#: library/ctypes.rst:2503 msgid "" "A sequence defining the structure fields. The items must be 2-tuples or 3-" "tuples. The first item is the name of the field, the second item specifies " "the type of the field; it can be any ctypes data type." msgstr "" -#: library/ctypes.rst:2497 +#: library/ctypes.rst:2507 msgid "" "For integer type fields like :class:`c_int`, a third optional item can be " "given. It must be a small positive integer defining the bit width of the " "field." msgstr "" -#: library/ctypes.rst:2501 +#: library/ctypes.rst:2511 msgid "" "Field names must be unique within one structure or union. This is not " "checked, only one field can be accessed when names are repeated." msgstr "" -#: library/ctypes.rst:2504 +#: library/ctypes.rst:2514 msgid "" "It is possible to define the :attr:`_fields_` class variable *after* the " "class statement that defines the Structure subclass, this allows creating " "data types that directly or indirectly reference themselves::" msgstr "" -#: library/ctypes.rst:2514 +#: library/ctypes.rst:2518 +msgid "" +"class List(Structure):\n" +" pass\n" +"List._fields_ = [(\"pnext\", POINTER(List)),\n" +" ...\n" +" ]" +msgstr "" + +#: library/ctypes.rst:2524 msgid "" "The :attr:`_fields_` class variable must, however, be defined before the " "type is first used (an instance is created, :func:`sizeof` is called on it, " @@ -2596,14 +3489,14 @@ msgid "" "raise an AttributeError." msgstr "" -#: library/ctypes.rst:2519 +#: library/ctypes.rst:2529 msgid "" "It is possible to define sub-subclasses of structure types, they inherit the " "fields of the base class plus the :attr:`_fields_` defined in the sub-" "subclass, if any." msgstr "" -#: library/ctypes.rst:2526 +#: library/ctypes.rst:2536 msgid "" "An optional small integer that allows overriding the alignment of structure " "fields in the instance. :attr:`_pack_` must already be defined when :attr:" @@ -2611,14 +3504,14 @@ msgid "" "attribute to 0 is the same as not setting it at all." msgstr "" -#: library/ctypes.rst:2534 +#: library/ctypes.rst:2544 msgid "" "An optional sequence that lists the names of unnamed (anonymous) fields. :" "attr:`_anonymous_` must be already defined when :attr:`_fields_` is " "assigned, otherwise it will have no effect." msgstr "" -#: library/ctypes.rst:2538 +#: library/ctypes.rst:2548 msgid "" "The fields listed in this variable must be structure or union type fields. :" "mod:`ctypes` will create descriptors in the structure type that allows " @@ -2626,11 +3519,24 @@ msgid "" "structure or union field." msgstr "" -#: library/ctypes.rst:2543 +#: library/ctypes.rst:2553 msgid "Here is an example type (Windows)::" msgstr "" -#: library/ctypes.rst:2556 +#: library/ctypes.rst:2555 +msgid "" +"class _U(Union):\n" +" _fields_ = [(\"lptdesc\", POINTER(TYPEDESC)),\n" +" (\"lpadesc\", POINTER(ARRAYDESC)),\n" +" (\"hreftype\", HREFTYPE)]\n" +"\n" +"class TYPEDESC(Structure):\n" +" _anonymous_ = (\"u\",)\n" +" _fields_ = [(\"u\", _U),\n" +" (\"vt\", VARTYPE)]" +msgstr "" + +#: library/ctypes.rst:2566 msgid "" "The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field " "specifies which one of the union fields is valid. Since the ``u`` field is " @@ -2640,7 +3546,15 @@ msgid "" "temporary union instance::" msgstr "" -#: library/ctypes.rst:2568 +#: library/ctypes.rst:2573 +msgid "" +"td = TYPEDESC()\n" +"td.vt = VT_PTR\n" +"td.lptdesc = POINTER(some_type)\n" +"td.u.lptdesc = POINTER(some_type)" +msgstr "" + +#: library/ctypes.rst:2578 msgid "" "It is possible to define sub-subclasses of structures, they inherit the " "fields of the base class. If the subclass definition has a separate :attr:" @@ -2648,7 +3562,7 @@ msgid "" "of the base class." msgstr "" -#: library/ctypes.rst:2573 +#: library/ctypes.rst:2583 msgid "" "Structure and union constructors accept both positional and keyword " "arguments. Positional arguments are used to initialize member fields in the " @@ -2658,15 +3572,15 @@ msgid "" "names not present in :attr:`_fields_`." msgstr "" -#: library/ctypes.rst:2584 +#: library/ctypes.rst:2594 msgid "Arrays and pointers" msgstr "" -#: library/ctypes.rst:2588 +#: library/ctypes.rst:2598 msgid "Abstract base class for arrays." msgstr "" -#: library/ctypes.rst:2590 +#: library/ctypes.rst:2600 msgid "" "The recommended way to create concrete array types is by multiplying any :" "mod:`ctypes` data type with a non-negative integer. Alternatively, you can " @@ -2676,34 +3590,34 @@ msgid "" "an :class:`Array`." msgstr "" -#: library/ctypes.rst:2600 +#: library/ctypes.rst:2610 msgid "" "A positive integer specifying the number of elements in the array. Out-of-" "range subscripts result in an :exc:`IndexError`. Will be returned by :func:" "`len`." msgstr "" -#: library/ctypes.rst:2607 +#: library/ctypes.rst:2617 msgid "Specifies the type of each element in the array." msgstr "" -#: library/ctypes.rst:2610 +#: library/ctypes.rst:2620 msgid "" "Array subclass constructors accept positional arguments, used to initialize " "the elements in order." msgstr "" -#: library/ctypes.rst:2616 +#: library/ctypes.rst:2626 msgid "Private, abstract base class for pointers." msgstr "" -#: library/ctypes.rst:2618 +#: library/ctypes.rst:2628 msgid "" "Concrete pointer types are created by calling :func:`POINTER` with the type " "that will be pointed to; this is done automatically by :func:`pointer`." msgstr "" -#: library/ctypes.rst:2622 +#: library/ctypes.rst:2632 msgid "" "If a pointer points to an array, its elements can be read and written using " "standard subscript and slice accesses. Pointer objects have no size, so :" @@ -2712,11 +3626,11 @@ msgid "" "probably crash with an access violation (if you're lucky)." msgstr "" -#: library/ctypes.rst:2632 +#: library/ctypes.rst:2642 msgid "Specifies the type pointed to." msgstr "" -#: library/ctypes.rst:2636 +#: library/ctypes.rst:2646 msgid "" "Returns the object to which to pointer points. Assigning to this attribute " "changes the pointer to point to the assigned object." diff --git a/library/dataclasses.po b/library/dataclasses.po index 8ad9e5671..7c67102b0 100644 --- a/library/dataclasses.po +++ b/library/dataclasses.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -38,10 +38,34 @@ msgid "" "pep:`526` type annotations. For example, this code::" msgstr "" +#: library/dataclasses.rst:22 +msgid "" +"from dataclasses import dataclass\n" +"\n" +"@dataclass\n" +"class InventoryItem:\n" +" \"\"\"Class for keeping track of an item in inventory.\"\"\"\n" +" name: str\n" +" unit_price: float\n" +" quantity_on_hand: int = 0\n" +"\n" +" def total_cost(self) -> float:\n" +" return self.unit_price * self.quantity_on_hand" +msgstr "" + #: library/dataclasses.rst:34 msgid "will add, among other things, a :meth:`!__init__` that looks like::" msgstr "" +#: library/dataclasses.rst:36 +msgid "" +"def __init__(self, name: str, unit_price: float, quantity_on_hand: int = " +"0):\n" +" self.name = name\n" +" self.unit_price = unit_price\n" +" self.quantity_on_hand = quantity_on_hand" +msgstr "" + #: library/dataclasses.rst:41 msgid "" "Note that this method is automatically added to the class: it is not " @@ -88,6 +112,23 @@ msgid "" "these three uses of ``@dataclass`` are equivalent::" msgstr "" +#: library/dataclasses.rst:74 +msgid "" +"@dataclass\n" +"class C:\n" +" ...\n" +"\n" +"@dataclass()\n" +"class C:\n" +" ...\n" +"\n" +"@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, " +"frozen=False,\n" +" match_args=True, kw_only=False, slots=False, weakref_slot=False)\n" +"class C:\n" +" ..." +msgstr "" + #: library/dataclasses.rst:87 msgid "The parameters to ``@dataclass`` are:" msgstr "" @@ -154,7 +195,7 @@ msgstr "" #: library/dataclasses.rst:127 msgid "" -":meth:`!__hash__` is used by built-in :meth:`hash()`, and when objects are " +":meth:`!__hash__` is used by built-in :meth:`hash`, and when objects are " "added to hashed collections such as dictionaries and sets. Having a :meth:`!" "__hash__` implies that instances of the class are immutable. Mutability is a " "complicated property that depends on the programmer's intent, the existence " @@ -233,14 +274,26 @@ msgid "" "*slots*: If true (the default is ``False``), :attr:`~object.__slots__` " "attribute will be generated and new class will be returned instead of the " "original one. If :attr:`!__slots__` is already defined in the class, then :" -"exc:`TypeError` is raised. Calling no-arg :func:`super` in dataclasses using " -"``slots=True`` will result in the following exception being raised: " -"``TypeError: super(type, obj): obj must be an instance or subtype of type``. " -"The two-arg :func:`super` is a valid workaround. See :gh:`90562` for full " -"details." +"exc:`TypeError` is raised." msgstr "" -#: library/dataclasses.rst:195 +#: library/dataclasses.rst:191 +msgid "" +"Calling no-arg :func:`super` in dataclasses using ``slots=True`` will result " +"in the following exception being raised: ``TypeError: super(type, obj): obj " +"must be an instance or subtype of type``. The two-arg :func:`super` is a " +"valid workaround. See :gh:`90562` for full details." +msgstr "" + +#: library/dataclasses.rst:198 +msgid "" +"Passing parameters to a base class :meth:`~object.__init_subclass__` when " +"using ``slots=True`` will result in a :exc:`TypeError`. Either use " +"``__init_subclass__`` with no parameters or use default values as a " +"workaround. See :gh:`91126` for full details." +msgstr "" + +#: library/dataclasses.rst:206 msgid "" "If a field name is already included in the :attr:`!__slots__` of a base " "class, it will not be included in the generated :attr:`!__slots__` to " @@ -250,34 +303,46 @@ msgid "" "`!__slots__` may be any iterable, but *not* an iterator." msgstr "" -#: library/dataclasses.rst:205 +#: library/dataclasses.rst:216 msgid "" "*weakref_slot*: If true (the default is ``False``), add a slot named " -"\"__weakref__\", which is required to make an instance weakref-able. It is " -"an error to specify ``weakref_slot=True`` without also specifying " -"``slots=True``." +"\"__weakref__\", which is required to make an instance :func:`weakref-able " +"`. It is an error to specify ``weakref_slot=True`` without also " +"specifying ``slots=True``." msgstr "" -#: library/dataclasses.rst:212 +#: library/dataclasses.rst:224 msgid "" "``field``\\s may optionally specify a default value, using normal Python " "syntax::" msgstr "" -#: library/dataclasses.rst:220 +#: library/dataclasses.rst:227 +msgid "" +"@dataclass\n" +"class C:\n" +" a: int # 'a' has no default value\n" +" b: int = 0 # assign a default value for 'b'" +msgstr "" + +#: library/dataclasses.rst:232 msgid "" "In this example, both :attr:`!a` and :attr:`!b` will be included in the " "added :meth:`~object.__init__` method, which will be defined as::" msgstr "" -#: library/dataclasses.rst:225 +#: library/dataclasses.rst:235 +msgid "def __init__(self, a: int, b: int = 0):" +msgstr "" + +#: library/dataclasses.rst:237 msgid "" ":exc:`TypeError` will be raised if a field without a default value follows a " "field with a default value. This is true whether this occurs in a single " "class, or as a result of class inheritance." msgstr "" -#: library/dataclasses.rst:231 +#: library/dataclasses.rst:243 msgid "" "For common and simple use cases, no other functionality is required. There " "are, however, some dataclass features that require additional per-field " @@ -286,7 +351,17 @@ msgid "" "function. For example::" msgstr "" -#: library/dataclasses.rst:244 +#: library/dataclasses.rst:249 +msgid "" +"@dataclass\n" +"class C:\n" +" mylist: list[int] = field(default_factory=list)\n" +"\n" +"c = C()\n" +"c.mylist += [1, 2, 3]" +msgstr "" + +#: library/dataclasses.rst:256 msgid "" "As shown above, the :const:`MISSING` value is a sentinel object used to " "detect if some parameters are provided by the user. This sentinel is used " @@ -294,18 +369,18 @@ msgid "" "meaning. No code should directly use the :const:`MISSING` value." msgstr "" -#: library/dataclasses.rst:249 +#: library/dataclasses.rst:261 msgid "The parameters to :func:`!field` are:" msgstr "" -#: library/dataclasses.rst:251 +#: library/dataclasses.rst:263 msgid "" "*default*: If provided, this will be the default value for this field. This " "is needed because the :func:`!field` call itself replaces the normal " "position of the default value." msgstr "" -#: library/dataclasses.rst:255 +#: library/dataclasses.rst:267 msgid "" "*default_factory*: If provided, it must be a zero-argument callable that " "will be called when a default value is needed for this field. Among other " @@ -314,19 +389,19 @@ msgid "" "*default_factory*." msgstr "" -#: library/dataclasses.rst:261 +#: library/dataclasses.rst:273 msgid "" "*init*: If true (the default), this field is included as a parameter to the " "generated :meth:`~object.__init__` method." msgstr "" -#: library/dataclasses.rst:264 +#: library/dataclasses.rst:276 msgid "" "*repr*: If true (the default), this field is included in the string returned " "by the generated :meth:`~object.__repr__` method." msgstr "" -#: library/dataclasses.rst:267 +#: library/dataclasses.rst:279 msgid "" "*hash*: This can be a bool or ``None``. If true, this field is included in " "the generated :meth:`~object.__hash__` method. If ``None`` (the default), " @@ -335,7 +410,7 @@ msgid "" "Setting this value to anything other than ``None`` is discouraged." msgstr "" -#: library/dataclasses.rst:274 +#: library/dataclasses.rst:286 msgid "" "One possible reason to set ``hash=False`` but ``compare=True`` would be if a " "field is expensive to compute a hash value for, that field is needed for " @@ -344,14 +419,14 @@ msgid "" "used for comparisons." msgstr "" -#: library/dataclasses.rst:280 +#: library/dataclasses.rst:292 msgid "" "*compare*: If true (the default), this field is included in the generated " "equality and comparison methods (:meth:`~object.__eq__`, :meth:`~object." "__gt__`, et al.)." msgstr "" -#: library/dataclasses.rst:284 +#: library/dataclasses.rst:296 msgid "" "*metadata*: This can be a mapping or ``None``. ``None`` is treated as an " "empty dict. This value is wrapped in :func:`~types.MappingProxyType` to " @@ -361,13 +436,13 @@ msgid "" "namespace in the metadata." msgstr "" -#: library/dataclasses.rst:292 +#: library/dataclasses.rst:304 msgid "" "*kw_only*: If true, this field will be marked as keyword-only. This is used " "when the generated :meth:`~object.__init__` method's parameters are computed." msgstr "" -#: library/dataclasses.rst:298 +#: library/dataclasses.rst:310 msgid "" "If the default value of a field is specified by a call to :func:`!field`, " "then the class attribute for this field will be replaced by the specified " @@ -378,14 +453,24 @@ msgid "" "specified. For example, after::" msgstr "" -#: library/dataclasses.rst:314 +#: library/dataclasses.rst:319 +msgid "" +"@dataclass\n" +"class C:\n" +" x: int\n" +" y: int = field(repr=False)\n" +" z: int = field(repr=False, default=10)\n" +" t: int = 20" +msgstr "" + +#: library/dataclasses.rst:326 msgid "" "The class attribute :attr:`!C.z` will be ``10``, the class attribute :attr:`!" "C.t` will be ``20``, and the class attributes :attr:`!C.x` and :attr:`!C.y` " "will not be set." msgstr "" -#: library/dataclasses.rst:320 +#: library/dataclasses.rst:332 msgid "" ":class:`!Field` objects describe each defined field. These objects are " "created internally, and are returned by the :func:`fields` module-level " @@ -393,28 +478,28 @@ msgid "" "directly. Its documented attributes are:" msgstr "" -#: library/dataclasses.rst:325 +#: library/dataclasses.rst:337 msgid ":attr:`!name`: The name of the field." msgstr "" -#: library/dataclasses.rst:326 +#: library/dataclasses.rst:338 msgid ":attr:`!type`: The type of the field." msgstr "" -#: library/dataclasses.rst:327 +#: library/dataclasses.rst:339 msgid "" ":attr:`!default`, :attr:`!default_factory`, :attr:`!init`, :attr:`!repr`, :" "attr:`!hash`, :attr:`!compare`, :attr:`!metadata`, and :attr:`!kw_only` have " "the identical meaning and values as they do in the :func:`field` function." msgstr "" -#: library/dataclasses.rst:331 +#: library/dataclasses.rst:343 msgid "" "Other attributes may exist, but they are private and must not be inspected " "or relied on." msgstr "" -#: library/dataclasses.rst:336 +#: library/dataclasses.rst:348 msgid "" "Returns a tuple of :class:`Field` objects that define the fields for this " "dataclass. Accepts either a dataclass, or an instance of a dataclass. " @@ -422,7 +507,7 @@ msgid "" "not return pseudo-fields which are ``ClassVar`` or ``InitVar``." msgstr "" -#: library/dataclasses.rst:343 +#: library/dataclasses.rst:355 msgid "" "Converts the dataclass *obj* to a dict (by using the factory function " "*dict_factory*). Each dataclass is converted to a dict of its fields, as " @@ -430,20 +515,42 @@ msgid "" "into. Other objects are copied with :func:`copy.deepcopy`." msgstr "" -#: library/dataclasses.rst:349 +#: library/dataclasses.rst:361 msgid "Example of using :func:`!asdict` on nested dataclasses::" msgstr "" -#: library/dataclasses.rst:386 +#: library/dataclasses.rst:363 +msgid "" +"@dataclass\n" +"class Point:\n" +" x: int\n" +" y: int\n" +"\n" +"@dataclass\n" +"class C:\n" +" mylist: list[Point]\n" +"\n" +"p = Point(10, 20)\n" +"assert asdict(p) == {'x': 10, 'y': 20}\n" +"\n" +"c = C([Point(0, 0), Point(10, 4)])\n" +"assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}" +msgstr "" + +#: library/dataclasses.rst:398 msgid "To create a shallow copy, the following workaround may be used::" msgstr "" -#: library/dataclasses.rst:370 +#: library/dataclasses.rst:380 +msgid "{field.name: getattr(obj, field.name) for field in fields(obj)}" +msgstr "" + +#: library/dataclasses.rst:382 msgid "" ":func:`!asdict` raises :exc:`TypeError` if *obj* is not a dataclass instance." msgstr "" -#: library/dataclasses.rst:375 +#: library/dataclasses.rst:387 msgid "" "Converts the dataclass *obj* to a tuple (by using the factory function " "*tuple_factory*). Each dataclass is converted to a tuple of its field " @@ -451,17 +558,27 @@ msgid "" "objects are copied with :func:`copy.deepcopy`." msgstr "" -#: library/dataclasses.rst:381 +#: library/dataclasses.rst:393 msgid "Continuing from the previous example::" msgstr "" -#: library/dataclasses.rst:390 +#: library/dataclasses.rst:395 +msgid "" +"assert astuple(p) == (10, 20)\n" +"assert astuple(c) == ([(0, 0), (10, 4)],)" +msgstr "" + +#: library/dataclasses.rst:400 +msgid "tuple(getattr(obj, field.name) for field in dataclasses.fields(obj))" +msgstr "" + +#: library/dataclasses.rst:402 msgid "" ":func:`!astuple` raises :exc:`TypeError` if *obj* is not a dataclass " "instance." msgstr "" -#: library/dataclasses.rst:395 +#: library/dataclasses.rst:407 msgid "" "Creates a new dataclass with name *cls_name*, fields as defined in *fields*, " "base classes as given in *bases*, and initialized with a namespace as given " @@ -473,13 +590,13 @@ msgid "" "`@dataclass `." msgstr "" -#: library/dataclasses.rst:405 +#: library/dataclasses.rst:417 msgid "" "If *module* is defined, the :attr:`!__module__` attribute of the dataclass " "is set to that value. By default, it is set to the module name of the caller." msgstr "" -#: library/dataclasses.rst:409 +#: library/dataclasses.rst:421 msgid "" "This function is not strictly required, because any Python mechanism for " "creating a new class with :attr:`!__annotations__` can then apply the :func:" @@ -487,11 +604,32 @@ msgid "" "This function is provided as a convenience. For example::" msgstr "" -#: library/dataclasses.rst:421 +#: library/dataclasses.rst:427 +msgid "" +"C = make_dataclass('C',\n" +" [('x', int),\n" +" 'y',\n" +" ('z', int, field(default=5))],\n" +" namespace={'add_one': lambda self: self.x + 1})" +msgstr "" + +#: library/dataclasses.rst:433 msgid "Is equivalent to::" msgstr "" -#: library/dataclasses.rst:434 +#: library/dataclasses.rst:435 +msgid "" +"@dataclass\n" +"class C:\n" +" x: int\n" +" y: 'typing.Any'\n" +" z: int = 5\n" +"\n" +" def add_one(self):\n" +" return self.x + 1" +msgstr "" + +#: library/dataclasses.rst:446 msgid "" "Creates a new object of the same type as *obj*, replacing fields with values " "from *changes*. If *obj* is not a Data Class, raises :exc:`TypeError`. If " @@ -499,27 +637,27 @@ msgid "" "`TypeError`." msgstr "" -#: library/dataclasses.rst:439 +#: library/dataclasses.rst:451 msgid "" "The newly returned object is created by calling the :meth:`~object.__init__` " "method of the dataclass. This ensures that :meth:`__post_init__`, if " "present, is also called." msgstr "" -#: library/dataclasses.rst:443 +#: library/dataclasses.rst:455 msgid "" "Init-only variables without default values, if any exist, must be specified " "on the call to :func:`!replace` so that they can be passed to :meth:`!" "__init__` and :meth:`__post_init__`." msgstr "" -#: library/dataclasses.rst:447 +#: library/dataclasses.rst:459 msgid "" "It is an error for *changes* to contain any fields that are defined as " "having ``init=False``. A :exc:`ValueError` will be raised in this case." msgstr "" -#: library/dataclasses.rst:451 +#: library/dataclasses.rst:463 msgid "" "Be forewarned about how ``init=False`` fields work during a call to :func:`!" "replace`. They are not copied from the source object, but rather are " @@ -530,24 +668,30 @@ msgid "" "instance copying." msgstr "" -#: library/dataclasses.rst:462 +#: library/dataclasses.rst:474 msgid "" "Return ``True`` if its parameter is a dataclass (including subclasses of a " "dataclass) or an instance of one, otherwise return ``False``." msgstr "" -#: library/dataclasses.rst:465 +#: library/dataclasses.rst:477 msgid "" "If you need to know if a class is an instance of a dataclass (and not a " "dataclass itself), then add a further check for ``not isinstance(obj, " "type)``::" msgstr "" -#: library/dataclasses.rst:474 +#: library/dataclasses.rst:481 +msgid "" +"def is_dataclass_instance(obj):\n" +" return is_dataclass(obj) and not isinstance(obj, type)" +msgstr "" + +#: library/dataclasses.rst:486 msgid "A sentinel value signifying a missing default or default_factory." msgstr "" -#: library/dataclasses.rst:478 +#: library/dataclasses.rst:490 msgid "" "A sentinel value used as a type annotation. Any fields after a pseudo-field " "with the type of :const:`!KW_ONLY` are marked as keyword-only fields. Note " @@ -558,30 +702,42 @@ msgid "" "the class is instantiated." msgstr "" -#: library/dataclasses.rst:487 +#: library/dataclasses.rst:499 msgid "" "In this example, the fields ``y`` and ``z`` will be marked as keyword-only " "fields::" msgstr "" -#: library/dataclasses.rst:498 +#: library/dataclasses.rst:501 +msgid "" +"@dataclass\n" +"class Point:\n" +" x: float\n" +" _: KW_ONLY\n" +" y: float\n" +" z: float\n" +"\n" +"p = Point(0, y=1.5, z=2.0)" +msgstr "" + +#: library/dataclasses.rst:510 msgid "" "In a single dataclass, it is an error to specify more than one field whose " "type is :const:`!KW_ONLY`." msgstr "" -#: library/dataclasses.rst:505 +#: library/dataclasses.rst:517 msgid "" "Raised when an implicitly defined :meth:`~object.__setattr__` or :meth:" "`~object.__delattr__` is called on a dataclass which was defined with " "``frozen=True``. It is a subclass of :exc:`AttributeError`." msgstr "" -#: library/dataclasses.rst:512 +#: library/dataclasses.rst:524 msgid "Post-init processing" msgstr "" -#: library/dataclasses.rst:516 +#: library/dataclasses.rst:528 msgid "" "When defined on the class, it will be called by the generated :meth:`~object." "__init__`, normally as :meth:`!self.__post_init__`. However, if any " @@ -591,13 +747,25 @@ msgid "" "automatically be called." msgstr "" -#: library/dataclasses.rst:523 +#: library/dataclasses.rst:535 msgid "" "Among other uses, this allows for initializing field values that depend on " "one or more other fields. For example::" msgstr "" -#: library/dataclasses.rst:535 +#: library/dataclasses.rst:538 +msgid "" +"@dataclass\n" +"class C:\n" +" a: float\n" +" b: float\n" +" c: float = field(init=False)\n" +"\n" +" def __post_init__(self):\n" +" self.c = self.a + self.b" +msgstr "" + +#: library/dataclasses.rst:547 msgid "" "The :meth:`~object.__init__` method generated by :func:`@dataclass " "` does not call base class :meth:`!__init__` methods. If the base " @@ -607,23 +775,38 @@ msgstr "" #: library/dataclasses.rst:552 msgid "" +"class Rectangle:\n" +" def __init__(self, height, width):\n" +" self.height = height\n" +" self.width = width\n" +"\n" +"@dataclass\n" +"class Square(Rectangle):\n" +" side: float\n" +"\n" +" def __post_init__(self):\n" +" super().__init__(self.side, self.side)" +msgstr "" + +#: library/dataclasses.rst:564 +msgid "" "Note, however, that in general the dataclass-generated :meth:`!__init__` " "methods don't need to be called, since the derived dataclass will take care " "of initializing all fields of any base class that is a dataclass itself." msgstr "" -#: library/dataclasses.rst:556 +#: library/dataclasses.rst:568 msgid "" "See the section below on init-only variables for ways to pass parameters to :" "meth:`!__post_init__`. Also see the warning about how :func:`replace` " "handles ``init=False`` fields." msgstr "" -#: library/dataclasses.rst:563 +#: library/dataclasses.rst:575 msgid "Class variables" msgstr "" -#: library/dataclasses.rst:565 +#: library/dataclasses.rst:577 msgid "" "One of the few places where :func:`@dataclass ` actually inspects " "the type of a field is to determine if a field is a class variable as " @@ -634,11 +817,11 @@ msgid "" "`fields` function." msgstr "" -#: library/dataclasses.rst:576 +#: library/dataclasses.rst:588 msgid "Init-only variables" msgstr "" -#: library/dataclasses.rst:578 +#: library/dataclasses.rst:590 msgid "" "Another place where :func:`@dataclass ` inspects a type " "annotation is to determine if a field is an init-only variable. It does " @@ -651,7 +834,7 @@ msgid "" "dataclasses." msgstr "" -#: library/dataclasses.rst:588 +#: library/dataclasses.rst:600 msgid "" "For example, suppose a field will be initialized from a database, if a value " "is not provided when creating the class::" @@ -659,15 +842,30 @@ msgstr "" #: library/dataclasses.rst:603 msgid "" +"@dataclass\n" +"class C:\n" +" i: int\n" +" j: int | None = None\n" +" database: InitVar[DatabaseType | None] = None\n" +"\n" +" def __post_init__(self, database):\n" +" if self.j is None and database is not None:\n" +" self.j = database.lookup('j')\n" +"\n" +"c = C(10, database=my_database)" +msgstr "" + +#: library/dataclasses.rst:615 +msgid "" "In this case, :func:`fields` will return :class:`Field` objects for :attr:`!" "i` and :attr:`!j`, but not for :attr:`!database`." msgstr "" -#: library/dataclasses.rst:609 +#: library/dataclasses.rst:621 msgid "Frozen instances" msgstr "" -#: library/dataclasses.rst:611 +#: library/dataclasses.rst:623 msgid "" "It is not possible to create truly immutable Python objects. However, by " "passing ``frozen=True`` to the :func:`@dataclass ` decorator you " @@ -676,18 +874,18 @@ msgid "" "methods will raise a :exc:`FrozenInstanceError` when invoked." msgstr "" -#: library/dataclasses.rst:617 +#: library/dataclasses.rst:629 msgid "" "There is a tiny performance penalty when using ``frozen=True``: :meth:" "`~object.__init__` cannot use simple assignment to initialize fields, and " "must use :meth:`!object.__setattr__`." msgstr "" -#: library/dataclasses.rst:626 +#: library/dataclasses.rst:638 msgid "Inheritance" msgstr "" -#: library/dataclasses.rst:628 +#: library/dataclasses.rst:640 msgid "" "When the dataclass is being created by the :func:`@dataclass ` " "decorator, it looks through all of the class's base classes in reverse MRO " @@ -699,24 +897,41 @@ msgid "" "order, derived classes override base classes. An example::" msgstr "" -#: library/dataclasses.rst:648 +#: library/dataclasses.rst:650 +msgid "" +"@dataclass\n" +"class Base:\n" +" x: Any = 15.0\n" +" y: int = 0\n" +"\n" +"@dataclass\n" +"class C(Base):\n" +" z: int = 10\n" +" x: int = 15" +msgstr "" + +#: library/dataclasses.rst:660 msgid "" "The final list of fields is, in order, :attr:`!x`, :attr:`!y`, :attr:`!z`. " "The final type of :attr:`!x` is :class:`int`, as specified in class :class:`!" "C`." msgstr "" -#: library/dataclasses.rst:651 +#: library/dataclasses.rst:663 msgid "" "The generated :meth:`~object.__init__` method for :class:`!C` will look " "like::" msgstr "" -#: library/dataclasses.rst:656 +#: library/dataclasses.rst:665 +msgid "def __init__(self, x: int = 15, y: int = 0, z: int = 10):" +msgstr "" + +#: library/dataclasses.rst:668 msgid "Re-ordering of keyword-only parameters in :meth:`!__init__`" msgstr "" -#: library/dataclasses.rst:658 +#: library/dataclasses.rst:670 msgid "" "After the parameters needed for :meth:`~object.__init__` are computed, any " "keyword-only parameters are moved to come after all regular (non-keyword-" @@ -724,7 +939,7 @@ msgid "" "implemented in Python: they must come after non-keyword-only parameters." msgstr "" -#: library/dataclasses.rst:664 +#: library/dataclasses.rst:676 msgid "" "In this example, :attr:`!Base.y`, :attr:`!Base.w`, and :attr:`!D.t` are " "keyword-only fields, and :attr:`!Base.x` and :attr:`!D.z` are regular " @@ -732,34 +947,59 @@ msgid "" msgstr "" #: library/dataclasses.rst:679 +msgid "" +"@dataclass\n" +"class Base:\n" +" x: Any = 15.0\n" +" _: KW_ONLY\n" +" y: int = 0\n" +" w: int = 1\n" +"\n" +"@dataclass\n" +"class D(Base):\n" +" z: int = 10\n" +" t: int = field(kw_only=True, default=0)" +msgstr "" + +#: library/dataclasses.rst:691 msgid "The generated :meth:`!__init__` method for :class:`!D` will look like::" msgstr "" -#: library/dataclasses.rst:683 +#: library/dataclasses.rst:693 +msgid "" +"def __init__(self, x: Any = 15.0, z: int = 10, *, y: int = 0, w: int = 1, t: " +"int = 0):" +msgstr "" + +#: library/dataclasses.rst:695 msgid "" "Note that the parameters have been re-ordered from how they appear in the " "list of fields: parameters derived from regular fields are followed by " "parameters derived from keyword-only fields." msgstr "" -#: library/dataclasses.rst:687 +#: library/dataclasses.rst:699 msgid "" "The relative ordering of keyword-only parameters is maintained in the re-" "ordered :meth:`!__init__` parameter list." msgstr "" -#: library/dataclasses.rst:692 +#: library/dataclasses.rst:704 msgid "Default factory functions" msgstr "" -#: library/dataclasses.rst:694 +#: library/dataclasses.rst:706 msgid "" "If a :func:`field` specifies a *default_factory*, it is called with zero " "arguments when a default value for the field is needed. For example, to " "create a new instance of a list, use::" msgstr "" -#: library/dataclasses.rst:700 +#: library/dataclasses.rst:710 +msgid "mylist: list = field(default_factory=list)" +msgstr "" + +#: library/dataclasses.rst:712 msgid "" "If a field is excluded from :meth:`~object.__init__` (using ``init=False``) " "and the field also specifies *default_factory*, then the default factory " @@ -768,11 +1008,11 @@ msgid "" "initial value." msgstr "" -#: library/dataclasses.rst:707 +#: library/dataclasses.rst:719 msgid "Mutable default values" msgstr "" -#: library/dataclasses.rst:709 +#: library/dataclasses.rst:721 msgid "" "Python stores default member variable values in class attributes. Consider " "this example, not using dataclasses::" @@ -780,19 +1020,55 @@ msgstr "" #: library/dataclasses.rst:724 msgid "" +"class C:\n" +" x = []\n" +" def add(self, element):\n" +" self.x.append(element)\n" +"\n" +"o1 = C()\n" +"o2 = C()\n" +"o1.add(1)\n" +"o2.add(2)\n" +"assert o1.x == [1, 2]\n" +"assert o1.x is o2.x" +msgstr "" + +#: library/dataclasses.rst:736 +msgid "" "Note that the two instances of class :class:`!C` share the same class " "variable :attr:`!x`, as expected." msgstr "" -#: library/dataclasses.rst:727 +#: library/dataclasses.rst:739 msgid "Using dataclasses, *if* this code was valid::" msgstr "" -#: library/dataclasses.rst:735 +#: library/dataclasses.rst:741 +msgid "" +"@dataclass\n" +"class D:\n" +" x: list = [] # This code raises ValueError\n" +" def add(self, element):\n" +" self.x.append(element)" +msgstr "" + +#: library/dataclasses.rst:747 msgid "it would generate code similar to::" msgstr "" -#: library/dataclasses.rst:746 +#: library/dataclasses.rst:749 +msgid "" +"class D:\n" +" x = []\n" +" def __init__(self, x=x):\n" +" self.x = x\n" +" def add(self, element):\n" +" self.x.append(element)\n" +"\n" +"assert D().x is D().x" +msgstr "" + +#: library/dataclasses.rst:758 msgid "" "This has the same issue as the original example using class :class:`!C`. " "That is, two instances of class :class:`!D` that do not specify a value for :" @@ -805,44 +1081,53 @@ msgid "" "partial solution, but it does protect against many common errors." msgstr "" -#: library/dataclasses.rst:757 +#: library/dataclasses.rst:769 msgid "" "Using default factory functions is a way to create new instances of mutable " "types as default values for fields::" msgstr "" -#: library/dataclasses.rst:766 +#: library/dataclasses.rst:772 +msgid "" +"@dataclass\n" +"class D:\n" +" x: list = field(default_factory=list)\n" +"\n" +"assert D().x is not D().x" +msgstr "" + +#: library/dataclasses.rst:778 msgid "" "Instead of looking for and disallowing objects of type :class:`list`, :class:" "`dict`, or :class:`set`, unhashable objects are now not allowed as default " "values. Unhashability is used to approximate mutability." msgstr "" -#: library/dataclasses.rst:773 +#: library/dataclasses.rst:785 msgid "Descriptor-typed fields" msgstr "" -#: library/dataclasses.rst:775 +#: library/dataclasses.rst:787 msgid "" "Fields that are assigned :ref:`descriptor objects ` as their " "default value have the following special behaviors:" msgstr "" -#: library/dataclasses.rst:778 +#: library/dataclasses.rst:790 msgid "" "The value for the field passed to the dataclass's :meth:`~object.__init__` " "method is passed to the descriptor's :meth:`~object.__set__` method rather " "than overwriting the descriptor object." msgstr "" -#: library/dataclasses.rst:782 +#: library/dataclasses.rst:794 msgid "" "Similarly, when getting or setting the field, the descriptor's :meth:" "`~object.__get__` or :meth:`!__set__` method is called rather than returning " "or overwriting the descriptor object." msgstr "" -#: library/dataclasses.rst:786 +#: library/dataclasses.rst:798 msgid "" "To determine whether a field contains a default value, :func:`@dataclass " "` will call the descriptor's :meth:`!__get__` method using its " @@ -852,7 +1137,36 @@ msgid "" "in this situation, no default value will be provided for the field." msgstr "" -#: library/dataclasses.rst:821 +#: library/dataclasses.rst:808 +msgid "" +"class IntConversionDescriptor:\n" +" def __init__(self, *, default):\n" +" self._default = default\n" +"\n" +" def __set_name__(self, owner, name):\n" +" self._name = \"_\" + name\n" +"\n" +" def __get__(self, obj, type):\n" +" if obj is None:\n" +" return self._default\n" +"\n" +" return getattr(obj, self._name, self._default)\n" +"\n" +" def __set__(self, obj, value):\n" +" setattr(obj, self._name, int(value))\n" +"\n" +"@dataclass\n" +"class InventoryItem:\n" +" quantity_on_hand: IntConversionDescriptor = " +"IntConversionDescriptor(default=100)\n" +"\n" +"i = InventoryItem()\n" +"print(i.quantity_on_hand) # 100\n" +"i.quantity_on_hand = 2.5 # calls __set__ with 2.5\n" +"print(i.quantity_on_hand) # 2" +msgstr "" + +#: library/dataclasses.rst:833 msgid "" "Note that if a field is annotated with a descriptor type, but is not " "assigned a descriptor object as its default value, the field will act like a " diff --git a/library/datetime.po b/library/datetime.po index cd1048a0e..2eb7a17cb 100644 --- a/library/datetime.po +++ b/library/datetime.po @@ -6,7 +6,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: 2024-04-15 00:06-0400\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -280,6 +280,17 @@ msgstr "Bu türdeki nesneler değiştirilemezdir." msgid "Subclass relationships::" msgstr "Alt sınıf ilişkileri::" +#: library/datetime.rst:157 +msgid "" +"object\n" +" timedelta\n" +" tzinfo\n" +" timezone\n" +" time\n" +" date\n" +" datetime" +msgstr "" + #: library/datetime.rst:166 msgid "Common Properties" msgstr "Ortak Özellikler" @@ -324,7 +335,9 @@ msgstr "" "bilinçsiz olabilir." #: library/datetime.rst:183 -msgid "A :class:`.datetime` object *d* is aware if both of the following hold:" +#, fuzzy +msgid "" +"A :class:`.datetime` object ``d`` is aware if both of the following hold:" msgstr "" "Bir :class:`.datetime` nesnesi *d* aşağıdakilerin her ikisi de geçerliyse " "bilinçlidir:" @@ -338,11 +351,13 @@ msgid "``d.tzinfo.utcoffset(d)`` does not return ``None``" msgstr "``d.tzinfo.utcoffset(d)``, ``None`` döndürmez" #: library/datetime.rst:188 -msgid "Otherwise, *d* is naive." +#, fuzzy +msgid "Otherwise, ``d`` is naive." msgstr "Aksi halde, *d* bilinçsizdir." #: library/datetime.rst:190 -msgid "A :class:`.time` object *t* is aware if both of the following hold:" +#, fuzzy +msgid "A :class:`.time` object ``t`` is aware if both of the following hold:" msgstr "" "Bir :class:`.time` nesnesi *t* aşağıdakilerin her ikisi de geçerliyse " "bilinçlidir:" @@ -356,7 +371,8 @@ msgid "``t.tzinfo.utcoffset(None)`` does not return ``None``." msgstr "``t.tzinfo.utcoffset(None)``, ``None`` döndürmez." #: library/datetime.rst:195 -msgid "Otherwise, *t* is naive." +#, fuzzy +msgid "Otherwise, ``t`` is naive." msgstr "Aksi takdirde, *t* bilinçsizdir." #: library/datetime.rst:197 @@ -443,6 +459,23 @@ msgstr "" "argümanların nasıl \"birleştirildiği\" ve sonuçta ortaya çıkan bu üç " "özelliğe normalleştirildiği gösterilmektedir::" +#: library/datetime.rst:232 +msgid "" +">>> from datetime import timedelta\n" +">>> delta = timedelta(\n" +"... days=50,\n" +"... seconds=27,\n" +"... microseconds=10,\n" +"... milliseconds=29000,\n" +"... minutes=5,\n" +"... hours=8,\n" +"... weeks=2\n" +"... )\n" +">>> # Only days, seconds, and microseconds remain\n" +">>> delta\n" +"datetime.timedelta(days=64, seconds=29156, microseconds=10)" +msgstr "" + #: library/datetime.rst:246 msgid "" "If any argument is a float and there are fractional microseconds, the " @@ -474,7 +507,15 @@ msgstr "" "Negatif değerlerin normalleştirilmesinin ilk başta şaşırtıcı olabileceğini " "unutmayın. Örneğin::" -#: library/datetime.rst:546 library/datetime.rst:1696 library/datetime.rst:2298 +#: library/datetime.rst:259 +msgid "" +">>> from datetime import timedelta\n" +">>> d = timedelta(microseconds=-1)\n" +">>> (d.days, d.seconds, d.microseconds)\n" +"(-1, 86399, 999999)" +msgstr "" + +#: library/datetime.rst:566 library/datetime.rst:1720 library/datetime.rst:2322 msgid "Class attributes:" msgstr "Sınıf özellikleri:" @@ -509,59 +550,59 @@ msgstr "" "dikkat edin. ``-timedelta.max`` bir :class:`timedelta` nesnesi olarak temsil " "edilemez." -#: library/datetime.rst:564 library/datetime.rst:1716 +#: library/datetime.rst:584 library/datetime.rst:1740 msgid "Instance attributes (read-only):" msgstr "Örnek özellikleri (salt okunur):" -#: library/datetime.rst:289 -msgid "Attribute" -msgstr "Özellik" - -#: library/datetime.rst:289 -msgid "Value" -msgstr "Değer" - -#: library/datetime.rst:291 -msgid "``days``" -msgstr "``days``" - #: library/datetime.rst:291 -msgid "Between -999999999 and 999999999 inclusive" +#, fuzzy +msgid "Between -999,999,999 and 999,999,999 inclusive." msgstr "999999999 ile -999999999 dahil arasında" -#: library/datetime.rst:293 -msgid "``seconds``" -msgstr "``seconds``" - -#: library/datetime.rst:293 -msgid "Between 0 and 86399 inclusive" +#: library/datetime.rst:296 +#, fuzzy +msgid "Between 0 and 86,399 inclusive." msgstr "0 ile 86399 dahil arasında" -#: library/datetime.rst:295 -msgid "``microseconds``" -msgstr "``microseconds``" +#: library/datetime.rst:300 +msgid "" +"It is a somewhat common bug for code to unintentionally use this attribute " +"when it is actually intended to get a :meth:`~timedelta.total_seconds` value " +"instead:" +msgstr "" + +#: library/datetime.rst:304 +msgid "" +">>> from datetime import timedelta\n" +">>> duration = timedelta(seconds=11235813)\n" +">>> duration.days, duration.seconds\n" +"(130, 3813)\n" +">>> duration.total_seconds()\n" +"11235813.0" +msgstr "" -#: library/datetime.rst:295 -msgid "Between 0 and 999999 inclusive" +#: library/datetime.rst:315 +#, fuzzy +msgid "Between 0 and 999,999 inclusive." msgstr "0 ile 999999 dahil arasında" -#: library/datetime.rst:581 library/datetime.rst:1138 +#: library/datetime.rst:601 library/datetime.rst:1162 msgid "Supported operations:" msgstr "Desteklenen operasyonlar:" -#: library/datetime.rst:584 library/datetime.rst:1141 +#: library/datetime.rst:604 library/datetime.rst:1165 msgid "Operation" msgstr "Operasyon" -#: library/datetime.rst:584 library/datetime.rst:1141 +#: library/datetime.rst:604 library/datetime.rst:1165 msgid "Result" msgstr "Sonuç" -#: library/datetime.rst:305 +#: library/datetime.rst:325 msgid "``t1 = t2 + t3``" msgstr "``t1 = t2 + t3``" -#: library/datetime.rst:305 +#: library/datetime.rst:325 #, fuzzy msgid "" "Sum of ``t2`` and ``t3``. Afterwards ``t1 - t2 == t3`` and ``t1 - t3 == t2`` " @@ -570,11 +611,11 @@ msgstr "" "*t2* ve *t3* 'ün toplamıdır. Daha sonra *t1*-*t2* == *t3* ve *t1*-*t3* == " "*t2* doğrudur. (1)" -#: library/datetime.rst:309 +#: library/datetime.rst:329 msgid "``t1 = t2 - t3``" msgstr "``t1 = t2 - t3``" -#: library/datetime.rst:309 +#: library/datetime.rst:329 #, fuzzy msgid "" "Difference of ``t2`` and ``t3``. Afterwards ``t1 == t2 - t3`` and ``t2 == " @@ -583,143 +624,143 @@ msgstr "" "*t2* ve *t3* 'ün farkı. Daha sonra *t1* == *t2* - *t3* ve *t2* == *t1* + " "*t3* doğrudur. (1)(6)" -#: library/datetime.rst:313 +#: library/datetime.rst:333 msgid "``t1 = t2 * i or t1 = i * t2``" msgstr "" -#: library/datetime.rst:313 +#: library/datetime.rst:333 msgid "" "Delta multiplied by an integer. Afterwards ``t1 // i == t2`` is true, " "provided ``i != 0``." msgstr "" -#: library/datetime.rst:317 +#: library/datetime.rst:337 msgid "In general, ``t1 * i == t1 * (i-1) + t1`` is true. (1)" msgstr "" -#: library/datetime.rst:320 +#: library/datetime.rst:340 msgid "``t1 = t2 * f or t1 = f * t2``" msgstr "" -#: library/datetime.rst:320 +#: library/datetime.rst:340 msgid "" "Delta multiplied by a float. The result is rounded to the nearest multiple " "of timedelta.resolution using round-half-to-even." msgstr "" -#: library/datetime.rst:324 +#: library/datetime.rst:344 msgid "``f = t2 / t3``" msgstr "" -#: library/datetime.rst:324 +#: library/datetime.rst:344 msgid "" "Division (3) of overall duration ``t2`` by interval unit ``t3``. Returns a :" "class:`float` object." msgstr "" -#: library/datetime.rst:328 +#: library/datetime.rst:348 msgid "``t1 = t2 / f or t1 = t2 / i``" msgstr "" -#: library/datetime.rst:328 +#: library/datetime.rst:348 msgid "" "Delta divided by a float or an int. The result is rounded to the nearest " "multiple of timedelta.resolution using round-half-to-even." msgstr "" -#: library/datetime.rst:332 +#: library/datetime.rst:352 msgid "``t1 = t2 // i`` or ``t1 = t2 // t3``" msgstr "" -#: library/datetime.rst:332 +#: library/datetime.rst:352 msgid "" "The floor is computed and the remainder (if any) is thrown away. In the " "second case, an integer is returned. (3)" msgstr "" -#: library/datetime.rst:336 +#: library/datetime.rst:356 msgid "``t1 = t2 % t3``" msgstr "" -#: library/datetime.rst:336 +#: library/datetime.rst:356 msgid "The remainder is computed as a :class:`timedelta` object. (3)" msgstr "" -#: library/datetime.rst:339 +#: library/datetime.rst:359 msgid "``q, r = divmod(t1, t2)``" msgstr "" -#: library/datetime.rst:339 +#: library/datetime.rst:359 msgid "" "Computes the quotient and the remainder: ``q = t1 // t2`` (3) and ``r = t1 % " -"t2``. q is an integer and r is a :class:`timedelta` object." +"t2``. ``q`` is an integer and ``r`` is a :class:`timedelta` object." msgstr "" -#: library/datetime.rst:344 +#: library/datetime.rst:364 msgid "``+t1``" msgstr "" -#: library/datetime.rst:344 +#: library/datetime.rst:364 msgid "Returns a :class:`timedelta` object with the same value. (2)" msgstr "" -#: library/datetime.rst:347 +#: library/datetime.rst:367 msgid "``-t1``" msgstr "" -#: library/datetime.rst:347 +#: library/datetime.rst:367 msgid "" -"Equivalent to ``timedelta(-t1.days, -t1.seconds*, -t1.microseconds)``, and " -"to ``t1 * -1``. (1)(4)" +"Equivalent to ``timedelta(-t1.days, -t1.seconds, -t1.microseconds)``, and to " +"``t1 * -1``. (1)(4)" msgstr "" -#: library/datetime.rst:351 +#: library/datetime.rst:371 msgid "``abs(t)``" msgstr "" -#: library/datetime.rst:351 +#: library/datetime.rst:371 msgid "" "Equivalent to ``+t`` when ``t.days >= 0``, and to ``-t`` when ``t.days < " "0``. (2)" msgstr "" -#: library/datetime.rst:354 +#: library/datetime.rst:374 msgid "``str(t)``" msgstr "" -#: library/datetime.rst:354 +#: library/datetime.rst:374 msgid "" "Returns a string in the form ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D is " "negative for negative ``t``. (5)" msgstr "" -#: library/datetime.rst:358 +#: library/datetime.rst:378 msgid "``repr(t)``" msgstr "" -#: library/datetime.rst:358 +#: library/datetime.rst:378 msgid "" "Returns a string representation of the :class:`timedelta` object as a " "constructor call with canonical attribute values." msgstr "" -#: library/datetime.rst:603 library/datetime.rst:2529 +#: library/datetime.rst:623 library/datetime.rst:2553 msgid "Notes:" msgstr "" -#: library/datetime.rst:367 +#: library/datetime.rst:387 msgid "This is exact but may overflow." msgstr "" -#: library/datetime.rst:370 +#: library/datetime.rst:390 msgid "This is exact and cannot overflow." msgstr "" -#: library/datetime.rst:373 +#: library/datetime.rst:393 msgid "Division by zero raises :exc:`ZeroDivisionError`." msgstr "" -#: library/datetime.rst:376 +#: library/datetime.rst:396 #, fuzzy msgid "``-timedelta.max`` is not representable as a :class:`timedelta` object." msgstr "" @@ -727,28 +768,36 @@ msgstr "" "dikkat edin. ``-timedelta.max`` bir :class:`timedelta` nesnesi olarak temsil " "edilemez." -#: library/datetime.rst:379 +#: library/datetime.rst:399 msgid "" "String representations of :class:`timedelta` objects are normalized " "similarly to their internal representation. This leads to somewhat unusual " "results for negative timedeltas. For example::" msgstr "" -#: library/datetime.rst:389 +#: library/datetime.rst:403 +msgid "" +">>> timedelta(hours=-5)\n" +"datetime.timedelta(days=-1, seconds=68400)\n" +">>> print(_)\n" +"-1 day, 19:00:00" +msgstr "" + +#: library/datetime.rst:409 msgid "" "The expression ``t2 - t3`` will always be equal to the expression ``t2 + (-" "t3)`` except when t3 is equal to ``timedelta.max``; in that case the former " "will produce a result while the latter will overflow." msgstr "" -#: library/datetime.rst:393 +#: library/datetime.rst:413 msgid "" "In addition to the operations listed above, :class:`timedelta` objects " "support certain additions and subtractions with :class:`date` and :class:`." "datetime` objects (see below)." msgstr "" -#: library/datetime.rst:397 +#: library/datetime.rst:417 msgid "" "Floor division and true division of a :class:`timedelta` object by another :" "class:`timedelta` object are now supported, as are remainder operations and " @@ -756,104 +805,134 @@ msgid "" "`timedelta` object by a :class:`float` object are now supported." msgstr "" -#: library/datetime.rst:403 +#: library/datetime.rst:423 msgid ":class:`timedelta` objects support equality and order comparisons." msgstr "" -#: library/datetime.rst:405 +#: library/datetime.rst:425 msgid "" "In Boolean contexts, a :class:`timedelta` object is considered to be true if " "and only if it isn't equal to ``timedelta(0)``." msgstr "" -#: library/datetime.rst:629 library/datetime.rst:1823 +#: library/datetime.rst:649 library/datetime.rst:1847 msgid "Instance methods:" msgstr "" -#: library/datetime.rst:412 +#: library/datetime.rst:432 msgid "" "Return the total number of seconds contained in the duration. Equivalent to " "``td / timedelta(seconds=1)``. For interval units other than seconds, use " "the division form directly (e.g. ``td / timedelta(microseconds=1)``)." msgstr "" -#: library/datetime.rst:416 +#: library/datetime.rst:436 msgid "" "Note that for very large time intervals (greater than 270 years on most " "platforms) this method will lose microsecond accuracy." msgstr "" -#: library/datetime.rst:422 +#: library/datetime.rst:442 msgid "Examples of usage: :class:`timedelta`" msgstr "" -#: library/datetime.rst:424 +#: library/datetime.rst:444 msgid "An additional example of normalization::" msgstr "" -#: library/datetime.rst:436 +#: library/datetime.rst:446 +msgid "" +">>> # Components of another_year add up to exactly 365 days\n" +">>> from datetime import timedelta\n" +">>> year = timedelta(days=365)\n" +">>> another_year = timedelta(weeks=40, days=84, hours=23,\n" +"... minutes=50, seconds=600)\n" +">>> year == another_year\n" +"True\n" +">>> year.total_seconds()\n" +"31536000.0" +msgstr "" + +#: library/datetime.rst:456 msgid "Examples of :class:`timedelta` arithmetic::" msgstr "" -#: library/datetime.rst:455 +#: library/datetime.rst:458 +msgid "" +">>> from datetime import timedelta\n" +">>> year = timedelta(days=365)\n" +">>> ten_years = 10 * year\n" +">>> ten_years\n" +"datetime.timedelta(days=3650)\n" +">>> ten_years.days // 365\n" +"10\n" +">>> nine_years = ten_years - year\n" +">>> nine_years\n" +"datetime.timedelta(days=3285)\n" +">>> three_years = nine_years // 3\n" +">>> three_years, three_years.days // 365\n" +"(datetime.timedelta(days=1095), 3)" +msgstr "" + +#: library/datetime.rst:475 msgid ":class:`date` Objects" msgstr "" -#: library/datetime.rst:457 +#: library/datetime.rst:477 msgid "" "A :class:`date` object represents a date (year, month and day) in an " "idealized calendar, the current Gregorian calendar indefinitely extended in " "both directions." msgstr "" -#: library/datetime.rst:461 +#: library/datetime.rst:481 msgid "" "January 1 of year 1 is called day number 1, January 2 of year 1 is called " "day number 2, and so on. [#]_" msgstr "" -#: library/datetime.rst:466 +#: library/datetime.rst:486 msgid "" "All arguments are required. Arguments must be integers, in the following " "ranges:" msgstr "" -#: library/datetime.rst:469 +#: library/datetime.rst:489 msgid "``MINYEAR <= year <= MAXYEAR``" msgstr "" -#: library/datetime.rst:470 +#: library/datetime.rst:490 msgid "``1 <= month <= 12``" msgstr "" -#: library/datetime.rst:471 +#: library/datetime.rst:491 msgid "``1 <= day <= number of days in the given month and year``" msgstr "" -#: library/datetime.rst:844 +#: library/datetime.rst:864 msgid "" "If an argument outside those ranges is given, :exc:`ValueError` is raised." msgstr "" -#: library/datetime.rst:849 +#: library/datetime.rst:869 msgid "Other constructors, all class methods:" msgstr "" -#: library/datetime.rst:480 +#: library/datetime.rst:500 msgid "Return the current local date." msgstr "" -#: library/datetime.rst:482 +#: library/datetime.rst:502 msgid "This is equivalent to ``date.fromtimestamp(time.time())``." msgstr "" -#: library/datetime.rst:486 +#: library/datetime.rst:506 msgid "" "Return the local date corresponding to the POSIX timestamp, such as is " "returned by :func:`time.time`." msgstr "" -#: library/datetime.rst:489 +#: library/datetime.rst:509 msgid "" "This may raise :exc:`OverflowError`, if the timestamp is out of the range of " "values supported by the platform C :c:func:`localtime` function, and :exc:" @@ -863,7 +942,7 @@ msgid "" "ignored by :meth:`fromtimestamp`." msgstr "" -#: library/datetime.rst:496 +#: library/datetime.rst:516 msgid "" "Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp is " "out of the range of values supported by the platform C :c:func:`localtime` " @@ -871,101 +950,112 @@ msgid "" "`localtime` failure." msgstr "" -#: library/datetime.rst:505 +#: library/datetime.rst:525 msgid "" "Return the date corresponding to the proleptic Gregorian ordinal, where " "January 1 of year 1 has ordinal 1." msgstr "" -#: library/datetime.rst:508 +#: library/datetime.rst:528 msgid "" ":exc:`ValueError` is raised unless ``1 <= ordinal <= date.max.toordinal()``. " -"For any date *d*, ``date.fromordinal(d.toordinal()) == d``." +"For any date ``d``, ``date.fromordinal(d.toordinal()) == d``." msgstr "" -#: library/datetime.rst:515 +#: library/datetime.rst:535 msgid "" "Return a :class:`date` corresponding to a *date_string* given in any valid " "ISO 8601 format, with the following exceptions:" msgstr "" -#: library/datetime.rst:1005 +#: library/datetime.rst:1029 msgid "" "Reduced precision dates are not currently supported (``YYYY-MM``, ``YYYY``)." msgstr "" -#: library/datetime.rst:1007 +#: library/datetime.rst:1031 msgid "" "Extended date representations are not currently supported (``±YYYYYY-MM-" "DD``)." msgstr "" -#: library/datetime.rst:1009 +#: library/datetime.rst:1033 msgid "Ordinal dates are not currently supported (``YYYY-OOO``)." msgstr "" -#: library/datetime.rst:1011 library/datetime.rst:1452 +#: library/datetime.rst:1035 library/datetime.rst:1476 msgid "Examples::" msgstr "" -#: library/datetime.rst:535 +#: library/datetime.rst:546 +msgid "" +">>> from datetime import date\n" +">>> date.fromisoformat('2019-12-04')\n" +"datetime.date(2019, 12, 4)\n" +">>> date.fromisoformat('20191204')\n" +"datetime.date(2019, 12, 4)\n" +">>> date.fromisoformat('2021-W01-1')\n" +"datetime.date(2021, 1, 4)" +msgstr "" + +#: library/datetime.rst:555 msgid "Previously, this method only supported the format ``YYYY-MM-DD``." msgstr "" -#: library/datetime.rst:540 +#: library/datetime.rst:560 msgid "" "Return a :class:`date` corresponding to the ISO calendar date specified by " "year, week and day. This is the inverse of the function :meth:`date." "isocalendar`." msgstr "" -#: library/datetime.rst:550 +#: library/datetime.rst:570 msgid "The earliest representable date, ``date(MINYEAR, 1, 1)``." msgstr "" -#: library/datetime.rst:555 +#: library/datetime.rst:575 msgid "The latest representable date, ``date(MAXYEAR, 12, 31)``." msgstr "" -#: library/datetime.rst:560 +#: library/datetime.rst:580 msgid "" "The smallest possible difference between non-equal date objects, " "``timedelta(days=1)``." msgstr "" -#: library/datetime.rst:1089 +#: library/datetime.rst:1113 msgid "Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive." msgstr "" -#: library/datetime.rst:1094 +#: library/datetime.rst:1118 msgid "Between 1 and 12 inclusive." msgstr "" -#: library/datetime.rst:1099 +#: library/datetime.rst:1123 msgid "Between 1 and the number of days in the given month of the given year." msgstr "" -#: library/datetime.rst:586 +#: library/datetime.rst:606 msgid "``date2 = date1 + timedelta``" msgstr "" -#: library/datetime.rst:586 +#: library/datetime.rst:606 msgid "``date2`` will be ``timedelta.days`` days after ``date1``. (1)" msgstr "" -#: library/datetime.rst:589 +#: library/datetime.rst:609 msgid "``date2 = date1 - timedelta``" msgstr "" -#: library/datetime.rst:589 +#: library/datetime.rst:609 msgid "Computes ``date2`` such that ``date2 + timedelta == date1``. (2)" msgstr "" -#: library/datetime.rst:592 +#: library/datetime.rst:612 msgid "``timedelta = date1 - date2``" msgstr "" -#: library/datetime.rst:1147 +#: library/datetime.rst:1171 msgid "\\(3)" msgstr "" @@ -977,7 +1067,7 @@ msgstr "" msgid "``date1 != date2``" msgstr "" -#: library/datetime.rst:1149 +#: library/datetime.rst:1173 msgid "Equality comparison. (4)" msgstr "" @@ -997,11 +1087,11 @@ msgstr "" msgid "``date1 >= date2``" msgstr "" -#: library/datetime.rst:1152 +#: library/datetime.rst:1176 msgid "Order comparison. (5)" msgstr "" -#: library/datetime.rst:606 +#: library/datetime.rst:626 msgid "" "*date2* is moved forward in time if ``timedelta.days > 0``, or backward if " "``timedelta.days < 0``. Afterward ``date2 - date1 == timedelta.days``. " @@ -1010,95 +1100,108 @@ msgid "" "`MINYEAR` or larger than :const:`MAXYEAR`." msgstr "" -#: library/datetime.rst:613 +#: library/datetime.rst:633 msgid "``timedelta.seconds`` and ``timedelta.microseconds`` are ignored." msgstr "" -#: library/datetime.rst:616 +#: library/datetime.rst:636 msgid "" "This is exact, and cannot overflow. ``timedelta.seconds`` and ``timedelta." "microseconds`` are 0, and ``date2 + timedelta == date1`` after." msgstr "" -#: library/datetime.rst:620 +#: library/datetime.rst:640 msgid ":class:`date` objects are equal if they represent the same date." msgstr "" -#: library/datetime.rst:623 +#: library/datetime.rst:643 msgid "" "*date1* is considered less than *date2* when *date1* precedes *date2* in " "time. In other words, ``date1 < date2`` if and only if ``date1.toordinal() < " "date2.toordinal()``." msgstr "" -#: library/datetime.rst:627 +#: library/datetime.rst:647 msgid "" "In Boolean contexts, all :class:`date` objects are considered to be true." msgstr "" -#: library/datetime.rst:633 +#: library/datetime.rst:653 msgid "" "Return a date with the same value, except for those parameters given new " "values by whichever keyword arguments are specified." msgstr "" -#: library/datetime.rst:1866 +#: library/datetime.rst:1890 msgid "Example::" msgstr "" -#: library/datetime.rst:1337 +#: library/datetime.rst:658 +msgid "" +">>> from datetime import date\n" +">>> d = date(2002, 12, 31)\n" +">>> d.replace(day=26)\n" +"datetime.date(2002, 12, 26)" +msgstr "" + +#: library/datetime.rst:1361 msgid "" "Return a :class:`time.struct_time` such as returned by :func:`time." "localtime`." msgstr "" -#: library/datetime.rst:648 +#: library/datetime.rst:668 msgid "The hours, minutes and seconds are 0, and the DST flag is -1." msgstr "" -#: library/datetime.rst:1339 +#: library/datetime.rst:1363 msgid "``d.timetuple()`` is equivalent to::" msgstr "" -#: library/datetime.rst:654 +#: library/datetime.rst:672 +msgid "" +"time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1))" +msgstr "" + +#: library/datetime.rst:674 msgid "" "where ``yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the " "day number within the current year starting with 1 for January 1st." msgstr "" -#: library/datetime.rst:660 +#: library/datetime.rst:680 msgid "" "Return the proleptic Gregorian ordinal of the date, where January 1 of year " -"1 has ordinal 1. For any :class:`date` object *d*, ``date.fromordinal(d." +"1 has ordinal 1. For any :class:`date` object ``d``, ``date.fromordinal(d." "toordinal()) == d``." msgstr "" -#: library/datetime.rst:667 +#: library/datetime.rst:687 msgid "" "Return the day of the week as an integer, where Monday is 0 and Sunday is 6. " "For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also :" "meth:`isoweekday`." msgstr "" -#: library/datetime.rst:674 +#: library/datetime.rst:694 msgid "" "Return the day of the week as an integer, where Monday is 1 and Sunday is 7. " "For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also :" "meth:`weekday`, :meth:`isocalendar`." msgstr "" -#: library/datetime.rst:681 +#: library/datetime.rst:701 msgid "" "Return a :term:`named tuple` object with three components: ``year``, " "``week`` and ``weekday``." msgstr "" -#: library/datetime.rst:684 +#: library/datetime.rst:704 msgid "" "The ISO calendar is a widely used variant of the Gregorian calendar. [#]_" msgstr "" -#: library/datetime.rst:686 +#: library/datetime.rst:706 msgid "" "The ISO year consists of 52 or 53 full weeks, and where a week starts on a " "Monday and ends on a Sunday. The first week of an ISO year is the first " @@ -1107,41 +1210,68 @@ msgid "" "Gregorian year." msgstr "" -#: library/datetime.rst:691 +#: library/datetime.rst:711 msgid "" "For example, 2004 begins on a Thursday, so the first week of ISO year 2004 " "begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004::" msgstr "" -#: library/datetime.rst:700 +#: library/datetime.rst:714 +msgid "" +">>> from datetime import date\n" +">>> date(2003, 12, 29).isocalendar()\n" +"datetime.IsoCalendarDate(year=2004, week=1, weekday=1)\n" +">>> date(2004, 1, 4).isocalendar()\n" +"datetime.IsoCalendarDate(year=2004, week=1, weekday=7)" +msgstr "" + +#: library/datetime.rst:720 msgid "Result changed from a tuple to a :term:`named tuple`." msgstr "" -#: library/datetime.rst:705 +#: library/datetime.rst:725 msgid "" "Return a string representing the date in ISO 8601 format, ``YYYY-MM-DD``::" msgstr "" -#: library/datetime.rst:713 -msgid "For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``." +#: library/datetime.rst:727 +msgid "" +">>> from datetime import date\n" +">>> date(2002, 12, 4).isoformat()\n" +"'2002-12-04'" +msgstr "" + +#: library/datetime.rst:733 +msgid "For a date ``d``, ``str(d)`` is equivalent to ``d.isoformat()``." msgstr "" -#: library/datetime.rst:718 +#: library/datetime.rst:738 msgid "Return a string representing the date::" msgstr "" -#: library/datetime.rst:1523 +#: library/datetime.rst:740 +msgid "" +">>> from datetime import date\n" +">>> date(2002, 12, 4).ctime()\n" +"'Wed Dec 4 00:00:00 2002'" +msgstr "" + +#: library/datetime.rst:1547 msgid "``d.ctime()`` is equivalent to::" msgstr "" -#: library/datetime.rst:728 +#: library/datetime.rst:1549 +msgid "time.ctime(time.mktime(d.timetuple()))" +msgstr "" + +#: library/datetime.rst:748 msgid "" "on platforms where the native C :c:func:`ctime` function (which :func:`time." "ctime` invokes, but which :meth:`date.ctime` does not invoke) conforms to " "the C standard." msgstr "" -#: library/datetime.rst:735 +#: library/datetime.rst:755 msgid "" "Return a string representing the date, controlled by an explicit format " "string. Format codes referring to hours, minutes or seconds will see 0 " @@ -1149,7 +1279,7 @@ msgid "" "isoformat`." msgstr "" -#: library/datetime.rst:742 +#: library/datetime.rst:762 msgid "" "Same as :meth:`.date.strftime`. This makes it possible to specify a format " "string for a :class:`.date` object in :ref:`formatted string literals >> import time\n" +">>> from datetime import date\n" +">>> today = date.today()\n" +">>> today\n" +"datetime.date(2007, 12, 5)\n" +">>> today == date.fromtimestamp(time.time())\n" +"True\n" +">>> my_birthday = date(today.year, 6, 24)\n" +">>> if my_birthday < today:\n" +"... my_birthday = my_birthday.replace(year=today.year + 1)\n" +"...\n" +">>> my_birthday\n" +"datetime.date(2008, 6, 24)\n" +">>> time_to_birthday = abs(my_birthday - today)\n" +">>> time_to_birthday.days\n" +"202" +msgstr "" + +#: library/datetime.rst:789 msgid "More examples of working with :class:`date`:" msgstr "" -#: library/datetime.rst:818 +#: library/datetime.rst:791 +msgid "" +">>> from datetime import date\n" +">>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001\n" +">>> d\n" +"datetime.date(2002, 3, 11)\n" +"\n" +">>> # Methods related to formatting string output\n" +">>> d.isoformat()\n" +"'2002-03-11'\n" +">>> d.strftime(\"%d/%m/%y\")\n" +"'11/03/02'\n" +">>> d.strftime(\"%A %d. %B %Y\")\n" +"'Monday 11. March 2002'\n" +">>> d.ctime()\n" +"'Mon Mar 11 00:00:00 2002'\n" +">>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, \"day\", \"month\")\n" +"'The day is 11, the month is March.'\n" +"\n" +">>> # Methods for to extracting 'components' under different calendars\n" +">>> t = d.timetuple()\n" +">>> for i in t: \n" +"... print(i)\n" +"2002 # year\n" +"3 # month\n" +"11 # day\n" +"0\n" +"0\n" +"0\n" +"0 # weekday (0 = Monday)\n" +"70 # 70th day in the year\n" +"-1\n" +">>> ic = d.isocalendar()\n" +">>> for i in ic: \n" +"... print(i)\n" +"2002 # ISO year\n" +"11 # ISO week number\n" +"1 # ISO day number ( 1 = Monday )\n" +"\n" +">>> # A date object is immutable; all operations produce a new object\n" +">>> d.replace(year=2005)\n" +"datetime.date(2005, 3, 11)" +msgstr "" + +#: library/datetime.rst:838 msgid ":class:`.datetime` Objects" msgstr "" -#: library/datetime.rst:820 +#: library/datetime.rst:840 msgid "" "A :class:`.datetime` object is a single object containing all the " "information from a :class:`date` object and a :class:`.time` object." msgstr "" -#: library/datetime.rst:823 +#: library/datetime.rst:843 msgid "" "Like a :class:`date` object, :class:`.datetime` assumes the current " "Gregorian calendar extended in both directions; like a :class:`.time` " @@ -1187,76 +1381,80 @@ msgid "" "every day." msgstr "" -#: library/datetime.rst:827 +#: library/datetime.rst:847 msgid "Constructor:" msgstr "" -#: library/datetime.rst:831 +#: library/datetime.rst:851 msgid "" "The *year*, *month* and *day* arguments are required. *tzinfo* may be " "``None``, or an instance of a :class:`tzinfo` subclass. The remaining " "arguments must be integers in the following ranges:" msgstr "" -#: library/datetime.rst:835 +#: library/datetime.rst:855 msgid "``MINYEAR <= year <= MAXYEAR``," msgstr "" -#: library/datetime.rst:836 +#: library/datetime.rst:856 msgid "``1 <= month <= 12``," msgstr "" -#: library/datetime.rst:837 +#: library/datetime.rst:857 msgid "``1 <= day <= number of days in the given month and year``," msgstr "" -#: library/datetime.rst:1687 +#: library/datetime.rst:1711 msgid "``0 <= hour < 24``," msgstr "" -#: library/datetime.rst:1688 +#: library/datetime.rst:1712 msgid "``0 <= minute < 60``," msgstr "" -#: library/datetime.rst:1689 +#: library/datetime.rst:1713 msgid "``0 <= second < 60``," msgstr "" -#: library/datetime.rst:1690 +#: library/datetime.rst:1714 msgid "``0 <= microsecond < 1000000``," msgstr "" -#: library/datetime.rst:1691 +#: library/datetime.rst:1715 msgid "``fold in [0, 1]``." msgstr "" -#: library/datetime.rst:1258 library/datetime.rst:1833 +#: library/datetime.rst:1282 library/datetime.rst:1857 msgid "Added the *fold* parameter." msgstr "" -#: library/datetime.rst:853 +#: library/datetime.rst:873 msgid "Return the current local date and time, with :attr:`.tzinfo` ``None``." msgstr "" -#: library/datetime.rst:855 +#: library/datetime.rst:875 msgid "Equivalent to::" msgstr "" -#: library/datetime.rst:859 +#: library/datetime.rst:877 +msgid "datetime.fromtimestamp(time.time())" +msgstr "" + +#: library/datetime.rst:879 msgid "See also :meth:`now`, :meth:`fromtimestamp`." msgstr "" -#: library/datetime.rst:861 +#: library/datetime.rst:881 msgid "" "This method is functionally equivalent to :meth:`now`, but without a ``tz`` " "parameter." msgstr "" -#: library/datetime.rst:866 +#: library/datetime.rst:886 msgid "Return the current local date and time." msgstr "" -#: library/datetime.rst:868 +#: library/datetime.rst:888 msgid "" "If optional argument *tz* is ``None`` or not specified, this is like :meth:" "`today`, but, if possible, supplies more precision than can be gotten from " @@ -1264,28 +1462,34 @@ msgid "" "possible on platforms supplying the C :c:func:`gettimeofday` function)." msgstr "" -#: library/datetime.rst:874 +#: library/datetime.rst:894 msgid "" "If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` " "subclass, and the current date and time are converted to *tz*’s time zone." msgstr "" -#: library/datetime.rst:877 +#: library/datetime.rst:897 msgid "This function is preferred over :meth:`today` and :meth:`utcnow`." msgstr "" -#: library/datetime.rst:882 +#: library/datetime.rst:901 +msgid "" +"Subsequent calls to :meth:`!datetime.now` may return the same instant " +"depending on the precision of the underlying clock." +msgstr "" + +#: library/datetime.rst:906 msgid "Return the current UTC date and time, with :attr:`.tzinfo` ``None``." msgstr "" -#: library/datetime.rst:884 +#: library/datetime.rst:908 msgid "" "This is like :meth:`now`, but returns the current UTC date and time, as a " "naive :class:`.datetime` object. An aware current UTC datetime can be " "obtained by calling ``datetime.now(timezone.utc)``. See also :meth:`now`." msgstr "" -#: library/datetime.rst:890 +#: library/datetime.rst:914 msgid "" "Because naive ``datetime`` objects are treated by many ``datetime`` methods " "as local times, it is preferred to use aware datetimes to represent times in " @@ -1293,11 +1497,11 @@ msgid "" "current time in UTC is by calling ``datetime.now(timezone.utc)``." msgstr "" -#: library/datetime.rst:897 +#: library/datetime.rst:921 msgid "Use :meth:`datetime.now` with :attr:`UTC` instead." msgstr "" -#: library/datetime.rst:902 +#: library/datetime.rst:926 msgid "" "Return the local date and time corresponding to the POSIX timestamp, such as " "is returned by :func:`time.time`. If optional argument *tz* is ``None`` or " @@ -1305,13 +1509,13 @@ msgid "" "time, and the returned :class:`.datetime` object is naive." msgstr "" -#: library/datetime.rst:907 +#: library/datetime.rst:931 msgid "" "If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` " "subclass, and the timestamp is converted to *tz*’s time zone." msgstr "" -#: library/datetime.rst:910 +#: library/datetime.rst:934 msgid "" ":meth:`fromtimestamp` may raise :exc:`OverflowError`, if the timestamp is " "out of the range of values supported by the platform C :c:func:`localtime` " @@ -1324,7 +1528,7 @@ msgid "" "preferred over :meth:`utcfromtimestamp`." msgstr "" -#: library/datetime.rst:921 +#: library/datetime.rst:945 msgid "" "Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp is " "out of the range of values supported by the platform C :c:func:`localtime` " @@ -1332,17 +1536,17 @@ msgid "" "`ValueError` on :c:func:`localtime` or :c:func:`gmtime` failure." msgstr "" -#: library/datetime.rst:928 +#: library/datetime.rst:952 msgid ":meth:`fromtimestamp` may return instances with :attr:`.fold` set to 1." msgstr "" -#: library/datetime.rst:933 +#: library/datetime.rst:957 msgid "" "Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, " "with :attr:`.tzinfo` ``None``. (The resulting object is naive.)" msgstr "" -#: library/datetime.rst:936 +#: library/datetime.rst:960 msgid "" "This may raise :exc:`OverflowError`, if the timestamp is out of the range of " "values supported by the platform C :c:func:`gmtime` function, and :exc:" @@ -1350,23 +1554,32 @@ msgid "" "to years in 1970 through 2038." msgstr "" -#: library/datetime.rst:941 +#: library/datetime.rst:965 msgid "To get an aware :class:`.datetime` object, call :meth:`fromtimestamp`::" msgstr "" -#: library/datetime.rst:945 +#: library/datetime.rst:967 +msgid "datetime.fromtimestamp(timestamp, timezone.utc)" +msgstr "" + +#: library/datetime.rst:969 msgid "" "On the POSIX compliant platforms, it is equivalent to the following " "expression::" msgstr "" -#: library/datetime.rst:950 +#: library/datetime.rst:972 +msgid "" +"datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)" +msgstr "" + +#: library/datetime.rst:974 msgid "" "except the latter formula always supports the full years range: between :" "const:`MINYEAR` and :const:`MAXYEAR` inclusive." msgstr "" -#: library/datetime.rst:955 +#: library/datetime.rst:979 msgid "" "Because naive ``datetime`` objects are treated by many ``datetime`` methods " "as local times, it is preferred to use aware datetimes to represent times in " @@ -1375,7 +1588,7 @@ msgid "" "tz=timezone.utc)``." msgstr "" -#: library/datetime.rst:961 +#: library/datetime.rst:985 msgid "" "Raise :exc:`OverflowError` instead of :exc:`ValueError` if the timestamp is " "out of the range of values supported by the platform C :c:func:`gmtime` " @@ -1383,11 +1596,11 @@ msgid "" "`gmtime` failure." msgstr "" -#: library/datetime.rst:969 +#: library/datetime.rst:993 msgid "Use :meth:`datetime.fromtimestamp` with :attr:`UTC` instead." msgstr "" -#: library/datetime.rst:974 +#: library/datetime.rst:998 msgid "" "Return the :class:`.datetime` corresponding to the proleptic Gregorian " "ordinal, where January 1 of year 1 has ordinal 1. :exc:`ValueError` is " @@ -1396,7 +1609,7 @@ msgid "" "is ``None``." msgstr "" -#: library/datetime.rst:982 +#: library/datetime.rst:1006 msgid "" "Return a new :class:`.datetime` object whose date components are equal to " "the given :class:`date` object's, and whose time components are equal to the " @@ -1407,41 +1620,66 @@ msgid "" "attr:`.tzinfo` attributes are ignored." msgstr "" -#: library/datetime.rst:990 +#: library/datetime.rst:1014 msgid "" -"For any :class:`.datetime` object *d*, ``d == datetime.combine(d.date(), d." +"For any :class:`.datetime` object ``d``, ``d == datetime.combine(d.date(), d." "time(), d.tzinfo)``." msgstr "" -#: library/datetime.rst:993 +#: library/datetime.rst:1017 msgid "Added the *tzinfo* argument." msgstr "" -#: library/datetime.rst:999 +#: library/datetime.rst:1023 msgid "" "Return a :class:`.datetime` corresponding to a *date_string* in any valid " "ISO 8601 format, with the following exceptions:" msgstr "" -#: library/datetime.rst:1787 +#: library/datetime.rst:1811 msgid "Time zone offsets may have fractional seconds." msgstr "" -#: library/datetime.rst:1003 +#: library/datetime.rst:1027 msgid "The ``T`` separator may be replaced by any single unicode character." msgstr "" -#: library/datetime.rst:1792 +#: library/datetime.rst:1816 msgid "Fractional hours and minutes are not supported." msgstr "" -#: library/datetime.rst:1035 +#: library/datetime.rst:1037 +msgid "" +">>> from datetime import datetime\n" +">>> datetime.fromisoformat('2011-11-04')\n" +"datetime.datetime(2011, 11, 4, 0, 0)\n" +">>> datetime.fromisoformat('20111104')\n" +"datetime.datetime(2011, 11, 4, 0, 0)\n" +">>> datetime.fromisoformat('2011-11-04T00:05:23')\n" +"datetime.datetime(2011, 11, 4, 0, 5, 23)\n" +">>> datetime.fromisoformat('2011-11-04T00:05:23Z')\n" +"datetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone.utc)\n" +">>> datetime.fromisoformat('20111104T000523')\n" +"datetime.datetime(2011, 11, 4, 0, 5, 23)\n" +">>> datetime.fromisoformat('2011-W01-2T00:05:23.283')\n" +"datetime.datetime(2011, 1, 4, 0, 5, 23, 283000)\n" +">>> datetime.fromisoformat('2011-11-04 00:05:23.283')\n" +"datetime.datetime(2011, 11, 4, 0, 5, 23, 283000)\n" +">>> datetime.fromisoformat('2011-11-04 00:05:23.283+00:00')\n" +"datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone." +"utc)\n" +">>> datetime.fromisoformat('2011-11-04T00:05:23+04:00') \n" +"datetime.datetime(2011, 11, 4, 0, 5, 23,\n" +" tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))" +msgstr "" + +#: library/datetime.rst:1059 msgid "" "Previously, this method only supported formats that could be emitted by :" -"meth:`date.isoformat()` or :meth:`datetime.isoformat()`." +"meth:`date.isoformat` or :meth:`datetime.isoformat`." msgstr "" -#: library/datetime.rst:1042 +#: library/datetime.rst:1066 msgid "" "Return a :class:`.datetime` corresponding to the ISO calendar date specified " "by year, week and day. The non-date components of the datetime are populated " @@ -1449,19 +1687,23 @@ msgid "" "`datetime.isocalendar`." msgstr "" -#: library/datetime.rst:1051 +#: library/datetime.rst:1075 msgid "" "Return a :class:`.datetime` corresponding to *date_string*, parsed according " "to *format*." msgstr "" -#: library/datetime.rst:1054 +#: library/datetime.rst:1078 msgid "" "If *format* does not contain microseconds or time zone information, this is " "equivalent to::" msgstr "" -#: library/datetime.rst:1058 +#: library/datetime.rst:2533 +msgid "datetime(*(time.strptime(date_string, format)[0:6]))" +msgstr "" + +#: library/datetime.rst:1082 msgid "" ":exc:`ValueError` is raised if the date_string and format can't be parsed " "by :func:`time.strptime` or if it returns a value which isn't a time tuple. " @@ -1469,43 +1711,43 @@ msgid "" "fromisoformat`." msgstr "" -#: library/datetime.rst:1069 +#: library/datetime.rst:1093 msgid "" "The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1, " "tzinfo=None)``." msgstr "" -#: library/datetime.rst:1075 +#: library/datetime.rst:1099 msgid "" "The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, " "59, 59, 999999, tzinfo=None)``." msgstr "" -#: library/datetime.rst:1081 +#: library/datetime.rst:1105 msgid "" "The smallest possible difference between non-equal :class:`.datetime` " "objects, ``timedelta(microseconds=1)``." msgstr "" -#: library/datetime.rst:1720 +#: library/datetime.rst:1744 msgid "In ``range(24)``." msgstr "" -#: library/datetime.rst:1114 library/datetime.rst:1730 +#: library/datetime.rst:1138 library/datetime.rst:1754 msgid "In ``range(60)``." msgstr "" -#: library/datetime.rst:1735 +#: library/datetime.rst:1759 msgid "In ``range(1000000)``." msgstr "" -#: library/datetime.rst:1124 +#: library/datetime.rst:1148 msgid "" "The object passed as the *tzinfo* argument to the :class:`.datetime` " "constructor, or ``None`` if none was passed." msgstr "" -#: library/datetime.rst:1746 +#: library/datetime.rst:1770 msgid "" "In ``[0, 1]``. Used to disambiguate wall times during a repeated interval. " "(A repeated interval occurs when clocks are rolled back at the end of " @@ -1515,24 +1757,24 @@ msgid "" "time representation." msgstr "" -#: library/datetime.rst:1143 +#: library/datetime.rst:1167 msgid "``datetime2 = datetime1 + timedelta``" msgstr "" -#: library/datetime.rst:2356 library/datetime.rst:2373 -#: library/datetime.rst:2438 library/datetime.rst:2447 +#: library/datetime.rst:2380 library/datetime.rst:2397 +#: library/datetime.rst:2462 library/datetime.rst:2471 msgid "\\(1)" msgstr "" -#: library/datetime.rst:1145 +#: library/datetime.rst:1169 msgid "``datetime2 = datetime1 - timedelta``" msgstr "" -#: library/datetime.rst:2389 +#: library/datetime.rst:2413 msgid "\\(2)" msgstr "" -#: library/datetime.rst:1147 +#: library/datetime.rst:1171 msgid "``timedelta = datetime1 - datetime2``" msgstr "" @@ -1560,7 +1802,7 @@ msgstr "" msgid "``datetime1 >= datetime2``" msgstr "" -#: library/datetime.rst:1159 +#: library/datetime.rst:1183 msgid "" "``datetime2`` is a duration of ``timedelta`` removed from ``datetime1``, " "moving forward in time if ``timedelta.days > 0``, or backward if ``timedelta." @@ -1571,7 +1813,7 @@ msgid "" "adjustments are done even if the input is an aware object." msgstr "" -#: library/datetime.rst:1168 +#: library/datetime.rst:1192 msgid "" "Computes the ``datetime2`` such that ``datetime2 + timedelta == datetime1``. " "As for addition, the result has the same :attr:`~.datetime.tzinfo` attribute " @@ -1579,44 +1821,44 @@ msgid "" "input is aware." msgstr "" -#: library/datetime.rst:1173 +#: library/datetime.rst:1197 msgid "" "Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined " "only if both operands are naive, or if both are aware. If one is aware and " "the other is naive, :exc:`TypeError` is raised." msgstr "" -#: library/datetime.rst:1177 +#: library/datetime.rst:1201 msgid "" "If both are naive, or both are aware and have the same :attr:`~.datetime." "tzinfo` attribute, the :attr:`~.datetime.tzinfo` attributes are ignored, and " -"the result is a :class:`timedelta` object *t* such that ``datetime2 + t == " +"the result is a :class:`timedelta` object ``t`` such that ``datetime2 + t == " "datetime1``. No time zone adjustments are done in this case." msgstr "" -#: library/datetime.rst:1182 +#: library/datetime.rst:1206 msgid "" "If both are aware and have different :attr:`~.datetime.tzinfo` attributes, " -"``a-b`` acts as if *a* and *b* were first converted to naive UTC datetimes. " -"The result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b." +"``a-b`` acts as if ``a`` and ``b`` were first converted to naive UTC " +"datetimes. The result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b." "replace(tzinfo=None) - b.utcoffset())`` except that the implementation never " "overflows." msgstr "" -#: library/datetime.rst:1188 +#: library/datetime.rst:1212 msgid "" ":class:`.datetime` objects are equal if they represent the same date and " "time, taking into account the time zone." msgstr "" -#: library/datetime.rst:1191 +#: library/datetime.rst:1215 msgid "" "Naive and aware :class:`!datetime` objects are never equal. :class:`!" "datetime` objects are never equal to :class:`date` objects that are not " "also :class:`!datetime` instances, even if they represent the same date." msgstr "" -#: library/datetime.rst:1196 +#: library/datetime.rst:1220 msgid "" "If both comparands are aware, and have the same :attr:`!tzinfo` attribute, " "the :attr:`!tzinfo` and :attr:`~.datetime.fold` attributes are ignored and " @@ -1627,20 +1869,20 @@ msgid "" "interval are never equal to :class:`!datetime` instances in other time zone." msgstr "" -#: library/datetime.rst:1206 +#: library/datetime.rst:1230 msgid "" "*datetime1* is considered less than *datetime2* when *datetime1* precedes " "*datetime2* in time, taking into account the time zone." msgstr "" -#: library/datetime.rst:1209 +#: library/datetime.rst:1233 msgid "" "Order comparison between naive and aware :class:`.datetime` objects, as well " "as a :class:`!datetime` object and a :class:`!date` object that is not also " "a :class:`!datetime` instance, raises :exc:`TypeError`." msgstr "" -#: library/datetime.rst:1213 +#: library/datetime.rst:1237 msgid "" "If both comparands are aware, and have the same :attr:`!tzinfo` attribute, " "the :attr:`!tzinfo` and :attr:`~.datetime.fold` attributes are ignored and " @@ -1650,33 +1892,33 @@ msgid "" "implementation never overflows." msgstr "" -#: library/datetime.rst:1220 +#: library/datetime.rst:1244 msgid "" "Equality comparisons between aware and naive :class:`.datetime` instances " "don't raise :exc:`TypeError`." msgstr "" -#: library/datetime.rst:1228 +#: library/datetime.rst:1252 msgid "Return :class:`date` object with same year, month and day." msgstr "" -#: library/datetime.rst:1233 +#: library/datetime.rst:1257 msgid "" "Return :class:`.time` object with same hour, minute, second, microsecond and " "fold. :attr:`.tzinfo` is ``None``. See also method :meth:`timetz`." msgstr "" -#: library/datetime.rst:1245 +#: library/datetime.rst:1269 msgid "The fold value is copied to the returned :class:`.time` object." msgstr "" -#: library/datetime.rst:1242 +#: library/datetime.rst:1266 msgid "" "Return :class:`.time` object with same hour, minute, second, microsecond, " "fold, and tzinfo attributes. See also method :meth:`time`." msgstr "" -#: library/datetime.rst:1253 +#: library/datetime.rst:1277 msgid "" "Return a datetime with the same attributes, except for those attributes " "given new values by whichever keyword arguments are specified. Note that " @@ -1684,21 +1926,21 @@ msgid "" "datetime with no conversion of date and time data." msgstr "" -#: library/datetime.rst:1264 +#: library/datetime.rst:1288 msgid "" "Return a :class:`.datetime` object with new :attr:`.tzinfo` attribute *tz*, " "adjusting the date and time data so the result is the same UTC time as " "*self*, but in *tz*'s local time." msgstr "" -#: library/datetime.rst:1268 +#: library/datetime.rst:1292 msgid "" "If provided, *tz* must be an instance of a :class:`tzinfo` subclass, and " "its :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. If " "*self* is naive, it is presumed to represent time in the system time zone." msgstr "" -#: library/datetime.rst:1272 +#: library/datetime.rst:1296 msgid "" "If called without arguments (or with ``tz=None``) the system local time zone " "is assumed for the target time zone. The ``.tzinfo`` attribute of the " @@ -1706,7 +1948,7 @@ msgid "" "with the zone name and offset obtained from the OS." msgstr "" -#: library/datetime.rst:1277 +#: library/datetime.rst:1301 msgid "" "If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no " "adjustment of date or time data is performed. Else the result is local time " @@ -1715,7 +1957,7 @@ msgid "" "date and time data as ``dt - dt.utcoffset()``." msgstr "" -#: library/datetime.rst:1283 +#: library/datetime.rst:1307 msgid "" "If you merely want to attach a :class:`timezone` object *tz* to a datetime " "*dt* without adjustment of date and time data, use ``dt." @@ -1724,54 +1966,72 @@ msgid "" "use ``dt.replace(tzinfo=None)``." msgstr "" -#: library/datetime.rst:1288 +#: library/datetime.rst:1312 msgid "" "Note that the default :meth:`tzinfo.fromutc` method can be overridden in a :" "class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`. " "Ignoring error cases, :meth:`astimezone` acts like::" msgstr "" -#: library/datetime.rst:1300 +#: library/datetime.rst:1316 +msgid "" +"def astimezone(self, tz):\n" +" if self.tzinfo is tz:\n" +" return self\n" +" # Convert self to UTC, and attach the new timezone object.\n" +" utc = (self - self.utcoffset()).replace(tzinfo=tz)\n" +" # Convert from UTC to tz's local time.\n" +" return tz.fromutc(utc)" +msgstr "" + +#: library/datetime.rst:1324 msgid "*tz* now can be omitted." msgstr "" -#: library/datetime.rst:1303 +#: library/datetime.rst:1327 msgid "" "The :meth:`astimezone` method can now be called on naive instances that are " "presumed to represent system local time." msgstr "" -#: library/datetime.rst:1310 +#: library/datetime.rst:1334 msgid "" "If :attr:`.tzinfo` is ``None``, returns ``None``, else returns ``self.tzinfo." "utcoffset(self)``, and raises an exception if the latter doesn't return " "``None`` or a :class:`timedelta` object with magnitude less than one day." msgstr "" -#: library/datetime.rst:1906 library/datetime.rst:2258 -#: library/datetime.rst:2582 +#: library/datetime.rst:1930 library/datetime.rst:2282 +#: library/datetime.rst:2606 msgid "The UTC offset is not restricted to a whole number of minutes." msgstr "" -#: library/datetime.rst:1320 +#: library/datetime.rst:1344 msgid "" "If :attr:`.tzinfo` is ``None``, returns ``None``, else returns ``self.tzinfo." "dst(self)``, and raises an exception if the latter doesn't return ``None`` " "or a :class:`timedelta` object with magnitude less than one day." msgstr "" -#: library/datetime.rst:1916 library/datetime.rst:2067 +#: library/datetime.rst:1940 library/datetime.rst:2091 msgid "The DST offset is not restricted to a whole number of minutes." msgstr "" -#: library/datetime.rst:1330 +#: library/datetime.rst:1354 msgid "" "If :attr:`.tzinfo` is ``None``, returns ``None``, else returns ``self.tzinfo." "tzname(self)``, raises an exception if the latter doesn't return ``None`` or " "a string object," msgstr "" -#: library/datetime.rst:1345 +#: library/datetime.rst:1365 +msgid "" +"time.struct_time((d.year, d.month, d.day,\n" +" d.hour, d.minute, d.second,\n" +" d.weekday(), yday, dst))" +msgstr "" + +#: library/datetime.rst:1369 msgid "" "where ``yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the " "day number within the current year starting with 1 for January 1st. The :" @@ -1782,24 +2042,24 @@ msgid "" "to 0." msgstr "" -#: library/datetime.rst:1356 +#: library/datetime.rst:1380 msgid "" -"If :class:`.datetime` instance *d* is naive, this is the same as ``d." +"If :class:`.datetime` instance ``d`` is naive, this is the same as ``d." "timetuple()`` except that :attr:`~.time.struct_time.tm_isdst` is forced to 0 " "regardless of what ``d.dst()`` returns. DST is never in effect for a UTC " "time." msgstr "" -#: library/datetime.rst:1360 +#: library/datetime.rst:1384 msgid "" -"If *d* is aware, *d* is normalized to UTC time, by subtracting ``d." +"If ``d`` is aware, ``d`` is normalized to UTC time, by subtracting ``d." "utcoffset()``, and a :class:`time.struct_time` for the normalized time is " "returned. :attr:`!tm_isdst` is forced to 0. Note that an :exc:" "`OverflowError` may be raised if ``d.year`` was ``MINYEAR`` or ``MAXYEAR`` " "and UTC adjustment spills over a year boundary." msgstr "" -#: library/datetime.rst:1369 +#: library/datetime.rst:1393 msgid "" "Because naive ``datetime`` objects are treated by many ``datetime`` methods " "as local times, it is preferred to use aware datetimes to represent times in " @@ -1809,20 +2069,20 @@ msgid "" "meth:`.datetime.timetuple`." msgstr "" -#: library/datetime.rst:1378 +#: library/datetime.rst:1402 msgid "" "Return the proleptic Gregorian ordinal of the date. The same as ``self." "date().toordinal()``." msgstr "" -#: library/datetime.rst:1383 +#: library/datetime.rst:1407 msgid "" "Return POSIX timestamp corresponding to the :class:`.datetime` instance. The " "return value is a :class:`float` similar to that returned by :func:`time." "time`." msgstr "" -#: library/datetime.rst:1387 +#: library/datetime.rst:1411 msgid "" "Naive :class:`.datetime` instances are assumed to represent local time and " "this method relies on the platform C :c:func:`mktime` function to perform " @@ -1832,18 +2092,22 @@ msgid "" "future." msgstr "" -#: library/datetime.rst:1394 +#: library/datetime.rst:1418 msgid "" "For aware :class:`.datetime` instances, the return value is computed as::" msgstr "" -#: library/datetime.rst:1401 +#: library/datetime.rst:1421 +msgid "(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()" +msgstr "" + +#: library/datetime.rst:1425 msgid "" "The :meth:`timestamp` method uses the :attr:`.fold` attribute to " "disambiguate the times during a repeated interval." msgstr "" -#: library/datetime.rst:1407 +#: library/datetime.rst:1431 msgid "" "There is no method to obtain the POSIX timestamp directly from a naive :" "class:`.datetime` instance representing UTC time. If your application uses " @@ -1851,145 +2115,193 @@ msgid "" "the POSIX timestamp by supplying ``tzinfo=timezone.utc``::" msgstr "" -#: library/datetime.rst:1415 +#: library/datetime.rst:1437 +msgid "timestamp = dt.replace(tzinfo=timezone.utc).timestamp()" +msgstr "" + +#: library/datetime.rst:1439 msgid "or by calculating the timestamp directly::" msgstr "" -#: library/datetime.rst:1421 +#: library/datetime.rst:1441 +msgid "timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)" +msgstr "" + +#: library/datetime.rst:1445 msgid "" "Return the day of the week as an integer, where Monday is 0 and Sunday is 6. " "The same as ``self.date().weekday()``. See also :meth:`isoweekday`." msgstr "" -#: library/datetime.rst:1427 +#: library/datetime.rst:1451 msgid "" "Return the day of the week as an integer, where Monday is 1 and Sunday is 7. " "The same as ``self.date().isoweekday()``. See also :meth:`weekday`, :meth:" "`isocalendar`." msgstr "" -#: library/datetime.rst:1434 +#: library/datetime.rst:1458 msgid "" "Return a :term:`named tuple` with three components: ``year``, ``week`` and " "``weekday``. The same as ``self.date().isocalendar()``." msgstr "" -#: library/datetime.rst:1440 +#: library/datetime.rst:1464 msgid "Return a string representing the date and time in ISO 8601 format:" msgstr "" -#: library/datetime.rst:1442 +#: library/datetime.rst:1466 msgid "``YYYY-MM-DDTHH:MM:SS.ffffff``, if :attr:`microsecond` is not 0" msgstr "" -#: library/datetime.rst:1443 +#: library/datetime.rst:1467 msgid "``YYYY-MM-DDTHH:MM:SS``, if :attr:`microsecond` is 0" msgstr "" -#: library/datetime.rst:1445 +#: library/datetime.rst:1469 msgid "" "If :meth:`utcoffset` does not return ``None``, a string is appended, giving " "the UTC offset:" msgstr "" -#: library/datetime.rst:1448 +#: library/datetime.rst:1472 msgid "" "``YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]``, if :attr:`microsecond` " "is not 0" msgstr "" -#: library/datetime.rst:1450 +#: library/datetime.rst:1474 msgid "" "``YYYY-MM-DDTHH:MM:SS+HH:MM[:SS[.ffffff]]``, if :attr:`microsecond` is 0" msgstr "" -#: library/datetime.rst:1460 +#: library/datetime.rst:1478 +msgid "" +">>> from datetime import datetime, timezone\n" +">>> datetime(2019, 5, 18, 15, 17, 8, 132263).isoformat()\n" +"'2019-05-18T15:17:08.132263'\n" +">>> datetime(2019, 5, 18, 15, 17, tzinfo=timezone.utc).isoformat()\n" +"'2019-05-18T15:17:00+00:00'" +msgstr "" + +#: library/datetime.rst:1484 msgid "" "The optional argument *sep* (default ``'T'``) is a one-character separator, " "placed between the date and time portions of the result. For example::" msgstr "" -#: library/datetime.rst:1846 +#: library/datetime.rst:1487 +msgid "" +">>> from datetime import tzinfo, timedelta, datetime\n" +">>> class TZ(tzinfo):\n" +"... \"\"\"A time zone with an arbitrary, constant -06:39 offset.\"\"\"\n" +"... def utcoffset(self, dt):\n" +"... return timedelta(hours=-6, minutes=-39)\n" +"...\n" +">>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')\n" +"'2002-12-25 00:00:00-06:39'\n" +">>> datetime(2009, 11, 27, microsecond=100, tzinfo=TZ()).isoformat()\n" +"'2009-11-27T00:00:00.000100-06:39'" +msgstr "" + +#: library/datetime.rst:1870 msgid "" "The optional argument *timespec* specifies the number of additional " "components of the time to include (the default is ``'auto'``). It can be one " "of the following:" msgstr "" -#: library/datetime.rst:1850 +#: library/datetime.rst:1874 msgid "" "``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0, same as " "``'microseconds'`` otherwise." msgstr "" -#: library/datetime.rst:1852 +#: library/datetime.rst:1876 msgid "``'hours'``: Include the :attr:`hour` in the two-digit ``HH`` format." msgstr "" -#: library/datetime.rst:1853 +#: library/datetime.rst:1877 msgid "" "``'minutes'``: Include :attr:`hour` and :attr:`minute` in ``HH:MM`` format." msgstr "" -#: library/datetime.rst:1854 +#: library/datetime.rst:1878 msgid "" "``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second` in " "``HH:MM:SS`` format." msgstr "" -#: library/datetime.rst:1856 +#: library/datetime.rst:1880 msgid "" "``'milliseconds'``: Include full time, but truncate fractional second part " "to milliseconds. ``HH:MM:SS.sss`` format." msgstr "" -#: library/datetime.rst:1858 +#: library/datetime.rst:1882 msgid "``'microseconds'``: Include full time in ``HH:MM:SS.ffffff`` format." msgstr "" -#: library/datetime.rst:1862 +#: library/datetime.rst:1886 msgid "Excluded time components are truncated, not rounded." msgstr "" -#: library/datetime.rst:1492 +#: library/datetime.rst:1516 msgid ":exc:`ValueError` will be raised on an invalid *timespec* argument::" msgstr "" -#: library/datetime.rst:1877 +#: library/datetime.rst:1519 +msgid "" +">>> from datetime import datetime\n" +">>> datetime.now().isoformat(timespec='minutes') \n" +"'2002-12-25T00:00'\n" +">>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)\n" +">>> dt.isoformat(timespec='microseconds')\n" +"'2015-01-01T12:30:59.000000'" +msgstr "" + +#: library/datetime.rst:1901 msgid "Added the *timespec* parameter." msgstr "" -#: library/datetime.rst:1508 +#: library/datetime.rst:1532 msgid "" -"For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to ``d." +"For a :class:`.datetime` instance ``d``, ``str(d)`` is equivalent to ``d." "isoformat(' ')``." msgstr "" -#: library/datetime.rst:1514 +#: library/datetime.rst:1538 msgid "Return a string representing the date and time::" msgstr "" -#: library/datetime.rst:1520 +#: library/datetime.rst:1540 +msgid "" +">>> from datetime import datetime\n" +">>> datetime(2002, 12, 4, 20, 30, 40).ctime()\n" +"'Wed Dec 4 20:30:40 2002'" +msgstr "" + +#: library/datetime.rst:1544 msgid "" "The output string will *not* include time zone information, regardless of " "whether the input is aware or naive." msgstr "" -#: library/datetime.rst:1527 +#: library/datetime.rst:1551 msgid "" "on platforms where the native C :c:func:`ctime` function (which :func:`time." "ctime` invokes, but which :meth:`datetime.ctime` does not invoke) conforms " "to the C standard." msgstr "" -#: library/datetime.rst:1534 +#: library/datetime.rst:1558 msgid "" "Return a string representing the date and time, controlled by an explicit " "format string. See also :ref:`strftime-strptime-behavior` and :meth:" "`datetime.isoformat`." msgstr "" -#: library/datetime.rst:1541 +#: library/datetime.rst:1565 msgid "" "Same as :meth:`.datetime.strftime`. This makes it possible to specify a " "format string for a :class:`.datetime` object in :ref:`formatted string " @@ -1997,82 +2309,207 @@ msgid "" "`strftime-strptime-behavior` and :meth:`datetime.isoformat`." msgstr "" -#: library/datetime.rst:1548 +#: library/datetime.rst:1572 msgid "Examples of Usage: :class:`.datetime`" msgstr "" -#: library/datetime.rst:1550 +#: library/datetime.rst:1574 msgid "Examples of working with :class:`.datetime` objects:" msgstr "" -#: library/datetime.rst:1603 +#: library/datetime.rst:1576 +msgid "" +">>> from datetime import datetime, date, time, timezone\n" +"\n" +">>> # Using datetime.combine()\n" +">>> d = date(2005, 7, 14)\n" +">>> t = time(12, 30)\n" +">>> datetime.combine(d, t)\n" +"datetime.datetime(2005, 7, 14, 12, 30)\n" +"\n" +">>> # Using datetime.now()\n" +">>> datetime.now() \n" +"datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1\n" +">>> datetime.now(timezone.utc) \n" +"datetime.datetime(2007, 12, 6, 15, 29, 43, 79060, tzinfo=datetime.timezone." +"utc)\n" +"\n" +">>> # Using datetime.strptime()\n" +">>> dt = datetime.strptime(\"21/11/06 16:30\", \"%d/%m/%y %H:%M\")\n" +">>> dt\n" +"datetime.datetime(2006, 11, 21, 16, 30)\n" +"\n" +">>> # Using datetime.timetuple() to get tuple of all attributes\n" +">>> tt = dt.timetuple()\n" +">>> for it in tt: \n" +"... print(it)\n" +"...\n" +"2006 # year\n" +"11 # month\n" +"21 # day\n" +"16 # hour\n" +"30 # minute\n" +"0 # second\n" +"1 # weekday (0 = Monday)\n" +"325 # number of days since 1st January\n" +"-1 # dst - method tzinfo.dst() returned None\n" +"\n" +">>> # Date in ISO format\n" +">>> ic = dt.isocalendar()\n" +">>> for it in ic: \n" +"... print(it)\n" +"...\n" +"2006 # ISO year\n" +"47 # ISO week\n" +"2 # ISO weekday\n" +"\n" +">>> # Formatting a datetime\n" +">>> dt.strftime(\"%A, %d. %B %Y %I:%M%p\")\n" +"'Tuesday, 21. November 2006 04:30PM'\n" +">>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'." +"format(dt, \"day\", \"month\", \"time\")\n" +"'The day is 21, the month is November, the time is 04:30PM.'" +msgstr "" + +#: library/datetime.rst:1627 msgid "" "The example below defines a :class:`tzinfo` subclass capturing time zone " "information for Kabul, Afghanistan, which used +4 UTC until 1945 and then " "+4:30 UTC thereafter::" msgstr "" -#: library/datetime.rst:1650 +#: library/datetime.rst:1631 +msgid "" +"from datetime import timedelta, datetime, tzinfo, timezone\n" +"\n" +"class KabulTz(tzinfo):\n" +" # Kabul used +4 until 1945, when they moved to +4:30\n" +" UTC_MOVE_DATE = datetime(1944, 12, 31, 20, tzinfo=timezone.utc)\n" +"\n" +" def utcoffset(self, dt):\n" +" if dt.year < 1945:\n" +" return timedelta(hours=4)\n" +" elif (1945, 1, 1, 0, 0) <= dt.timetuple()[:5] < (1945, 1, 1, 0, " +"30):\n" +" # An ambiguous (\"imaginary\") half-hour range representing\n" +" # a 'fold' in time due to the shift from +4 to +4:30.\n" +" # If dt falls in the imaginary range, use fold to decide how\n" +" # to resolve. See PEP495.\n" +" return timedelta(hours=4, minutes=(30 if dt.fold else 0))\n" +" else:\n" +" return timedelta(hours=4, minutes=30)\n" +"\n" +" def fromutc(self, dt):\n" +" # Follow same validations as in datetime.tzinfo\n" +" if not isinstance(dt, datetime):\n" +" raise TypeError(\"fromutc() requires a datetime argument\")\n" +" if dt.tzinfo is not self:\n" +" raise ValueError(\"dt.tzinfo is not self\")\n" +"\n" +" # A custom implementation is required for fromutc as\n" +" # the input to this function is a datetime with utc values\n" +" # but with a tzinfo set to self.\n" +" # See datetime.astimezone or fromtimestamp.\n" +" if dt.replace(tzinfo=timezone.utc) >= self.UTC_MOVE_DATE:\n" +" return dt + timedelta(hours=4, minutes=30)\n" +" else:\n" +" return dt + timedelta(hours=4)\n" +"\n" +" def dst(self, dt):\n" +" # Kabul does not observe daylight saving time.\n" +" return timedelta(0)\n" +"\n" +" def tzname(self, dt):\n" +" if dt >= self.UTC_MOVE_DATE:\n" +" return \"+04:30\"\n" +" return \"+04\"" +msgstr "" + +#: library/datetime.rst:1674 msgid "Usage of ``KabulTz`` from above::" msgstr "" #: library/datetime.rst:1676 +msgid "" +">>> tz1 = KabulTz()\n" +"\n" +">>> # Datetime before the change\n" +">>> dt1 = datetime(1900, 11, 21, 16, 30, tzinfo=tz1)\n" +">>> print(dt1.utcoffset())\n" +"4:00:00\n" +"\n" +">>> # Datetime after the change\n" +">>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=tz1)\n" +">>> print(dt2.utcoffset())\n" +"4:30:00\n" +"\n" +">>> # Convert datetime to another time zone\n" +">>> dt3 = dt2.astimezone(timezone.utc)\n" +">>> dt3\n" +"datetime.datetime(2006, 6, 14, 8, 30, tzinfo=datetime.timezone.utc)\n" +">>> dt2\n" +"datetime.datetime(2006, 6, 14, 13, 0, tzinfo=KabulTz())\n" +">>> dt2 == dt3\n" +"True" +msgstr "" + +#: library/datetime.rst:1700 msgid ":class:`.time` Objects" msgstr "" -#: library/datetime.rst:1678 +#: library/datetime.rst:1702 msgid "" "A :class:`.time` object represents a (local) time of day, independent of any " "particular day, and subject to adjustment via a :class:`tzinfo` object." msgstr "" -#: library/datetime.rst:1683 +#: library/datetime.rst:1707 msgid "" "All arguments are optional. *tzinfo* may be ``None``, or an instance of a :" "class:`tzinfo` subclass. The remaining arguments must be integers in the " "following ranges:" msgstr "" -#: library/datetime.rst:1693 +#: library/datetime.rst:1717 msgid "" "If an argument outside those ranges is given, :exc:`ValueError` is raised. " "All default to 0 except *tzinfo*, which defaults to ``None``." msgstr "" -#: library/datetime.rst:1701 +#: library/datetime.rst:1725 msgid "The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``." msgstr "" -#: library/datetime.rst:1706 +#: library/datetime.rst:1730 msgid "The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``." msgstr "" -#: library/datetime.rst:1711 +#: library/datetime.rst:1735 msgid "" "The smallest possible difference between non-equal :class:`.time` objects, " "``timedelta(microseconds=1)``, although note that arithmetic on :class:`." "time` objects is not supported." msgstr "" -#: library/datetime.rst:1740 +#: library/datetime.rst:1764 msgid "" "The object passed as the tzinfo argument to the :class:`.time` constructor, " "or ``None`` if none was passed." msgstr "" -#: library/datetime.rst:1754 +#: library/datetime.rst:1778 msgid "" -":class:`.time` objects support equality and order comparisons, where *a* is " -"considered less than *b* when *a* precedes *b* in time." +":class:`.time` objects support equality and order comparisons, where ``a`` " +"is considered less than ``b`` when ``a`` precedes ``b`` in time." msgstr "" -#: library/datetime.rst:1757 +#: library/datetime.rst:1781 msgid "" "Naive and aware :class:`!time` objects are never equal. Order comparison " "between naive and aware :class:`!time` objects raises :exc:`TypeError`." msgstr "" -#: library/datetime.rst:1761 +#: library/datetime.rst:1785 msgid "" "If both comparands are aware, and have the same :attr:`~.time.tzinfo` " "attribute, the :attr:`!tzinfo` and :attr:`!fold` attributes are ignored and " @@ -2081,18 +2518,18 @@ msgid "" "subtracting their UTC offsets (obtained from ``self.utcoffset()``)." msgstr "" -#: library/datetime.rst:1767 +#: library/datetime.rst:1791 msgid "" "Equality comparisons between aware and naive :class:`.time` instances don't " "raise :exc:`TypeError`." msgstr "" -#: library/datetime.rst:1771 +#: library/datetime.rst:1795 msgid "" "In Boolean contexts, a :class:`.time` object is always considered to be true." msgstr "" -#: library/datetime.rst:1773 +#: library/datetime.rst:1797 msgid "" "Before Python 3.5, a :class:`.time` object was considered to be false if it " "represented midnight in UTC. This behavior was considered obscure and error-" @@ -2100,39 +2537,61 @@ msgid "" "details." msgstr "" -#: library/datetime.rst:1780 +#: library/datetime.rst:1804 msgid "Other constructor:" msgstr "" -#: library/datetime.rst:1784 +#: library/datetime.rst:1808 msgid "" "Return a :class:`.time` corresponding to a *time_string* in any valid ISO " "8601 format, with the following exceptions:" msgstr "" -#: library/datetime.rst:1788 +#: library/datetime.rst:1812 msgid "" "The leading ``T``, normally required in cases where there may be ambiguity " "between a date and a time, is not required." msgstr "" -#: library/datetime.rst:1790 +#: library/datetime.rst:1814 msgid "" "Fractional seconds may have any number of digits (anything beyond 6 will be " "truncated)." msgstr "" -#: library/datetime.rst:1794 +#: library/datetime.rst:1818 msgid "Examples:" msgstr "" -#: library/datetime.rst:1818 +#: library/datetime.rst:1820 +msgid "" +">>> from datetime import time\n" +">>> time.fromisoformat('04:23:01')\n" +"datetime.time(4, 23, 1)\n" +">>> time.fromisoformat('T04:23:01')\n" +"datetime.time(4, 23, 1)\n" +">>> time.fromisoformat('T042301')\n" +"datetime.time(4, 23, 1)\n" +">>> time.fromisoformat('04:23:01.000384')\n" +"datetime.time(4, 23, 1, 384)\n" +">>> time.fromisoformat('04:23:01,000384')\n" +"datetime.time(4, 23, 1, 384)\n" +">>> time.fromisoformat('04:23:01+04:00')\n" +"datetime.time(4, 23, 1, tzinfo=datetime.timezone(datetime." +"timedelta(seconds=14400)))\n" +">>> time.fromisoformat('04:23:01Z')\n" +"datetime.time(4, 23, 1, tzinfo=datetime.timezone.utc)\n" +">>> time.fromisoformat('04:23:01+00:00')\n" +"datetime.time(4, 23, 1, tzinfo=datetime.timezone.utc)" +msgstr "" + +#: library/datetime.rst:1842 msgid "" "Previously, this method only supported formats that could be emitted by :" -"meth:`time.isoformat()`." +"meth:`time.isoformat`." msgstr "" -#: library/datetime.rst:1828 +#: library/datetime.rst:1852 msgid "" "Return a :class:`.time` with the same value, except for those attributes " "given new values by whichever keyword arguments are specified. Note that " @@ -2140,46 +2599,59 @@ msgid "" "aware :class:`.time`, without conversion of the time data." msgstr "" -#: library/datetime.rst:1839 +#: library/datetime.rst:1863 msgid "Return a string representing the time in ISO 8601 format, one of:" msgstr "" -#: library/datetime.rst:1841 +#: library/datetime.rst:1865 msgid "``HH:MM:SS.ffffff``, if :attr:`microsecond` is not 0" msgstr "" -#: library/datetime.rst:1842 +#: library/datetime.rst:1866 msgid "``HH:MM:SS``, if :attr:`microsecond` is 0" msgstr "" -#: library/datetime.rst:1843 +#: library/datetime.rst:1867 msgid "" "``HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]``, if :meth:`utcoffset` does not " "return ``None``" msgstr "" -#: library/datetime.rst:1844 +#: library/datetime.rst:1868 msgid "" "``HH:MM:SS+HH:MM[:SS[.ffffff]]``, if :attr:`microsecond` is 0 and :meth:" "`utcoffset` does not return ``None``" msgstr "" -#: library/datetime.rst:1864 +#: library/datetime.rst:1888 msgid ":exc:`ValueError` will be raised on an invalid *timespec* argument." msgstr "" -#: library/datetime.rst:1883 -msgid "For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``." +#: library/datetime.rst:1892 +msgid "" +">>> from datetime import time\n" +">>> time(hour=12, minute=34, second=56, microsecond=123456)." +"isoformat(timespec='minutes')\n" +"'12:34'\n" +">>> dt = time(hour=12, minute=34, second=56, microsecond=0)\n" +">>> dt.isoformat(timespec='microseconds')\n" +"'12:34:56.000000'\n" +">>> dt.isoformat(timespec='auto')\n" +"'12:34:56'" msgstr "" -#: library/datetime.rst:1888 +#: library/datetime.rst:1907 +msgid "For a time ``t``, ``str(t)`` is equivalent to ``t.isoformat()``." +msgstr "" + +#: library/datetime.rst:1912 msgid "" "Return a string representing the time, controlled by an explicit format " "string. See also :ref:`strftime-strptime-behavior` and :meth:`time." "isoformat`." msgstr "" -#: library/datetime.rst:1894 +#: library/datetime.rst:1918 msgid "" "Same as :meth:`.time.strftime`. This makes it possible to specify a format " "string for a :class:`.time` object in :ref:`formatted string literals >> from datetime import time, tzinfo, timedelta\n" +">>> class TZ1(tzinfo):\n" +"... def utcoffset(self, dt):\n" +"... return timedelta(hours=1)\n" +"... def dst(self, dt):\n" +"... return timedelta(0)\n" +"... def tzname(self,dt):\n" +"... return \"+01:00\"\n" +"... def __repr__(self):\n" +"... return f\"{self.__class__.__name__}()\"\n" +"...\n" +">>> t = time(12, 10, 30, tzinfo=TZ1())\n" +">>> t\n" +"datetime.time(12, 10, 30, tzinfo=TZ1())\n" +">>> t.isoformat()\n" +"'12:10:30+01:00'\n" +">>> t.dst()\n" +"datetime.timedelta(0)\n" +">>> t.tzname()\n" +"'+01:00'\n" +">>> t.strftime(\"%H:%M:%S %Z\")\n" +"'12:10:30 +01:00'\n" +">>> 'The {} is {:%H:%M}.'.format(\"time\", t)\n" +"'The time is 12:10.'" +msgstr "" + +#: library/datetime.rst:1983 msgid ":class:`tzinfo` Objects" msgstr "" -#: library/datetime.rst:1963 +#: library/datetime.rst:1987 msgid "" "This is an abstract base class, meaning that this class should not be " "instantiated directly. Define a subclass of :class:`tzinfo` to capture " "information about a particular time zone." msgstr "" -#: library/datetime.rst:1967 +#: library/datetime.rst:1991 msgid "" "An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the " "constructors for :class:`.datetime` and :class:`.time` objects. The latter " @@ -2237,7 +2737,7 @@ msgid "" "object passed to them." msgstr "" -#: library/datetime.rst:1973 +#: library/datetime.rst:1997 msgid "" "You need to derive a concrete subclass, and (at least) supply " "implementations of the standard :class:`tzinfo` methods needed by the :class:" @@ -2247,7 +2747,7 @@ msgid "" "American EST and EDT." msgstr "" -#: library/datetime.rst:1980 +#: library/datetime.rst:2004 msgid "" "Special requirement for pickling: A :class:`tzinfo` subclass must have an :" "meth:`~object.__init__` method that can be called with no arguments, " @@ -2255,20 +2755,20 @@ msgid "" "technical requirement that may be relaxed in the future." msgstr "" -#: library/datetime.rst:1986 +#: library/datetime.rst:2010 msgid "" "A concrete subclass of :class:`tzinfo` may need to implement the following " "methods. Exactly which methods are needed depends on the uses made of aware :" "mod:`!datetime` objects. If in doubt, simply implement all of them." msgstr "" -#: library/datetime.rst:1993 +#: library/datetime.rst:2017 msgid "" "Return offset of local time from UTC, as a :class:`timedelta` object that is " "positive east of UTC. If local time is west of UTC, this should be negative." msgstr "" -#: library/datetime.rst:1996 +#: library/datetime.rst:2020 msgid "" "This represents the *total* offset from UTC; for example, if a :class:" "`tzinfo` object represents both time zone and DST adjustments, :meth:" @@ -2279,25 +2779,31 @@ msgid "" "meth:`utcoffset` will probably look like one of these two::" msgstr "" -#: library/datetime.rst:2007 +#: library/datetime.rst:2028 +msgid "" +"return CONSTANT # fixed-offset class\n" +"return CONSTANT + self.dst(dt) # daylight-aware class" +msgstr "" + +#: library/datetime.rst:2031 msgid "" "If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return " "``None`` either." msgstr "" -#: library/datetime.rst:2010 +#: library/datetime.rst:2034 msgid "" "The default implementation of :meth:`utcoffset` raises :exc:" "`NotImplementedError`." msgstr "" -#: library/datetime.rst:2019 +#: library/datetime.rst:2043 msgid "" "Return the daylight saving time (DST) adjustment, as a :class:`timedelta` " "object or ``None`` if DST information isn't known." msgstr "" -#: library/datetime.rst:2023 +#: library/datetime.rst:2047 msgid "" "Return ``timedelta(0)`` if DST is not in effect. If DST is in effect, return " "the offset as a :class:`timedelta` object (see :meth:`utcoffset` for " @@ -2310,17 +2816,17 @@ msgid "" "to account for DST changes when crossing time zones." msgstr "" -#: library/datetime.rst:2033 +#: library/datetime.rst:2057 msgid "" "An instance *tz* of a :class:`tzinfo` subclass that models both standard and " "daylight times must be consistent in this sense:" msgstr "" -#: library/datetime.rst:2036 +#: library/datetime.rst:2060 msgid "``tz.utcoffset(dt) - tz.dst(dt)``" msgstr "" -#: library/datetime.rst:2038 +#: library/datetime.rst:2062 msgid "" "must return the same result for every :class:`.datetime` *dt* with ``dt." "tzinfo == tz``. For sane :class:`tzinfo` subclasses, this expression yields " @@ -2333,22 +2839,42 @@ msgid "" "astimezone` regardless." msgstr "" -#: library/datetime.rst:2047 +#: library/datetime.rst:2071 msgid "" "Most implementations of :meth:`dst` will probably look like one of these " "two::" msgstr "" -#: library/datetime.rst:2053 +#: library/datetime.rst:2073 +msgid "" +"def dst(self, dt):\n" +" # a fixed-offset class: doesn't account for DST\n" +" return timedelta(0)" +msgstr "" + +#: library/datetime.rst:2077 msgid "or::" msgstr "" -#: library/datetime.rst:2065 +#: library/datetime.rst:2079 +msgid "" +"def dst(self, dt):\n" +" # Code to set dston and dstoff to the time zone's DST\n" +" # transition times based on the input dt.year, and expressed\n" +" # in standard local time.\n" +"\n" +" if dston <= dt.replace(tzinfo=None) < dstoff:\n" +" return timedelta(hours=1)\n" +" else:\n" +" return timedelta(0)" +msgstr "" + +#: library/datetime.rst:2089 msgid "" "The default implementation of :meth:`dst` raises :exc:`NotImplementedError`." msgstr "" -#: library/datetime.rst:2073 +#: library/datetime.rst:2097 msgid "" "Return the time zone name corresponding to the :class:`.datetime` object " "*dt*, as a string. Nothing about string names is defined by the :mod:`!" @@ -2362,13 +2888,13 @@ msgid "" "accounting for daylight time." msgstr "" -#: library/datetime.rst:2083 +#: library/datetime.rst:2107 msgid "" "The default implementation of :meth:`tzname` raises :exc:" "`NotImplementedError`." msgstr "" -#: library/datetime.rst:2086 +#: library/datetime.rst:2110 msgid "" "These methods are called by a :class:`.datetime` or :class:`.time` object, " "in response to their methods of the same names. A :class:`.datetime` object " @@ -2378,7 +2904,7 @@ msgid "" "datetime`." msgstr "" -#: library/datetime.rst:2092 +#: library/datetime.rst:2116 msgid "" "When ``None`` is passed, it's up to the class designer to decide the best " "response. For example, returning ``None`` is appropriate if the class wishes " @@ -2387,7 +2913,7 @@ msgid "" "offset, as there is no other convention for discovering the standard offset." msgstr "" -#: library/datetime.rst:2098 +#: library/datetime.rst:2122 msgid "" "When a :class:`.datetime` object is passed in response to a :class:`." "datetime` method, ``dt.tzinfo`` is the same object as *self*. :class:" @@ -2397,13 +2923,13 @@ msgid "" "zones." msgstr "" -#: library/datetime.rst:2104 +#: library/datetime.rst:2128 msgid "" "There is one more :class:`tzinfo` method that a subclass may wish to " "override:" msgstr "" -#: library/datetime.rst:2109 +#: library/datetime.rst:2133 msgid "" "This is called from the default :meth:`datetime.astimezone` implementation. " "When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time " @@ -2412,7 +2938,7 @@ msgid "" "datetime in *self*'s local time." msgstr "" -#: library/datetime.rst:2115 +#: library/datetime.rst:2139 msgid "" "Most :class:`tzinfo` subclasses should be able to inherit the default :meth:" "`fromutc` implementation without problems. It's strong enough to handle " @@ -2427,19 +2953,217 @@ msgid "" "offset changes." msgstr "" -#: library/datetime.rst:2126 +#: library/datetime.rst:2150 msgid "" "Skipping code for error cases, the default :meth:`fromutc` implementation " "acts like::" msgstr "" -#: library/datetime.rst:2144 +#: library/datetime.rst:2153 +msgid "" +"def fromutc(self, dt):\n" +" # raise ValueError error if dt.tzinfo is not self\n" +" dtoff = dt.utcoffset()\n" +" dtdst = dt.dst()\n" +" # raise ValueError if dtoff is None or dtdst is None\n" +" delta = dtoff - dtdst # this is self's standard offset\n" +" if delta:\n" +" dt += delta # convert to standard local time\n" +" dtdst = dt.dst()\n" +" # raise ValueError if dtdst is None\n" +" if dtdst:\n" +" return dt + dtdst\n" +" else:\n" +" return dt" +msgstr "" + +#: library/datetime.rst:2168 msgid "" "In the following :download:`tzinfo_examples.py <../includes/tzinfo_examples." "py>` file there are some examples of :class:`tzinfo` classes:" msgstr "" -#: library/datetime.rst:2150 +#: library/datetime.rst:2172 +msgid "" +"from datetime import tzinfo, timedelta, datetime\n" +"\n" +"ZERO = timedelta(0)\n" +"HOUR = timedelta(hours=1)\n" +"SECOND = timedelta(seconds=1)\n" +"\n" +"# A class capturing the platform's idea of local time.\n" +"# (May result in wrong values on historical times in\n" +"# timezones where UTC offset and/or the DST rules had\n" +"# changed in the past.)\n" +"import time as _time\n" +"\n" +"STDOFFSET = timedelta(seconds = -_time.timezone)\n" +"if _time.daylight:\n" +" DSTOFFSET = timedelta(seconds = -_time.altzone)\n" +"else:\n" +" DSTOFFSET = STDOFFSET\n" +"\n" +"DSTDIFF = DSTOFFSET - STDOFFSET\n" +"\n" +"class LocalTimezone(tzinfo):\n" +"\n" +" def fromutc(self, dt):\n" +" assert dt.tzinfo is self\n" +" stamp = (dt - datetime(1970, 1, 1, tzinfo=self)) // SECOND\n" +" args = _time.localtime(stamp)[:6]\n" +" dst_diff = DSTDIFF // SECOND\n" +" # Detect fold\n" +" fold = (args == _time.localtime(stamp - dst_diff))\n" +" return datetime(*args, microsecond=dt.microsecond,\n" +" tzinfo=self, fold=fold)\n" +"\n" +" def utcoffset(self, dt):\n" +" if self._isdst(dt):\n" +" return DSTOFFSET\n" +" else:\n" +" return STDOFFSET\n" +"\n" +" def dst(self, dt):\n" +" if self._isdst(dt):\n" +" return DSTDIFF\n" +" else:\n" +" return ZERO\n" +"\n" +" def tzname(self, dt):\n" +" return _time.tzname[self._isdst(dt)]\n" +"\n" +" def _isdst(self, dt):\n" +" tt = (dt.year, dt.month, dt.day,\n" +" dt.hour, dt.minute, dt.second,\n" +" dt.weekday(), 0, 0)\n" +" stamp = _time.mktime(tt)\n" +" tt = _time.localtime(stamp)\n" +" return tt.tm_isdst > 0\n" +"\n" +"Local = LocalTimezone()\n" +"\n" +"\n" +"# A complete implementation of current DST rules for major US time zones.\n" +"\n" +"def first_sunday_on_or_after(dt):\n" +" days_to_go = 6 - dt.weekday()\n" +" if days_to_go:\n" +" dt += timedelta(days_to_go)\n" +" return dt\n" +"\n" +"\n" +"# US DST Rules\n" +"#\n" +"# This is a simplified (i.e., wrong for a few cases) set of rules for US\n" +"# DST start and end times. For a complete and up-to-date set of DST rules\n" +"# and timezone definitions, visit the Olson Database (or try pytz):\n" +"# http://www.twinsun.com/tz/tz-link.htm\n" +"# https://sourceforge.net/projects/pytz/ (might not be up-to-date)\n" +"#\n" +"# In the US, since 2007, DST starts at 2am (standard time) on the second\n" +"# Sunday in March, which is the first Sunday on or after Mar 8.\n" +"DSTSTART_2007 = datetime(1, 3, 8, 2)\n" +"# and ends at 2am (DST time) on the first Sunday of Nov.\n" +"DSTEND_2007 = datetime(1, 11, 1, 2)\n" +"# From 1987 to 2006, DST used to start at 2am (standard time) on the first\n" +"# Sunday in April and to end at 2am (DST time) on the last\n" +"# Sunday of October, which is the first Sunday on or after Oct 25.\n" +"DSTSTART_1987_2006 = datetime(1, 4, 1, 2)\n" +"DSTEND_1987_2006 = datetime(1, 10, 25, 2)\n" +"# From 1967 to 1986, DST used to start at 2am (standard time) on the last\n" +"# Sunday in April (the one on or after April 24) and to end at 2am (DST " +"time)\n" +"# on the last Sunday of October, which is the first Sunday\n" +"# on or after Oct 25.\n" +"DSTSTART_1967_1986 = datetime(1, 4, 24, 2)\n" +"DSTEND_1967_1986 = DSTEND_1987_2006\n" +"\n" +"def us_dst_range(year):\n" +" # Find start and end times for US DST. For years before 1967, return\n" +" # start = end for no DST.\n" +" if 2006 < year:\n" +" dststart, dstend = DSTSTART_2007, DSTEND_2007\n" +" elif 1986 < year < 2007:\n" +" dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006\n" +" elif 1966 < year < 1987:\n" +" dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986\n" +" else:\n" +" return (datetime(year, 1, 1), ) * 2\n" +"\n" +" start = first_sunday_on_or_after(dststart.replace(year=year))\n" +" end = first_sunday_on_or_after(dstend.replace(year=year))\n" +" return start, end\n" +"\n" +"\n" +"class USTimeZone(tzinfo):\n" +"\n" +" def __init__(self, hours, reprname, stdname, dstname):\n" +" self.stdoffset = timedelta(hours=hours)\n" +" self.reprname = reprname\n" +" self.stdname = stdname\n" +" self.dstname = dstname\n" +"\n" +" def __repr__(self):\n" +" return self.reprname\n" +"\n" +" def tzname(self, dt):\n" +" if self.dst(dt):\n" +" return self.dstname\n" +" else:\n" +" return self.stdname\n" +"\n" +" def utcoffset(self, dt):\n" +" return self.stdoffset + self.dst(dt)\n" +"\n" +" def dst(self, dt):\n" +" if dt is None or dt.tzinfo is None:\n" +" # An exception may be sensible here, in one or both cases.\n" +" # It depends on how you want to treat them. The default\n" +" # fromutc() implementation (called by the default astimezone()\n" +" # implementation) passes a datetime with dt.tzinfo is self.\n" +" return ZERO\n" +" assert dt.tzinfo is self\n" +" start, end = us_dst_range(dt.year)\n" +" # Can't compare naive to aware objects, so strip the timezone from\n" +" # dt first.\n" +" dt = dt.replace(tzinfo=None)\n" +" if start + HOUR <= dt < end - HOUR:\n" +" # DST is in effect.\n" +" return HOUR\n" +" if end - HOUR <= dt < end:\n" +" # Fold (an ambiguous hour): use dt.fold to disambiguate.\n" +" return ZERO if dt.fold else HOUR\n" +" if start <= dt < start + HOUR:\n" +" # Gap (a non-existent hour): reverse the fold rule.\n" +" return HOUR if dt.fold else ZERO\n" +" # DST is off.\n" +" return ZERO\n" +"\n" +" def fromutc(self, dt):\n" +" assert dt.tzinfo is self\n" +" start, end = us_dst_range(dt.year)\n" +" start = start.replace(tzinfo=self)\n" +" end = end.replace(tzinfo=self)\n" +" std_time = dt + self.stdoffset\n" +" dst_time = std_time + HOUR\n" +" if end <= dst_time < end + HOUR:\n" +" # Repeated hour\n" +" return std_time.replace(fold=1)\n" +" if std_time < start or dst_time >= end:\n" +" # Standard time\n" +" return std_time\n" +" if start <= std_time < end - HOUR:\n" +" # Daylight saving time\n" +" return dst_time\n" +"\n" +"\n" +"Eastern = USTimeZone(-5, \"Eastern\", \"EST\", \"EDT\")\n" +"Central = USTimeZone(-6, \"Central\", \"CST\", \"CDT\")\n" +"Mountain = USTimeZone(-7, \"Mountain\", \"MST\", \"MDT\")\n" +"Pacific = USTimeZone(-8, \"Pacific\", \"PST\", \"PDT\")\n" +msgstr "" + +#: library/datetime.rst:2174 msgid "" "Note that there are unavoidable subtleties twice per year in a :class:" "`tzinfo` subclass accounting for both standard and daylight time, at the DST " @@ -2448,7 +3172,18 @@ msgid "" "ends the minute after 1:59 (EDT) on the first Sunday in November::" msgstr "" -#: library/datetime.rst:2164 +#: library/datetime.rst:2180 +msgid "" +" UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM\n" +" EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM\n" +" EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM\n" +"\n" +"start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM\n" +"\n" +" end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM" +msgstr "" + +#: library/datetime.rst:2188 msgid "" "When DST starts (the \"start\" line), the local wall clock leaps from 1:59 " "to 3:00. A wall time of the form 2:MM doesn't really make sense on that day, " @@ -2457,7 +3192,23 @@ msgid "" "get::" msgstr "" -#: library/datetime.rst:2183 +#: library/datetime.rst:2193 +msgid "" +">>> from datetime import datetime, timezone\n" +">>> from tzinfo_examples import HOUR, Eastern\n" +">>> u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc)\n" +">>> for i in range(4):\n" +"... u = u0 + i*HOUR\n" +"... t = u.astimezone(Eastern)\n" +"... print(u.time(), 'UTC =', t.time(), t.tzname())\n" +"...\n" +"05:00:00 UTC = 00:00:00 EST\n" +"06:00:00 UTC = 01:00:00 EST\n" +"07:00:00 UTC = 03:00:00 EDT\n" +"08:00:00 UTC = 04:00:00 EDT" +msgstr "" + +#: library/datetime.rst:2207 msgid "" "When DST ends (the \"end\" line), there's a potentially worse problem: " "there's an hour that can't be spelled unambiguously in local wall time: the " @@ -2472,13 +3223,27 @@ msgid "" "Fall back transition of 2016, we get::" msgstr "" -#: library/datetime.rst:2205 +#: library/datetime.rst:2218 +msgid "" +">>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)\n" +">>> for i in range(4):\n" +"... u = u0 + i*HOUR\n" +"... t = u.astimezone(Eastern)\n" +"... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)\n" +"...\n" +"04:00:00 UTC = 00:00:00 EDT 0\n" +"05:00:00 UTC = 01:00:00 EDT 0\n" +"06:00:00 UTC = 01:00:00 EST 1\n" +"07:00:00 UTC = 02:00:00 EST 0" +msgstr "" + +#: library/datetime.rst:2229 msgid "" "Note that the :class:`.datetime` instances that differ only by the value of " "the :attr:`~.datetime.fold` attribute are considered equal in comparisons." msgstr "" -#: library/datetime.rst:2208 +#: library/datetime.rst:2232 msgid "" "Applications that can't bear wall-time ambiguities should explicitly check " "the value of the :attr:`~.datetime.fold` attribute or avoid using hybrid :" @@ -2488,28 +3253,28 @@ msgid "" "offset -4 hours))." msgstr "" -#: library/datetime.rst:2216 +#: library/datetime.rst:2240 msgid ":mod:`zoneinfo`" msgstr "" -#: library/datetime.rst:2217 +#: library/datetime.rst:2241 msgid "" "The :mod:`!datetime` module has a basic :class:`timezone` class (for " "handling arbitrary fixed offsets from UTC) and its :attr:`timezone.utc` " "attribute (a UTC :class:`!timezone` instance)." msgstr "" -#: library/datetime.rst:2221 +#: library/datetime.rst:2245 msgid "" "``zoneinfo`` brings the *IANA time zone database* (also known as the Olson " "database) to Python, and its usage is recommended." msgstr "" -#: library/datetime.rst:2224 +#: library/datetime.rst:2248 msgid "`IANA time zone database `_" msgstr "" -#: library/datetime.rst:2225 +#: library/datetime.rst:2249 msgid "" "The Time Zone Database (often called tz, tzdata or zoneinfo) contains code " "and data that represent the history of local time for many representative " @@ -2518,24 +3283,24 @@ msgid "" "saving rules." msgstr "" -#: library/datetime.rst:2235 +#: library/datetime.rst:2259 msgid ":class:`timezone` Objects" msgstr "" -#: library/datetime.rst:2237 +#: library/datetime.rst:2261 msgid "" "The :class:`timezone` class is a subclass of :class:`tzinfo`, each instance " "of which represents a time zone defined by a fixed offset from UTC." msgstr "" -#: library/datetime.rst:2241 +#: library/datetime.rst:2265 msgid "" "Objects of this class cannot be used to represent time zone information in " "the locations where different offsets are used in different days of the year " "or where historical changes have been made to civil time." msgstr "" -#: library/datetime.rst:2248 +#: library/datetime.rst:2272 msgid "" "The *offset* argument must be specified as a :class:`timedelta` object " "representing the difference between the local time and UTC. It must be " @@ -2543,25 +3308,25 @@ msgid "" "otherwise :exc:`ValueError` is raised." msgstr "" -#: library/datetime.rst:2253 +#: library/datetime.rst:2277 msgid "" "The *name* argument is optional. If specified it must be a string that will " "be used as the value returned by the :meth:`datetime.tzname` method." msgstr "" -#: library/datetime.rst:2275 +#: library/datetime.rst:2299 msgid "" "Return the fixed value specified when the :class:`timezone` instance is " "constructed." msgstr "" -#: library/datetime.rst:2267 +#: library/datetime.rst:2291 msgid "" "The *dt* argument is ignored. The return value is a :class:`timedelta` " "instance equal to the difference between the local time and UTC." msgstr "" -#: library/datetime.rst:2278 +#: library/datetime.rst:2302 msgid "" "If *name* is not provided in the constructor, the name returned by " "``tzname(dt)`` is generated from the value of the ``offset`` as follows. If " @@ -2570,145 +3335,154 @@ msgid "" "are two digits of ``offset.hours`` and ``offset.minutes`` respectively." msgstr "" -#: library/datetime.rst:2284 +#: library/datetime.rst:2308 msgid "" "Name generated from ``offset=timedelta(0)`` is now plain ``'UTC'``, not " "``'UTC+00:00'``." msgstr "" -#: library/datetime.rst:2291 +#: library/datetime.rst:2315 msgid "Always returns ``None``." msgstr "" -#: library/datetime.rst:2295 +#: library/datetime.rst:2319 msgid "" "Return ``dt + offset``. The *dt* argument must be an aware :class:`." "datetime` instance, with ``tzinfo`` set to ``self``." msgstr "" -#: library/datetime.rst:2302 +#: library/datetime.rst:2326 msgid "The UTC time zone, ``timezone(timedelta(0))``." msgstr "" -#: library/datetime.rst:2311 +#: library/datetime.rst:2335 msgid ":meth:`~.datetime.strftime` and :meth:`~.datetime.strptime` Behavior" msgstr "" -#: library/datetime.rst:2313 +#: library/datetime.rst:2337 msgid "" ":class:`date`, :class:`.datetime`, and :class:`.time` objects all support a " "``strftime(format)`` method, to create a string representing the time under " "the control of an explicit format string." msgstr "" -#: library/datetime.rst:2317 +#: library/datetime.rst:2341 msgid "" "Conversely, the :meth:`datetime.strptime` class method creates a :class:`." "datetime` object from a string representing a date and time and a " "corresponding format string." msgstr "" -#: library/datetime.rst:2321 +#: library/datetime.rst:2345 msgid "" "The table below provides a high-level comparison of :meth:`~.datetime." "strftime` versus :meth:`~.datetime.strptime`:" msgstr "" -#: library/datetime.rst:2325 +#: library/datetime.rst:2349 msgid "``strftime``" msgstr "" -#: library/datetime.rst:2325 +#: library/datetime.rst:2349 msgid "``strptime``" msgstr "" -#: library/datetime.rst:2327 +#: library/datetime.rst:2351 msgid "Usage" msgstr "" -#: library/datetime.rst:2327 +#: library/datetime.rst:2351 msgid "Convert object to a string according to a given format" msgstr "" -#: library/datetime.rst:2327 +#: library/datetime.rst:2351 msgid "" "Parse a string into a :class:`.datetime` object given a corresponding format" msgstr "" -#: library/datetime.rst:2329 +#: library/datetime.rst:2353 msgid "Type of method" msgstr "" -#: library/datetime.rst:2329 +#: library/datetime.rst:2353 msgid "Instance method" msgstr "" -#: library/datetime.rst:2329 +#: library/datetime.rst:2353 msgid "Class method" msgstr "" -#: library/datetime.rst:2331 +#: library/datetime.rst:2355 msgid "Method of" msgstr "" -#: library/datetime.rst:2331 +#: library/datetime.rst:2355 msgid ":class:`date`; :class:`.datetime`; :class:`.time`" msgstr "" -#: library/datetime.rst:2331 +#: library/datetime.rst:2355 msgid ":class:`.datetime`" msgstr "" -#: library/datetime.rst:2333 +#: library/datetime.rst:2357 msgid "Signature" msgstr "" -#: library/datetime.rst:2333 +#: library/datetime.rst:2357 msgid "``strftime(format)``" msgstr "" -#: library/datetime.rst:2333 +#: library/datetime.rst:2357 msgid "``strptime(date_string, format)``" msgstr "" -#: library/datetime.rst:2340 +#: library/datetime.rst:2364 msgid "" ":meth:`~.datetime.strftime` and :meth:`~.datetime.strptime` Format Codes" msgstr "" -#: library/datetime.rst:2342 +#: library/datetime.rst:2366 msgid "" "These methods accept format codes that can be used to parse and format " "dates::" msgstr "" -#: library/datetime.rst:2350 +#: library/datetime.rst:2368 +msgid "" +">>> datetime.strptime('31/01/22 23:59:59.999999',\n" +"... '%d/%m/%y %H:%M:%S.%f')\n" +"datetime.datetime(2022, 1, 31, 23, 59, 59, 999999)\n" +">>> _.strftime('%a %d %b %Y, %I:%M%p')\n" +"'Mon 31 Jan 2022, 11:59PM'" +msgstr "" + +#: library/datetime.rst:2374 msgid "" "The following is a list of all the format codes that the 1989 C standard " "requires, and these work on all platforms with a standard C implementation." msgstr "" -#: library/datetime.rst:2457 +#: library/datetime.rst:2481 msgid "Directive" msgstr "" -#: library/datetime.rst:2457 +#: library/datetime.rst:2481 msgid "Meaning" msgstr "" -#: library/datetime.rst:2457 +#: library/datetime.rst:2481 msgid "Example" msgstr "" -#: library/datetime.rst:2457 +#: library/datetime.rst:2481 msgid "Notes" msgstr "" -#: library/datetime.rst:2356 +#: library/datetime.rst:2380 msgid "``%a``" msgstr "" -#: library/datetime.rst:2356 +#: library/datetime.rst:2380 msgid "Weekday as locale's abbreviated name." msgstr "" @@ -2720,11 +3494,11 @@ msgstr "" msgid "So, Mo, ..., Sa (de_DE)" msgstr "" -#: library/datetime.rst:2361 +#: library/datetime.rst:2385 msgid "``%A``" msgstr "" -#: library/datetime.rst:2361 +#: library/datetime.rst:2385 msgid "Weekday as locale's full name." msgstr "" @@ -2736,40 +3510,40 @@ msgstr "" msgid "Sonntag, Montag, ..., Samstag (de_DE)" msgstr "" -#: library/datetime.rst:2366 +#: library/datetime.rst:2390 msgid "``%w``" msgstr "" -#: library/datetime.rst:2366 +#: library/datetime.rst:2390 msgid "Weekday as a decimal number, where 0 is Sunday and 6 is Saturday." msgstr "" -#: library/datetime.rst:2366 +#: library/datetime.rst:2390 msgid "0, 1, ..., 6" msgstr "" -#: library/datetime.rst:2370 +#: library/datetime.rst:2394 msgid "``%d``" msgstr "" -#: library/datetime.rst:2370 +#: library/datetime.rst:2394 msgid "Day of the month as a zero-padded decimal number." msgstr "" -#: library/datetime.rst:2370 +#: library/datetime.rst:2394 msgid "01, 02, ..., 31" msgstr "" -#: library/datetime.rst:2383 library/datetime.rst:2392 -#: library/datetime.rst:2401 library/datetime.rst:2419 +#: library/datetime.rst:2407 library/datetime.rst:2416 +#: library/datetime.rst:2425 library/datetime.rst:2443 msgid "\\(9)" msgstr "" -#: library/datetime.rst:2373 +#: library/datetime.rst:2397 msgid "``%b``" msgstr "" -#: library/datetime.rst:2373 +#: library/datetime.rst:2397 msgid "Month as locale's abbreviated name." msgstr "" @@ -2781,11 +3555,11 @@ msgstr "" msgid "Jan, Feb, ..., Dez (de_DE)" msgstr "" -#: library/datetime.rst:2378 +#: library/datetime.rst:2402 msgid "``%B``" msgstr "" -#: library/datetime.rst:2378 +#: library/datetime.rst:2402 msgid "Month as locale's full name." msgstr "" @@ -2797,67 +3571,67 @@ msgstr "" msgid "Januar, Februar, ..., Dezember (de_DE)" msgstr "" -#: library/datetime.rst:2383 +#: library/datetime.rst:2407 msgid "``%m``" msgstr "" -#: library/datetime.rst:2383 +#: library/datetime.rst:2407 msgid "Month as a zero-padded decimal number." msgstr "" -#: library/datetime.rst:2395 +#: library/datetime.rst:2419 msgid "01, 02, ..., 12" msgstr "" -#: library/datetime.rst:2386 +#: library/datetime.rst:2410 msgid "``%y``" msgstr "" -#: library/datetime.rst:2386 +#: library/datetime.rst:2410 msgid "Year without century as a zero-padded decimal number." msgstr "" -#: library/datetime.rst:2386 +#: library/datetime.rst:2410 msgid "00, 01, ..., 99" msgstr "" -#: library/datetime.rst:2389 +#: library/datetime.rst:2413 msgid "``%Y``" msgstr "" -#: library/datetime.rst:2389 +#: library/datetime.rst:2413 msgid "Year with century as a decimal number." msgstr "" -#: library/datetime.rst:2459 +#: library/datetime.rst:2483 msgid "0001, 0002, ..., 2013, 2014, ..., 9998, 9999" msgstr "" -#: library/datetime.rst:2392 +#: library/datetime.rst:2416 msgid "``%H``" msgstr "" -#: library/datetime.rst:2392 +#: library/datetime.rst:2416 msgid "Hour (24-hour clock) as a zero-padded decimal number." msgstr "" -#: library/datetime.rst:2392 +#: library/datetime.rst:2416 msgid "00, 01, ..., 23" msgstr "" -#: library/datetime.rst:2395 +#: library/datetime.rst:2419 msgid "``%I``" msgstr "" -#: library/datetime.rst:2395 +#: library/datetime.rst:2419 msgid "Hour (12-hour clock) as a zero-padded decimal number." msgstr "" -#: library/datetime.rst:2398 +#: library/datetime.rst:2422 msgid "``%p``" msgstr "" -#: library/datetime.rst:2398 +#: library/datetime.rst:2422 msgid "Locale's equivalent of either AM or PM." msgstr "" @@ -2869,127 +3643,127 @@ msgstr "" msgid "am, pm (de_DE)" msgstr "" -#: library/datetime.rst:2398 +#: library/datetime.rst:2422 msgid "\\(1), \\(3)" msgstr "" -#: library/datetime.rst:2401 +#: library/datetime.rst:2425 msgid "``%M``" msgstr "" -#: library/datetime.rst:2401 +#: library/datetime.rst:2425 msgid "Minute as a zero-padded decimal number." msgstr "" -#: library/datetime.rst:2404 +#: library/datetime.rst:2428 msgid "00, 01, ..., 59" msgstr "" -#: library/datetime.rst:2404 +#: library/datetime.rst:2428 msgid "``%S``" msgstr "" -#: library/datetime.rst:2404 +#: library/datetime.rst:2428 msgid "Second as a zero-padded decimal number." msgstr "" -#: library/datetime.rst:2404 +#: library/datetime.rst:2428 msgid "\\(4), \\(9)" msgstr "" -#: library/datetime.rst:2407 +#: library/datetime.rst:2431 msgid "``%f``" msgstr "" -#: library/datetime.rst:2407 +#: library/datetime.rst:2431 msgid "Microsecond as a decimal number, zero-padded to 6 digits." msgstr "" -#: library/datetime.rst:2407 +#: library/datetime.rst:2431 msgid "000000, 000001, ..., 999999" msgstr "" -#: library/datetime.rst:2407 +#: library/datetime.rst:2431 msgid "\\(5)" msgstr "" -#: library/datetime.rst:2570 +#: library/datetime.rst:2594 msgid "``%z``" msgstr "" -#: library/datetime.rst:2411 +#: library/datetime.rst:2435 msgid "" "UTC offset in the form ``±HHMM[SS[.ffffff]]`` (empty string if the object is " "naive)." msgstr "" -#: library/datetime.rst:2411 +#: library/datetime.rst:2435 msgid "(empty), +0000, -0400, +1030, +063415, -030712.345216" msgstr "" -#: library/datetime.rst:2416 library/datetime.rst:2473 +#: library/datetime.rst:2440 library/datetime.rst:2497 msgid "\\(6)" msgstr "" -#: library/datetime.rst:2596 +#: library/datetime.rst:2620 msgid "``%Z``" msgstr "" -#: library/datetime.rst:2416 +#: library/datetime.rst:2440 msgid "Time zone name (empty string if the object is naive)." msgstr "" -#: library/datetime.rst:2416 +#: library/datetime.rst:2440 msgid "(empty), UTC, GMT" msgstr "" -#: library/datetime.rst:2419 +#: library/datetime.rst:2443 msgid "``%j``" msgstr "" -#: library/datetime.rst:2419 +#: library/datetime.rst:2443 msgid "Day of the year as a zero-padded decimal number." msgstr "" -#: library/datetime.rst:2419 +#: library/datetime.rst:2443 msgid "001, 002, ..., 366" msgstr "" -#: library/datetime.rst:2422 +#: library/datetime.rst:2446 msgid "``%U``" msgstr "" -#: library/datetime.rst:2422 +#: library/datetime.rst:2446 msgid "" "Week number of the year (Sunday as the first day of the week) as a zero-" "padded decimal number. All days in a new year preceding the first Sunday are " "considered to be in week 0." msgstr "" -#: library/datetime.rst:2430 +#: library/datetime.rst:2454 msgid "00, 01, ..., 53" msgstr "" -#: library/datetime.rst:2430 +#: library/datetime.rst:2454 msgid "\\(7), \\(9)" msgstr "" -#: library/datetime.rst:2430 +#: library/datetime.rst:2454 msgid "``%W``" msgstr "" -#: library/datetime.rst:2430 +#: library/datetime.rst:2454 msgid "" "Week number of the year (Monday as the first day of the week) as a zero-" "padded decimal number. All days in a new year preceding the first Monday are " "considered to be in week 0." msgstr "" -#: library/datetime.rst:2438 +#: library/datetime.rst:2462 msgid "``%c``" msgstr "" -#: library/datetime.rst:2438 +#: library/datetime.rst:2462 msgid "Locale's appropriate date and time representation." msgstr "" @@ -3001,11 +3775,11 @@ msgstr "" msgid "Di 16 Aug 21:30:00 1988 (de_DE)" msgstr "" -#: library/datetime.rst:2443 +#: library/datetime.rst:2467 msgid "``%x``" msgstr "" -#: library/datetime.rst:2443 +#: library/datetime.rst:2467 msgid "Locale's appropriate date representation." msgstr "" @@ -3021,11 +3795,11 @@ msgstr "" msgid "16.08.1988 (de_DE)" msgstr "" -#: library/datetime.rst:2447 +#: library/datetime.rst:2471 msgid "``%X``" msgstr "" -#: library/datetime.rst:2447 +#: library/datetime.rst:2471 msgid "Locale's appropriate time representation." msgstr "" @@ -3037,83 +3811,83 @@ msgstr "" msgid "21:30:00 (de_DE)" msgstr "" -#: library/datetime.rst:2450 +#: library/datetime.rst:2474 msgid "``%%``" msgstr "" -#: library/datetime.rst:2450 +#: library/datetime.rst:2474 msgid "A literal ``'%'`` character." msgstr "" -#: library/datetime.rst:2450 +#: library/datetime.rst:2474 msgid "%" msgstr "" -#: library/datetime.rst:2453 +#: library/datetime.rst:2477 msgid "" "Several additional directives not required by the C89 standard are included " "for convenience. These parameters all correspond to ISO 8601 date values." msgstr "" -#: library/datetime.rst:2459 +#: library/datetime.rst:2483 msgid "``%G``" msgstr "" -#: library/datetime.rst:2459 +#: library/datetime.rst:2483 msgid "" "ISO 8601 year with century representing the year that contains the greater " "part of the ISO week (``%V``)." msgstr "" -#: library/datetime.rst:2459 +#: library/datetime.rst:2483 msgid "\\(8)" msgstr "" -#: library/datetime.rst:2464 +#: library/datetime.rst:2488 msgid "``%u``" msgstr "" -#: library/datetime.rst:2464 +#: library/datetime.rst:2488 msgid "ISO 8601 weekday as a decimal number where 1 is Monday." msgstr "" -#: library/datetime.rst:2464 +#: library/datetime.rst:2488 msgid "1, 2, ..., 7" msgstr "" -#: library/datetime.rst:2467 +#: library/datetime.rst:2491 msgid "``%V``" msgstr "" -#: library/datetime.rst:2467 +#: library/datetime.rst:2491 msgid "" "ISO 8601 week as a decimal number with Monday as the first day of the week. " "Week 01 is the week containing Jan 4." msgstr "" -#: library/datetime.rst:2467 +#: library/datetime.rst:2491 msgid "01, 02, ..., 53" msgstr "" -#: library/datetime.rst:2467 +#: library/datetime.rst:2491 msgid "\\(8), \\(9)" msgstr "" -#: library/datetime.rst:2592 +#: library/datetime.rst:2616 msgid "``%:z``" msgstr "" -#: library/datetime.rst:2473 +#: library/datetime.rst:2497 msgid "" "UTC offset in the form ``±HH:MM[:SS[.ffffff]]`` (empty string if the object " "is naive)." msgstr "" -#: library/datetime.rst:2473 +#: library/datetime.rst:2497 msgid "(empty), +00:00, -04:00, +10:30, +06:34:15, -03:07:12.345216" msgstr "" -#: library/datetime.rst:2479 +#: library/datetime.rst:2503 msgid "" "These may not be available on all platforms when used with the :meth:`~." "datetime.strftime` method. The ISO 8601 year and ISO 8601 week directives " @@ -3122,7 +3896,7 @@ msgid "" "directives will raise a :exc:`ValueError`." msgstr "" -#: library/datetime.rst:2484 +#: library/datetime.rst:2508 msgid "" "The full set of format codes supported varies across platforms, because " "Python calls the platform C library's :c:func:`strftime` function, and " @@ -3132,58 +3906,58 @@ msgid "" "unsupported format specifiers." msgstr "" -#: library/datetime.rst:2490 +#: library/datetime.rst:2514 msgid "``%G``, ``%u`` and ``%V`` were added." msgstr "" -#: library/datetime.rst:2493 +#: library/datetime.rst:2517 msgid "``%:z`` was added." msgstr "" -#: library/datetime.rst:2497 +#: library/datetime.rst:2521 msgid "Technical Detail" msgstr "" -#: library/datetime.rst:2499 +#: library/datetime.rst:2523 msgid "" "Broadly speaking, ``d.strftime(fmt)`` acts like the :mod:`time` module's " "``time.strftime(fmt, d.timetuple())`` although not all objects support a :" "meth:`~date.timetuple` method." msgstr "" -#: library/datetime.rst:2503 +#: library/datetime.rst:2527 msgid "" "For the :meth:`.datetime.strptime` class method, the default value is " "``1900-01-01T00:00:00.000``: any components not specified in the format " "string will be pulled from the default value. [#]_" msgstr "" -#: library/datetime.rst:2507 +#: library/datetime.rst:2531 msgid "Using ``datetime.strptime(date_string, format)`` is equivalent to::" msgstr "" -#: library/datetime.rst:2511 +#: library/datetime.rst:2535 msgid "" "except when the format includes sub-second components or time zone offset " "information, which are supported in ``datetime.strptime`` but are discarded " "by ``time.strptime``." msgstr "" -#: library/datetime.rst:2515 +#: library/datetime.rst:2539 msgid "" "For :class:`.time` objects, the format codes for year, month, and day should " "not be used, as :class:`!time` objects have no such values. If they're used " "anyway, 1900 is substituted for the year, and 1 for the month and day." msgstr "" -#: library/datetime.rst:2519 +#: library/datetime.rst:2543 msgid "" "For :class:`date` objects, the format codes for hours, minutes, seconds, and " "microseconds should not be used, as :class:`date` objects have no such " "values. If they're used anyway, 0 is substituted for them." msgstr "" -#: library/datetime.rst:2523 +#: library/datetime.rst:2547 msgid "" "For the same reason, handling of format strings containing Unicode code " "points that can't be represented in the charset of the current locale is " @@ -3192,7 +3966,7 @@ msgid "" "`UnicodeError` or return an empty string instead." msgstr "" -#: library/datetime.rst:2532 +#: library/datetime.rst:2556 msgid "" "Because the format depends on the current locale, care should be taken when " "making assumptions about the output value. Field orderings will vary (for " @@ -3200,38 +3974,38 @@ msgid "" "contain non-ASCII characters." msgstr "" -#: library/datetime.rst:2538 +#: library/datetime.rst:2562 msgid "" "The :meth:`~.datetime.strptime` method can parse years in the full [1, 9999] " "range, but years < 1000 must be zero-filled to 4-digit width." msgstr "" -#: library/datetime.rst:2541 +#: library/datetime.rst:2565 msgid "" "In previous versions, :meth:`~.datetime.strftime` method was restricted to " "years >= 1900." msgstr "" -#: library/datetime.rst:2545 +#: library/datetime.rst:2569 msgid "" "In version 3.2, :meth:`~.datetime.strftime` method was restricted to years " ">= 1000." msgstr "" -#: library/datetime.rst:2550 +#: library/datetime.rst:2574 msgid "" "When used with the :meth:`~.datetime.strptime` method, the ``%p`` directive " "only affects the output hour field if the ``%I`` directive is used to parse " "the hour." msgstr "" -#: library/datetime.rst:2554 +#: library/datetime.rst:2578 msgid "" "Unlike the :mod:`time` module, the :mod:`!datetime` module does not support " "leap seconds." msgstr "" -#: library/datetime.rst:2558 +#: library/datetime.rst:2582 msgid "" "When used with the :meth:`~.datetime.strptime` method, the ``%f`` directive " "accepts from one to six digits and zero pads on the right. ``%f`` is an " @@ -3239,17 +4013,17 @@ msgid "" "separately in datetime objects, and therefore always available)." msgstr "" -#: library/datetime.rst:2565 +#: library/datetime.rst:2589 msgid "" "For a naive object, the ``%z``, ``%:z`` and ``%Z`` format codes are replaced " "by empty strings." msgstr "" -#: library/datetime.rst:2568 +#: library/datetime.rst:2592 msgid "For an aware object:" msgstr "" -#: library/datetime.rst:2571 +#: library/datetime.rst:2595 msgid "" ":meth:`~.datetime.utcoffset` is transformed into a string of the form " "``±HHMM[SS[.ffffff]]``, where ``HH`` is a 2-digit string giving the number " @@ -3263,7 +4037,7 @@ msgid "" "replaced with the string ``'-0330'``." msgstr "" -#: library/datetime.rst:2585 +#: library/datetime.rst:2609 msgid "" "When the ``%z`` directive is provided to the :meth:`~.datetime.strptime` " "method, the UTC offsets can have a colon as a separator between hours, " @@ -3272,53 +4046,53 @@ msgid "" "``'+00:00'``." msgstr "" -#: library/datetime.rst:2593 +#: library/datetime.rst:2617 msgid "" "Behaves exactly as ``%z``, but has a colon separator added between hours, " "minutes and seconds." msgstr "" -#: library/datetime.rst:2597 +#: library/datetime.rst:2621 msgid "" "In :meth:`~.datetime.strftime`, ``%Z`` is replaced by an empty string if :" "meth:`~.datetime.tzname` returns ``None``; otherwise ``%Z`` is replaced by " "the returned value, which must be a string." msgstr "" -#: library/datetime.rst:2601 +#: library/datetime.rst:2625 msgid ":meth:`~.datetime.strptime` only accepts certain values for ``%Z``:" msgstr "" -#: library/datetime.rst:2603 +#: library/datetime.rst:2627 msgid "any value in ``time.tzname`` for your machine's locale" msgstr "" -#: library/datetime.rst:2604 +#: library/datetime.rst:2628 msgid "the hard-coded values ``UTC`` and ``GMT``" msgstr "" -#: library/datetime.rst:2606 +#: library/datetime.rst:2630 msgid "" "So someone living in Japan may have ``JST``, ``UTC``, and ``GMT`` as valid " "values, but probably not ``EST``. It will raise ``ValueError`` for invalid " "values." msgstr "" -#: library/datetime.rst:2610 +#: library/datetime.rst:2634 msgid "" "When the ``%z`` directive is provided to the :meth:`~.datetime.strptime` " "method, an aware :class:`.datetime` object will be produced. The ``tzinfo`` " "of the result will be set to a :class:`timezone` instance." msgstr "" -#: library/datetime.rst:2616 +#: library/datetime.rst:2640 msgid "" "When used with the :meth:`~.datetime.strptime` method, ``%U`` and ``%W`` are " "only used in calculations when the day of the week and the calendar year " "(``%Y``) are specified." msgstr "" -#: library/datetime.rst:2621 +#: library/datetime.rst:2645 msgid "" "Similar to ``%U`` and ``%W``, ``%V`` is only used in calculations when the " "day of the week and the ISO year (``%G``) are specified in a :meth:`~." @@ -3326,7 +4100,7 @@ msgid "" "interchangeable." msgstr "" -#: library/datetime.rst:2627 +#: library/datetime.rst:2651 msgid "" "When used with the :meth:`~.datetime.strptime` method, the leading zero is " "optional for formats ``%d``, ``%m``, ``%H``, ``%I``, ``%M``, ``%S``, " @@ -3334,15 +4108,15 @@ msgid "" "zero." msgstr "" -#: library/datetime.rst:2632 +#: library/datetime.rst:2656 msgid "Footnotes" msgstr "" -#: library/datetime.rst:2633 +#: library/datetime.rst:2657 msgid "If, that is, we ignore the effects of Relativity" msgstr "" -#: library/datetime.rst:2635 +#: library/datetime.rst:2659 msgid "" "This matches the definition of the \"proleptic Gregorian\" calendar in " "Dershowitz and Reingold's book *Calendrical Calculations*, where it's the " @@ -3351,26 +4125,41 @@ msgid "" "systems." msgstr "" -#: library/datetime.rst:2641 +#: library/datetime.rst:2665 msgid "" "See R. H. van Gent's `guide to the mathematics of the ISO 8601 calendar " "`_ for a good explanation." msgstr "" -#: library/datetime.rst:2645 +#: library/datetime.rst:2669 msgid "" "Passing ``datetime.strptime('Feb 29', '%b %d')`` will fail since 1900 is not " "a leap year." msgstr "" -#: library/datetime.rst:2305 +#: library/datetime.rst:2329 msgid "% (percent)" msgstr "" -#: library/datetime.rst:2305 +#: library/datetime.rst:2329 msgid "datetime format" msgstr "" +#~ msgid "Attribute" +#~ msgstr "Özellik" + +#~ msgid "Value" +#~ msgstr "Değer" + +#~ msgid "``days``" +#~ msgstr "``days``" + +#~ msgid "``seconds``" +#~ msgstr "``seconds``" + +#~ msgid "``microseconds``" +#~ msgstr "``microseconds``" + #~ msgid "Package `DateType `_" #~ msgstr "Paket `DateType `_" diff --git a/library/dbm.po b/library/dbm.po index a0e460733..1785fecc4 100644 --- a/library/dbm.po +++ b/library/dbm.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -173,6 +173,33 @@ msgid "" "then prints out the contents of the database::" msgstr "" +#: library/dbm.rst:110 +msgid "" +"import dbm\n" +"\n" +"# Open database, creating it if necessary.\n" +"with dbm.open('cache', 'c') as db:\n" +"\n" +" # Record some values\n" +" db[b'hello'] = b'there'\n" +" db['www.python.org'] = 'Python Website'\n" +" db['www.cnn.com'] = 'Cable News Network'\n" +"\n" +" # Note that the keys are considered bytes now.\n" +" assert db[b'www.python.org'] == b'Python Website'\n" +" # Notice how the value is now in bytes.\n" +" assert db['www.cnn.com'] == b'Cable News Network'\n" +"\n" +" # Often-used methods of the dict interface work too.\n" +" print(db.get('python.org', b'not present'))\n" +"\n" +" # Storing a non-string key or value will raise an exception (most\n" +" # likely a TypeError).\n" +" db['www.yahoo.com'] = 4\n" +"\n" +"# db is automatically closed when leaving the with statement." +msgstr "" + #: library/dbm.rst:137 msgid "Module :mod:`shelve`" msgstr "" @@ -293,6 +320,14 @@ msgid "" "memory that contains them all::" msgstr "" +#: library/dbm.rst:226 +msgid "" +"k = db.firstkey()\n" +"while k is not None:\n" +" print(k)\n" +" k = db.nextkey(k)" +msgstr "" + #: library/dbm.rst:233 msgid "" "If you have carried out a lot of deletions and would like to shrink the " diff --git a/library/decimal.po b/library/decimal.po index 5fa5168fe..104197fe8 100644 --- a/library/decimal.po +++ b/library/decimal.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -154,6 +154,17 @@ msgid "" "values for precision, rounding, or enabled traps::" msgstr "" +#: library/decimal.rst:131 +msgid "" +">>> from decimal import *\n" +">>> getcontext()\n" +"Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,\n" +" capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,\n" +" InvalidOperation])\n" +"\n" +">>> getcontext().prec = 7 # Set a new precision" +msgstr "" + #: library/decimal.rst:139 msgid "" "Decimal instances can be constructed from integers, strings, floats, or " @@ -163,6 +174,27 @@ msgid "" "negative ``Infinity``, and ``-0``::" msgstr "" +#: library/decimal.rst:145 +msgid "" +">>> getcontext().prec = 28\n" +">>> Decimal(10)\n" +"Decimal('10')\n" +">>> Decimal('3.14')\n" +"Decimal('3.14')\n" +">>> Decimal(3.14)\n" +"Decimal('3.140000000000000124344978758017532527446746826171875')\n" +">>> Decimal((0, (3, 1, 4), -2))\n" +"Decimal('3.14')\n" +">>> Decimal(str(2.0 ** 0.5))\n" +"Decimal('1.4142135623730951')\n" +">>> Decimal(2) ** Decimal('0.5')\n" +"Decimal('1.414213562373095048801688724')\n" +">>> Decimal('NaN')\n" +"Decimal('NaN')\n" +">>> Decimal('-Infinity')\n" +"Decimal('-Infinity')" +msgstr "" + #: library/decimal.rst:163 msgid "" "If the :exc:`FloatOperation` signal is trapped, accidental mixing of " @@ -170,6 +202,22 @@ msgid "" "exception::" msgstr "" +#: library/decimal.rst:167 +msgid "" +">>> c = getcontext()\n" +">>> c.traps[FloatOperation] = True\n" +">>> Decimal(3.14)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"decimal.FloatOperation: []\n" +">>> Decimal('3.5') < 3.7\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"decimal.FloatOperation: []\n" +">>> Decimal('3.5') == 3.5\n" +"True" +msgstr "" + #: library/decimal.rst:182 msgid "" "The significance of a new Decimal is determined solely by the number of " @@ -177,18 +225,69 @@ msgid "" "arithmetic operations." msgstr "" +#: library/decimal.rst:186 +msgid "" +">>> getcontext().prec = 6\n" +">>> Decimal('3.0')\n" +"Decimal('3.0')\n" +">>> Decimal('3.1415926535')\n" +"Decimal('3.1415926535')\n" +">>> Decimal('3.1415926535') + Decimal('2.7182818285')\n" +"Decimal('5.85987')\n" +">>> getcontext().rounding = ROUND_UP\n" +">>> Decimal('3.1415926535') + Decimal('2.7182818285')\n" +"Decimal('5.85988')" +msgstr "" + #: library/decimal.rst:199 msgid "" "If the internal limits of the C version are exceeded, constructing a decimal " "raises :class:`InvalidOperation`::" msgstr "" +#: library/decimal.rst:202 +msgid "" +">>> Decimal(\"1e9999999999999999999\")\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"decimal.InvalidOperation: []" +msgstr "" + #: library/decimal.rst:209 msgid "" "Decimals interact well with much of the rest of Python. Here is a small " "decimal floating-point flying circus:" msgstr "" +#: library/decimal.rst:212 +msgid "" +">>> data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()))\n" +">>> max(data)\n" +"Decimal('9.25')\n" +">>> min(data)\n" +"Decimal('0.03')\n" +">>> sorted(data)\n" +"[Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),\n" +" Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]\n" +">>> sum(data)\n" +"Decimal('19.29')\n" +">>> a,b,c = data[:3]\n" +">>> str(a)\n" +"'1.34'\n" +">>> float(a)\n" +"1.34\n" +">>> round(a, 1)\n" +"Decimal('1.3')\n" +">>> int(a)\n" +"1\n" +">>> a * 5\n" +"Decimal('6.70')\n" +">>> a * b\n" +"Decimal('2.5058')\n" +">>> c % a\n" +"Decimal('0.77')" +msgstr "" + #: library/decimal.rst:241 msgid "And some mathematical functions are also available to Decimal:" msgstr "" @@ -222,6 +321,30 @@ msgid "" "many of the traps are enabled:" msgstr "" +#: library/decimal.rst:275 +msgid "" +">>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)\n" +">>> setcontext(myothercontext)\n" +">>> Decimal(1) / Decimal(7)\n" +"Decimal('0.142857142857142857142857142857142857142857142857142857142857')\n" +"\n" +">>> ExtendedContext\n" +"Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,\n" +" capitals=1, clamp=0, flags=[], traps=[])\n" +">>> setcontext(ExtendedContext)\n" +">>> Decimal(1) / Decimal(7)\n" +"Decimal('0.142857143')\n" +">>> Decimal(42) / Decimal(0)\n" +"Decimal('Infinity')\n" +"\n" +">>> setcontext(BasicContext)\n" +">>> Decimal(42) / Decimal(0)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in -toplevel-\n" +" Decimal(42) / Decimal(0)\n" +"DivisionByZero: x / 0" +msgstr "" + #: library/decimal.rst:299 msgid "" "Contexts also have signal flags for monitoring exceptional conditions " @@ -230,6 +353,17 @@ msgid "" "computations by using the :meth:`~Context.clear_flags` method. ::" msgstr "" +#: library/decimal.rst:304 +msgid "" +">>> setcontext(ExtendedContext)\n" +">>> getcontext().clear_flags()\n" +">>> Decimal(355) / Decimal(113)\n" +"Decimal('3.14159292')\n" +">>> getcontext()\n" +"Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,\n" +" capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[])" +msgstr "" + #: library/decimal.rst:312 msgid "" "The *flags* entry shows that the rational approximation to pi was rounded " @@ -243,6 +377,19 @@ msgid "" "attribute of a context:" msgstr "" +#: library/decimal.rst:319 +msgid "" +">>> setcontext(ExtendedContext)\n" +">>> Decimal(1) / Decimal(0)\n" +"Decimal('Infinity')\n" +">>> getcontext().traps[DivisionByZero] = 1\n" +">>> Decimal(1) / Decimal(0)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in -toplevel-\n" +" Decimal(1) / Decimal(0)\n" +"DivisionByZero: x / 0" +msgstr "" + #: library/decimal.rst:331 msgid "" "Most programs adjust the current context only once, at the beginning of the " @@ -269,6 +416,21 @@ msgid "" "throughout, are removed::" msgstr "" +#: library/decimal.rst:355 +msgid "" +"sign ::= '+' | '-'\n" +"digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | " +"'9'\n" +"indicator ::= 'e' | 'E'\n" +"digits ::= digit [digit]...\n" +"decimal-part ::= digits '.' [digits] | ['.'] digits\n" +"exponent-part ::= indicator [sign] digits\n" +"infinity ::= 'Infinity' | 'Inf'\n" +"nan ::= 'NaN' [digits] | 'sNaN' [digits]\n" +"numeric-value ::= decimal-part [exponent-part] | infinity\n" +"numeric-string ::= [sign] numeric-value | [sign] nan" +msgstr "" + #: library/decimal.rst:366 msgid "" "Other Unicode decimal digits are also permitted where ``digit`` appears " @@ -350,6 +512,14 @@ msgid "" "*dividend* rather than the sign of the divisor::" msgstr "" +#: library/decimal.rst:418 +msgid "" +">>> (-7) % 4\n" +"1\n" +">>> Decimal(-7) % Decimal(4)\n" +"Decimal('-3')" +msgstr "" + #: library/decimal.rst:423 msgid "" "The integer division operator ``//`` behaves analogously, returning the " @@ -357,6 +527,14 @@ msgid "" "floor, so as to preserve the usual identity ``x == (x // y) * y + x % y``::" msgstr "" +#: library/decimal.rst:427 +msgid "" +">>> -7 // 4\n" +"-2\n" +">>> Decimal(-7) // Decimal(4)\n" +"Decimal('-1')" +msgstr "" + #: library/decimal.rst:432 msgid "" "The ``%`` and ``//`` operators implement the ``remainder`` and ``divide-" @@ -401,6 +579,12 @@ msgid "" "denominator::" msgstr "" +#: library/decimal.rst:465 +msgid "" +">>> Decimal('-3.14').as_integer_ratio()\n" +"(-157, 50)" +msgstr "" + #: library/decimal.rst:468 msgid "" "The conversion is exact. Raise OverflowError on infinities and ValueError " @@ -426,6 +610,14 @@ msgid "" "Decimal instance, and if either operand is a NaN then the result is a NaN::" msgstr "" +#: library/decimal.rst:491 +msgid "" +"a or b is a NaN ==> Decimal('NaN')\n" +"a < b ==> Decimal('-1')\n" +"a == b ==> Decimal('0')\n" +"a > b ==> Decimal('1')" +msgstr "" + #: library/decimal.rst:498 msgid "" "This operation is identical to the :meth:`compare` method, except that all " @@ -519,6 +711,18 @@ msgid "" "directly from a :class:`float`." msgstr "" +#: library/decimal.rst:588 +msgid "" +">>> Decimal.from_float(0.1)\n" +"Decimal('0.1000000000000000055511151231257827021181583404541015625')\n" +">>> Decimal.from_float(float('nan'))\n" +"Decimal('NaN')\n" +">>> Decimal.from_float(float('inf'))\n" +"Decimal('Infinity')\n" +">>> Decimal.from_float(float('-inf'))\n" +"Decimal('-Infinity')" +msgstr "" + #: library/decimal.rst:603 msgid "" "Fused multiply-add. Return self*other+third with no rounding of the " @@ -939,6 +1143,22 @@ msgstr "" msgid "For example::" msgstr "" +#: library/decimal.rst:929 +msgid "" +">>> from decimal import Decimal, getcontext, ROUND_DOWN\n" +">>> getcontext().rounding = ROUND_DOWN\n" +">>> round(Decimal('3.75')) # context rounding ignored\n" +"4\n" +">>> round(Decimal('3.5')) # round-ties-to-even\n" +"4\n" +">>> round(Decimal('3.75'), 0) # uses the context rounding\n" +"Decimal('3')\n" +">>> round(Decimal('3.75'), 1)\n" +"Decimal('3.7')\n" +">>> round(Decimal('3.75'), -1)\n" +"Decimal('0E+1')" +msgstr "" + #: library/decimal.rst:946 msgid "Logical operands" msgstr "" @@ -999,10 +1219,29 @@ msgid "" "context::" msgstr "" +#: library/decimal.rst:993 +msgid "" +"from decimal import localcontext\n" +"\n" +"with localcontext() as ctx:\n" +" ctx.prec = 42 # Perform a high precision calculation\n" +" s = calculate_something()\n" +"s = +s # Round the final result back to the default precision" +msgstr "" + #: library/decimal.rst:1000 msgid "Using keyword arguments, the code would be the following::" msgstr "" +#: library/decimal.rst:1002 +msgid "" +"from decimal import localcontext\n" +"\n" +"with localcontext(prec=42) as ctx:\n" +" s = calculate_something()\n" +"s = +s" +msgstr "" + #: library/decimal.rst:1008 msgid "" "Raises :exc:`TypeError` if *kwargs* supplies an attribute that :class:" @@ -1140,6 +1379,12 @@ msgid "" "For example::" msgstr "" +#: library/decimal.rst:1101 +msgid "" +">>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')\n" +"Decimal('1.23000E+999')" +msgstr "" + #: library/decimal.rst:1104 msgid "" "A *clamp* value of ``1`` allows compatibility with the fixed-width decimal " @@ -1191,6 +1436,15 @@ msgid "" "sum can change the result:" msgstr "" +#: library/decimal.rst:1148 +msgid "" +">>> getcontext().prec = 3\n" +">>> Decimal('3.4445') + Decimal('1.0023')\n" +"Decimal('4.45')\n" +">>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')\n" +"Decimal('4.44')" +msgstr "" + #: library/decimal.rst:1156 msgid "" "This method implements the to-number operation of the IBM specification. If " @@ -1206,6 +1460,18 @@ msgid "" "conversion." msgstr "" +#: library/decimal.rst:1167 +msgid "" +">>> context = Context(prec=5, rounding=ROUND_DOWN)\n" +">>> context.create_decimal_from_float(math.pi)\n" +"Decimal('3.1415')\n" +">>> context = Context(prec=5, traps=[Inexact])\n" +">>> context.create_decimal_from_float(math.pi)\n" +"Traceback (most recent call last):\n" +" ...\n" +"decimal.Inexact: None" +msgstr "" + #: library/decimal.rst:1182 msgid "" "Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent " @@ -1685,6 +1951,19 @@ msgid "" "trapped, returns ``NaN``. Possible causes include::" msgstr "" +#: library/decimal.rst:1660 +msgid "" +"Infinity - Infinity\n" +"0 * Infinity\n" +"Infinity / Infinity\n" +"x % 0\n" +"Infinity % x\n" +"sqrt(-x) and x > 0\n" +"0 ** 0\n" +"x ** (non-integer)\n" +"x ** Infinity" +msgstr "" + #: library/decimal.rst:1673 msgid "Numerical overflow." msgstr "" @@ -1755,6 +2034,21 @@ msgstr "" msgid "The following table summarizes the hierarchy of signals::" msgstr "" +#: library/decimal.rst:1726 +msgid "" +"exceptions.ArithmeticError(exceptions.Exception)\n" +" DecimalException\n" +" Clamped\n" +" DivisionByZero(DecimalException, exceptions.ZeroDivisionError)\n" +" Inexact\n" +" Overflow(Inexact, Rounded)\n" +" Underflow(Inexact, Rounded, Subnormal)\n" +" InvalidOperation\n" +" Rounded\n" +" Subnormal\n" +" FloatOperation(DecimalException, exceptions.TypeError)" +msgstr "" + #: library/decimal.rst:1745 msgid "Floating-Point Notes" msgstr "" @@ -1780,12 +2074,47 @@ msgid "" "of the associative and distributive properties of addition:" msgstr "" +#: library/decimal.rst:1761 +msgid "" +"# Examples from Seminumerical Algorithms, Section 4.2.2.\n" +">>> from decimal import Decimal, getcontext\n" +">>> getcontext().prec = 8\n" +"\n" +">>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')\n" +">>> (u + v) + w\n" +"Decimal('9.5111111')\n" +">>> u + (v + w)\n" +"Decimal('10')\n" +"\n" +">>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')\n" +">>> (u*v) + (u*w)\n" +"Decimal('0.01')\n" +">>> u * (v+w)\n" +"Decimal('0.0060000')" +msgstr "" + #: library/decimal.rst:1779 msgid "" "The :mod:`decimal` module makes it possible to restore the identities by " "expanding the precision sufficiently to avoid loss of significance:" msgstr "" +#: library/decimal.rst:1782 +msgid "" +">>> getcontext().prec = 20\n" +">>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')\n" +">>> (u + v) + w\n" +"Decimal('9.51111111')\n" +">>> u + (v + w)\n" +"Decimal('9.51111111')\n" +">>>\n" +">>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')\n" +">>> (u*v) + (u*w)\n" +"Decimal('0.0060000')\n" +">>> u * (v+w)\n" +"Decimal('0.0060000')" +msgstr "" + #: library/decimal.rst:1799 msgid "Special values" msgstr "" @@ -1899,6 +2228,22 @@ msgid "" "a race condition between threads calling :func:`getcontext`. For example::" msgstr "" +#: library/decimal.rst:1878 +msgid "" +"# Set applicationwide defaults for all threads about to be launched\n" +"DefaultContext.prec = 12\n" +"DefaultContext.rounding = ROUND_DOWN\n" +"DefaultContext.traps = ExtendedContext.traps.copy()\n" +"DefaultContext.traps[InvalidOperation] = 1\n" +"setcontext(DefaultContext)\n" +"\n" +"# Afterwards, the threads can be started\n" +"t1.start()\n" +"t2.start()\n" +"t3.start()\n" +" . . ." +msgstr "" + #: library/decimal.rst:1897 msgid "Recipes" msgstr "" @@ -1909,6 +2254,155 @@ msgid "" "ways to work with the :class:`Decimal` class::" msgstr "" +#: library/decimal.rst:1902 +msgid "" +"def moneyfmt(value, places=2, curr='', sep=',', dp='.',\n" +" pos='', neg='-', trailneg=''):\n" +" \"\"\"Convert Decimal to a money formatted string.\n" +"\n" +" places: required number of places after the decimal point\n" +" curr: optional currency symbol before the sign (may be blank)\n" +" sep: optional grouping separator (comma, period, space, or blank)\n" +" dp: decimal point indicator (comma or period)\n" +" only specify as blank when places is zero\n" +" pos: optional sign for positive numbers: '+', space or blank\n" +" neg: optional sign for negative numbers: '-', '(', space or blank\n" +" trailneg:optional trailing minus indicator: '-', ')', space or blank\n" +"\n" +" >>> d = Decimal('-1234567.8901')\n" +" >>> moneyfmt(d, curr='$')\n" +" '-$1,234,567.89'\n" +" >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')\n" +" '1.234.568-'\n" +" >>> moneyfmt(d, curr='$', neg='(', trailneg=')')\n" +" '($1,234,567.89)'\n" +" >>> moneyfmt(Decimal(123456789), sep=' ')\n" +" '123 456 789.00'\n" +" >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')\n" +" '<0.02>'\n" +"\n" +" \"\"\"\n" +" q = Decimal(10) ** -places # 2 places --> '0.01'\n" +" sign, digits, exp = value.quantize(q).as_tuple()\n" +" result = []\n" +" digits = list(map(str, digits))\n" +" build, next = result.append, digits.pop\n" +" if sign:\n" +" build(trailneg)\n" +" for i in range(places):\n" +" build(next() if digits else '0')\n" +" if places:\n" +" build(dp)\n" +" if not digits:\n" +" build('0')\n" +" i = 0\n" +" while digits:\n" +" build(next())\n" +" i += 1\n" +" if i == 3 and digits:\n" +" i = 0\n" +" build(sep)\n" +" build(curr)\n" +" build(neg if sign else pos)\n" +" return ''.join(reversed(result))\n" +"\n" +"def pi():\n" +" \"\"\"Compute Pi to the current precision.\n" +"\n" +" >>> print(pi())\n" +" 3.141592653589793238462643383\n" +"\n" +" \"\"\"\n" +" getcontext().prec += 2 # extra digits for intermediate steps\n" +" three = Decimal(3) # substitute \"three=3.0\" for regular floats\n" +" lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24\n" +" while s != lasts:\n" +" lasts = s\n" +" n, na = n+na, na+8\n" +" d, da = d+da, da+32\n" +" t = (t * n) / d\n" +" s += t\n" +" getcontext().prec -= 2\n" +" return +s # unary plus applies the new precision\n" +"\n" +"def exp(x):\n" +" \"\"\"Return e raised to the power of x. Result type matches input " +"type.\n" +"\n" +" >>> print(exp(Decimal(1)))\n" +" 2.718281828459045235360287471\n" +" >>> print(exp(Decimal(2)))\n" +" 7.389056098930650227230427461\n" +" >>> print(exp(2.0))\n" +" 7.38905609893\n" +" >>> print(exp(2+0j))\n" +" (7.38905609893+0j)\n" +"\n" +" \"\"\"\n" +" getcontext().prec += 2\n" +" i, lasts, s, fact, num = 0, 0, 1, 1, 1\n" +" while s != lasts:\n" +" lasts = s\n" +" i += 1\n" +" fact *= i\n" +" num *= x\n" +" s += num / fact\n" +" getcontext().prec -= 2\n" +" return +s\n" +"\n" +"def cos(x):\n" +" \"\"\"Return the cosine of x as measured in radians.\n" +"\n" +" The Taylor series approximation works best for a small value of x.\n" +" For larger values, first compute x = x % (2 * pi).\n" +"\n" +" >>> print(cos(Decimal('0.5')))\n" +" 0.8775825618903727161162815826\n" +" >>> print(cos(0.5))\n" +" 0.87758256189\n" +" >>> print(cos(0.5+0j))\n" +" (0.87758256189+0j)\n" +"\n" +" \"\"\"\n" +" getcontext().prec += 2\n" +" i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1\n" +" while s != lasts:\n" +" lasts = s\n" +" i += 2\n" +" fact *= i * (i-1)\n" +" num *= x * x\n" +" sign *= -1\n" +" s += num / fact * sign\n" +" getcontext().prec -= 2\n" +" return +s\n" +"\n" +"def sin(x):\n" +" \"\"\"Return the sine of x as measured in radians.\n" +"\n" +" The Taylor series approximation works best for a small value of x.\n" +" For larger values, first compute x = x % (2 * pi).\n" +"\n" +" >>> print(sin(Decimal('0.5')))\n" +" 0.4794255386042030002732879352\n" +" >>> print(sin(0.5))\n" +" 0.479425538604\n" +" >>> print(sin(0.5+0j))\n" +" (0.479425538604+0j)\n" +"\n" +" \"\"\"\n" +" getcontext().prec += 2\n" +" i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1\n" +" while s != lasts:\n" +" lasts = s\n" +" i += 2\n" +" fact *= i * (i-1)\n" +" num *= x * x\n" +" sign *= -1\n" +" s += num / fact * sign\n" +" getcontext().prec -= 2\n" +" return +s" +msgstr "" + #: library/decimal.rst:2054 msgid "Decimal FAQ" msgstr "" @@ -1985,6 +2479,20 @@ msgid "" "computation::" msgstr "" +#: library/decimal.rst:2143 +msgid "" +">>> getcontext().prec = 5\n" +">>> pi = Decimal('3.1415926535') # More than 5 digits\n" +">>> pi # All digits are retained\n" +"Decimal('3.1415926535')\n" +">>> pi + 0 # Rounded after an addition\n" +"Decimal('3.1416')\n" +">>> pi - Decimal('0.00005') # Subtract unrounded numbers, then round\n" +"Decimal('3.1415')\n" +">>> pi + 0 - Decimal('0.00005'). # Intermediate values are rounded\n" +"Decimal('3.1416')" +msgstr "" + #: library/decimal.rst:2154 msgid "" "Q. Some decimal values always print with exponential notation. Is there a " @@ -2017,6 +2525,12 @@ msgid "" "would suggest:" msgstr "" +#: library/decimal.rst:2178 +msgid "" +">>> Decimal(math.pi)\n" +"Decimal('3.141592653589793115997963468544185161590576171875')" +msgstr "" + #: library/decimal.rst:2183 msgid "" "Q. Within a complex calculation, how can I make sure that I haven't gotten a " @@ -2047,12 +2561,28 @@ msgid "" "haven't been rounded:" msgstr "" +#: library/decimal.rst:2200 +msgid "" +">>> getcontext().prec = 3\n" +">>> Decimal('3.104') + Decimal('2.104')\n" +"Decimal('5.21')\n" +">>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')\n" +"Decimal('5.20')" +msgstr "" + #: library/decimal.rst:2208 msgid "" "The solution is either to increase precision or to force rounding of inputs " "using the unary plus operation:" msgstr "" +#: library/decimal.rst:2211 +msgid "" +">>> getcontext().prec = 3\n" +">>> +Decimal('1.23456789') # unary plus triggers rounding\n" +"Decimal('1.23')" +msgstr "" + #: library/decimal.rst:2217 msgid "" "Alternatively, inputs can be rounded upon creation using the :meth:`Context." @@ -2090,12 +2620,28 @@ msgid "" "value for :attr:`~Context.prec` as well [#]_::" msgstr "" +#: library/decimal.rst:2242 +msgid "" +">>> setcontext(Context(prec=MAX_PREC, Emax=MAX_EMAX, Emin=MIN_EMIN))\n" +">>> x = Decimal(2) ** 256\n" +">>> x / 128\n" +"Decimal('904625697166532776746648320380374280103671755200316906558262375061821325312')" +msgstr "" + #: library/decimal.rst:2248 msgid "" "For inexact results, :attr:`MAX_PREC` is far too large on 64-bit platforms " "and the available memory will be insufficient::" msgstr "" +#: library/decimal.rst:2251 +msgid "" +">>> Decimal(1) / 3\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"MemoryError" +msgstr "" + #: library/decimal.rst:2256 msgid "" "On systems with overallocation (e.g. Linux), a more sophisticated approach " @@ -2104,6 +2650,30 @@ msgid "" "of 500MB each::" msgstr "" +#: library/decimal.rst:2260 +msgid "" +">>> import sys\n" +">>>\n" +">>> # Maximum number of digits for a single operand using 500MB in 8-byte " +"words\n" +">>> # with 19 digits per word (4-byte and 9 digits for the 32-bit build):\n" +">>> maxdigits = 19 * ((500 * 1024**2) // 8)\n" +">>>\n" +">>> # Check that this works:\n" +">>> c = Context(prec=maxdigits, Emax=MAX_EMAX, Emin=MIN_EMIN)\n" +">>> c.traps[Inexact] = True\n" +">>> setcontext(c)\n" +">>>\n" +">>> # Fill the available precision with nines:\n" +">>> x = Decimal(0).logical_invert() * 9\n" +">>> sys.getsizeof(x)\n" +"524288112\n" +">>> x + 2\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" decimal.Inexact: []" +msgstr "" + #: library/decimal.rst:2280 msgid "" "In general (and especially on systems without overallocation), it is " diff --git a/library/devmode.po b/library/devmode.po index fcf51fd3d..a73084a38 100644 --- a/library/devmode.po +++ b/library/devmode.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-10-01 00:18+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -48,6 +48,11 @@ msgid "" "but with additional effects described below::" msgstr "" +#: library/devmode.rst:24 +msgid "" +"PYTHONMALLOC=debug PYTHONASYNCIODEBUG=1 python -W default -X faulthandler" +msgstr "" + #: library/devmode.rst:26 msgid "Effects of the Python Development Mode:" msgstr "" @@ -224,29 +229,82 @@ msgid "" "in the command line::" msgstr "" +#: library/devmode.rst:116 +msgid "" +"import sys\n" +"\n" +"def main():\n" +" fp = open(sys.argv[1])\n" +" nlines = len(fp.readlines())\n" +" print(nlines)\n" +" # The file is closed implicitly\n" +"\n" +"if __name__ == \"__main__\":\n" +" main()" +msgstr "" + #: library/devmode.rst:127 msgid "" "The script does not close the file explicitly. By default, Python does not " "emit any warning. Example using README.txt, which has 269 lines:" msgstr "" +#: library/devmode.rst:130 +msgid "" +"$ python script.py README.txt\n" +"269" +msgstr "" + #: library/devmode.rst:135 msgid "" "Enabling the Python Development Mode displays a :exc:`ResourceWarning` " "warning:" msgstr "" +#: library/devmode.rst:137 +msgid "" +"$ python -X dev script.py README.txt\n" +"269\n" +"script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='README." +"rst' mode='r' encoding='UTF-8'>\n" +" main()\n" +"ResourceWarning: Enable tracemalloc to get the object allocation traceback" +msgstr "" + #: library/devmode.rst:145 msgid "" "In addition, enabling :mod:`tracemalloc` shows the line where the file was " "opened:" msgstr "" +#: library/devmode.rst:148 +msgid "" +"$ python -X dev -X tracemalloc=5 script.py README.rst\n" +"269\n" +"script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='README." +"rst' mode='r' encoding='UTF-8'>\n" +" main()\n" +"Object allocated at (most recent call last):\n" +" File \"script.py\", lineno 10\n" +" main()\n" +" File \"script.py\", lineno 4\n" +" fp = open(sys.argv[1])" +msgstr "" + #: library/devmode.rst:160 msgid "" "The fix is to close explicitly the file. Example using a context manager::" msgstr "" +#: library/devmode.rst:162 +msgid "" +"def main():\n" +" # Close the file explicitly when exiting the with block\n" +" with open(sys.argv[1]) as fp:\n" +" nlines = len(fp.readlines())\n" +" print(nlines)" +msgstr "" + #: library/devmode.rst:168 msgid "" "Not closing a resource explicitly can leave a resource open for way longer " @@ -263,16 +321,52 @@ msgstr "" msgid "Script displaying the first line of itself::" msgstr "" +#: library/devmode.rst:179 +msgid "" +"import os\n" +"\n" +"def main():\n" +" fp = open(__file__)\n" +" firstline = fp.readline()\n" +" print(firstline.rstrip())\n" +" os.close(fp.fileno())\n" +" # The file is closed implicitly\n" +"\n" +"main()" +msgstr "" + #: library/devmode.rst:190 msgid "By default, Python does not emit any warning:" msgstr "" +#: library/devmode.rst:192 +msgid "" +"$ python script.py\n" +"import os" +msgstr "" + #: library/devmode.rst:197 msgid "" "The Python Development Mode shows a :exc:`ResourceWarning` and logs a \"Bad " "file descriptor\" error when finalizing the file object:" msgstr "" +#: library/devmode.rst:200 +msgid "" +"$ python -X dev script.py\n" +"import os\n" +"script.py:10: ResourceWarning: unclosed file <_io.TextIOWrapper name='script." +"py' mode='r' encoding='UTF-8'>\n" +" main()\n" +"ResourceWarning: Enable tracemalloc to get the object allocation traceback\n" +"Exception ignored in: <_io.TextIOWrapper name='script.py' mode='r' " +"encoding='UTF-8'>\n" +"Traceback (most recent call last):\n" +" File \"script.py\", line 10, in \n" +" main()\n" +"OSError: [Errno 9] Bad file descriptor" +msgstr "" + #: library/devmode.rst:213 msgid "" "``os.close(fp.fileno())`` closes the file descriptor. When the file object " diff --git a/library/difflib.po b/library/difflib.po index 409e774c7..86da66d4b 100644 --- a/library/difflib.po +++ b/library/difflib.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -431,6 +431,10 @@ msgid "" "ignored. For example, pass::" msgstr "" +#: library/difflib.rst:375 +msgid "lambda x: x in \" \\t\"" +msgstr "" + #: library/difflib.rst:377 msgid "" "if you're comparing lines as sequences of characters, and don't want to " @@ -553,6 +557,13 @@ msgid "" "triples always describe non-adjacent equal blocks." msgstr "" +#: library/difflib.rst:479 +msgid "" +">>> s = SequenceMatcher(None, \"abxcd\", \"abcd\")\n" +">>> s.get_matching_blocks()\n" +"[Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]" +msgstr "" + #: library/difflib.rst:488 msgid "" "Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is " @@ -607,6 +618,21 @@ msgstr "" msgid "For example::" msgstr "" +#: library/difflib.rst:514 +msgid "" +">>> a = \"qabxcd\"\n" +">>> b = \"abycdf\"\n" +">>> s = SequenceMatcher(None, a, b)\n" +">>> for tag, i1, i2, j1, j2 in s.get_opcodes():\n" +"... print('{:7} a[{}:{}] --> b[{}:{}] {!r:>8} --> {!r}'.format(\n" +"... tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2]))\n" +"delete a[0:1] --> b[0:0] 'q' --> ''\n" +"equal a[1:3] --> b[0:2] 'ab' --> 'ab'\n" +"replace a[3:4] --> b[2:3] 'x' --> 'y'\n" +"equal a[4:6] --> b[3:5] 'cd' --> 'cd'\n" +"insert a[6:6] --> b[5:6] '' --> 'f'" +msgstr "" + #: library/difflib.rst:529 msgid "Return a :term:`generator` of groups with up to *n* lines of context." msgstr "" @@ -647,6 +673,14 @@ msgid "" "arguments. For instance::" msgstr "" +#: library/difflib.rst:557 +msgid "" +">>> SequenceMatcher(None, 'tide', 'diet').ratio()\n" +"0.25\n" +">>> SequenceMatcher(None, 'diet', 'tide').ratio()\n" +"0.5" +msgstr "" + #: library/difflib.rst:565 msgid "Return an upper bound on :meth:`ratio` relatively quickly." msgstr "" @@ -821,6 +855,73 @@ msgid "" "This example shows how to use difflib to create a ``diff``-like utility." msgstr "" +#: library/difflib.rst:761 +msgid "" +"\"\"\" Command line interface to difflib.py providing diffs in four " +"formats:\n" +"\n" +"* ndiff: lists every line and highlights interline changes.\n" +"* context: highlights clusters of changes in a before/after format.\n" +"* unified: highlights clusters of changes in an inline format.\n" +"* html: generates side by side comparison with change highlights.\n" +"\n" +"\"\"\"\n" +"\n" +"import sys, os, difflib, argparse\n" +"from datetime import datetime, timezone\n" +"\n" +"def file_mtime(path):\n" +" t = datetime.fromtimestamp(os.stat(path).st_mtime,\n" +" timezone.utc)\n" +" return t.astimezone().isoformat()\n" +"\n" +"def main():\n" +"\n" +" parser = argparse.ArgumentParser()\n" +" parser.add_argument('-c', action='store_true', default=False,\n" +" help='Produce a context format diff (default)')\n" +" parser.add_argument('-u', action='store_true', default=False,\n" +" help='Produce a unified format diff')\n" +" parser.add_argument('-m', action='store_true', default=False,\n" +" help='Produce HTML side by side diff '\n" +" '(can use -c and -l in conjunction)')\n" +" parser.add_argument('-n', action='store_true', default=False,\n" +" help='Produce a ndiff format diff')\n" +" parser.add_argument('-l', '--lines', type=int, default=3,\n" +" help='Set number of context lines (default 3)')\n" +" parser.add_argument('fromfile')\n" +" parser.add_argument('tofile')\n" +" options = parser.parse_args()\n" +"\n" +" n = options.lines\n" +" fromfile = options.fromfile\n" +" tofile = options.tofile\n" +"\n" +" fromdate = file_mtime(fromfile)\n" +" todate = file_mtime(tofile)\n" +" with open(fromfile) as ff:\n" +" fromlines = ff.readlines()\n" +" with open(tofile) as tf:\n" +" tolines = tf.readlines()\n" +"\n" +" if options.u:\n" +" diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, " +"fromdate, todate, n=n)\n" +" elif options.n:\n" +" diff = difflib.ndiff(fromlines, tolines)\n" +" elif options.m:\n" +" diff = difflib.HtmlDiff().make_file(fromlines,tolines,fromfile," +"tofile,context=options.c,numlines=n)\n" +" else:\n" +" diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, " +"fromdate, todate, n=n)\n" +"\n" +" sys.stdout.writelines(diff)\n" +"\n" +"if __name__ == '__main__':\n" +" main()\n" +msgstr "" + #: library/difflib.rst:764 msgid "ndiff example" msgstr "" @@ -828,3 +929,120 @@ msgstr "" #: library/difflib.rst:766 msgid "This example shows how to use :func:`difflib.ndiff`." msgstr "" + +#: library/difflib.rst:768 +msgid "" +"\"\"\"ndiff [-q] file1 file2\n" +" or\n" +"ndiff (-r1 | -r2) < ndiff_output > file1_or_file2\n" +"\n" +"Print a human-friendly file difference report to stdout. Both inter-\n" +"and intra-line differences are noted. In the second form, recreate file1\n" +"(-r1) or file2 (-r2) on stdout, from an ndiff report on stdin.\n" +"\n" +"In the first form, if -q (\"quiet\") is not specified, the first two lines\n" +"of output are\n" +"\n" +"-: file1\n" +"+: file2\n" +"\n" +"Each remaining line begins with a two-letter code:\n" +"\n" +" \"- \" line unique to file1\n" +" \"+ \" line unique to file2\n" +" \" \" line common to both files\n" +" \"? \" line not present in either input file\n" +"\n" +"Lines beginning with \"? \" attempt to guide the eye to intraline\n" +"differences, and were not present in either input file. These lines can be\n" +"confusing if the source files contain tab characters.\n" +"\n" +"The first file can be recovered by retaining only lines that begin with\n" +"\" \" or \"- \", and deleting those 2-character prefixes; use ndiff with -" +"r1.\n" +"\n" +"The second file can be recovered similarly, but by retaining only \" \" " +"and\n" +"\"+ \" lines; use ndiff with -r2; or, on Unix, the second file can be\n" +"recovered by piping the output through\n" +"\n" +" sed -n '/^[+ ] /s/^..//p'\n" +"\"\"\"\n" +"\n" +"__version__ = 1, 7, 0\n" +"\n" +"import difflib, sys\n" +"\n" +"def fail(msg):\n" +" out = sys.stderr.write\n" +" out(msg + \"\\n\\n\")\n" +" out(__doc__)\n" +" return 0\n" +"\n" +"# open a file & return the file object; gripe and return 0 if it\n" +"# couldn't be opened\n" +"def fopen(fname):\n" +" try:\n" +" return open(fname)\n" +" except IOError as detail:\n" +" return fail(\"couldn't open \" + fname + \": \" + str(detail))\n" +"\n" +"# open two files & spray the diff to stdout; return false iff a problem\n" +"def fcompare(f1name, f2name):\n" +" f1 = fopen(f1name)\n" +" f2 = fopen(f2name)\n" +" if not f1 or not f2:\n" +" return 0\n" +"\n" +" a = f1.readlines(); f1.close()\n" +" b = f2.readlines(); f2.close()\n" +" for line in difflib.ndiff(a, b):\n" +" print(line, end=' ')\n" +"\n" +" return 1\n" +"\n" +"# crack args (sys.argv[1:] is normal) & compare;\n" +"# return false iff a problem\n" +"\n" +"def main(args):\n" +" import getopt\n" +" try:\n" +" opts, args = getopt.getopt(args, \"qr:\")\n" +" except getopt.error as detail:\n" +" return fail(str(detail))\n" +" noisy = 1\n" +" qseen = rseen = 0\n" +" for opt, val in opts:\n" +" if opt == \"-q\":\n" +" qseen = 1\n" +" noisy = 0\n" +" elif opt == \"-r\":\n" +" rseen = 1\n" +" whichfile = val\n" +" if qseen and rseen:\n" +" return fail(\"can't specify both -q and -r\")\n" +" if rseen:\n" +" if args:\n" +" return fail(\"no args allowed with -r option\")\n" +" if whichfile in (\"1\", \"2\"):\n" +" restore(whichfile)\n" +" return 1\n" +" return fail(\"-r value must be 1 or 2\")\n" +" if len(args) != 2:\n" +" return fail(\"need 2 filename args\")\n" +" f1name, f2name = args\n" +" if noisy:\n" +" print('-:', f1name)\n" +" print('+:', f2name)\n" +" return fcompare(f1name, f2name)\n" +"\n" +"# read ndiff output from stdin, and print file1 (which=='1') or\n" +"# file2 (which=='2') to stdout\n" +"\n" +"def restore(which):\n" +" restored = difflib.restore(sys.stdin.readlines(), which)\n" +" sys.stdout.writelines(restored)\n" +"\n" +"if __name__ == '__main__':\n" +" main(sys.argv[1:])\n" +msgstr "" diff --git a/library/dis.po b/library/dis.po index a4c4671e9..df5e91b79 100644 --- a/library/dis.po +++ b/library/dis.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -80,12 +80,29 @@ msgstr "" msgid "Example: Given the function :func:`!myfunc`::" msgstr "" +#: library/dis.rst:56 +msgid "" +"def myfunc(alist):\n" +" return len(alist)" +msgstr "" + #: library/dis.rst:59 msgid "" "the following command can be used to display the disassembly of :func:`!" "myfunc`:" msgstr "" +#: library/dis.rst:62 +msgid "" +">>> dis.dis(myfunc)\n" +" 2 0 RESUME 0\n" +"\n" +" 3 2 LOAD_GLOBAL 1 (NULL + len)\n" +" 12 LOAD_FAST 0 (alist)\n" +" 14 CALL 1\n" +" 22 RETURN_VALUE" +msgstr "" + #: library/dis.rst:72 msgid "(The \"2\" is a line number)." msgstr "" @@ -98,6 +115,10 @@ msgstr "" msgid "The :mod:`dis` module can be invoked as a script from the command line:" msgstr "" +#: library/dis.rst:81 +msgid "python -m dis [-h] [infile]" +msgstr "" + #: library/dis.rst:85 msgid "The following options are accepted:" msgstr "" @@ -203,6 +224,19 @@ msgstr "" msgid "Example:" msgstr "" +#: library/dis.rst:162 +msgid "" +">>> bytecode = dis.Bytecode(myfunc)\n" +">>> for instr in bytecode:\n" +"... print(instr.opname)\n" +"...\n" +"RESUME\n" +"LOAD_GLOBAL\n" +"LOAD_FAST\n" +"CALL\n" +"RETURN_VALUE" +msgstr "" + #: library/dis.rst:176 msgid "Analysis functions" msgstr "" @@ -486,6 +520,10 @@ msgstr "" msgid "Removes the top-of-stack item::" msgstr "" +#: library/dis.rst:451 +msgid "STACK.pop()" +msgstr "" + #: library/dis.rst:456 msgid "" "Removes the top two values from the stack. Equivalent to ``POP_TOP``; " @@ -502,10 +540,20 @@ msgid "" "original location::" msgstr "" +#: library/dis.rst:476 +msgid "" +"assert i > 0\n" +"STACK.append(STACK[-i])" +msgstr "" + #: library/dis.rst:484 msgid "Swap the top of the stack with the i-th element::" msgstr "" +#: library/dis.rst:486 +msgid "STACK[-i], STACK[-1] = STACK[-1], STACK[-i]" +msgstr "" + #: library/dis.rst:493 msgid "" "Rather than being an actual instruction, this opcode is used to mark extra " @@ -584,12 +632,58 @@ msgid "" "*op*)::" msgstr "" +#: library/dis.rst:558 +msgid "" +"rhs = STACK.pop()\n" +"lhs = STACK.pop()\n" +"STACK.append(lhs op rhs)" +msgstr "" + #: library/dis.rst:576 library/dis.rst:594 library/dis.rst:694 -#: library/dis.rst:714 library/dis.rst:945 library/dis.rst:1057 -#: library/dis.rst:1069 +#: library/dis.rst:714 library/dis.rst:946 library/dis.rst:1062 +#: library/dis.rst:1074 msgid "Implements::" msgstr "" +#: library/dis.rst:569 +msgid "" +"key = STACK.pop()\n" +"container = STACK.pop()\n" +"STACK.append(container[key])" +msgstr "" + +#: library/dis.rst:578 +msgid "" +"key = STACK.pop()\n" +"container = STACK.pop()\n" +"value = STACK.pop()\n" +"container[key] = value" +msgstr "" + +#: library/dis.rst:588 +msgid "" +"key = STACK.pop()\n" +"container = STACK.pop()\n" +"del container[key]" +msgstr "" + +#: library/dis.rst:596 +msgid "" +"end = STACK.pop()\n" +"start = STACK.pop()\n" +"container = STACK.pop()\n" +"STACK.append(container[start:end])" +msgstr "" + +#: library/dis.rst:608 +msgid "" +"end = STACK.pop()\n" +"start = STACK.pop()\n" +"container = STACK.pop()\n" +"values = STACK.pop()\n" +"container[start:end] = value" +msgstr "" + #: library/dis.rst:617 msgid "**Coroutine opcodes**" msgstr "" @@ -661,18 +755,41 @@ msgid "" "``__aexit__`` and result of ``__aenter__()`` to the stack::" msgstr "" +#: library/dis.rst:684 +msgid "STACK.extend((__aexit__, __aenter__())" +msgstr "" + #: library/dis.rst:690 msgid "**Miscellaneous opcodes**" msgstr "" +#: library/dis.rst:696 +msgid "" +"item = STACK.pop()\n" +"set.add(STACK[-i], item)" +msgstr "" + #: library/dis.rst:699 msgid "Used to implement set comprehensions." msgstr "" +#: library/dis.rst:706 +msgid "" +"item = STACK.pop()\n" +"list.append(STACK[-i], item)" +msgstr "" + #: library/dis.rst:709 msgid "Used to implement list comprehensions." msgstr "" +#: library/dis.rst:716 +msgid "" +"value = STACK.pop()\n" +"key = STACK.pop()\n" +"dict.__setitem__(STACK[-i], key, value)" +msgstr "" + #: library/dis.rst:720 msgid "Used to implement dict comprehensions." msgstr "" @@ -797,10 +914,12 @@ msgid "" msgstr "" #: library/dis.rst:853 -msgid "Perform ``STACK.append(len(STACK[-1]))``." +msgid "" +"Perform ``STACK.append(len(STACK[-1]))``. Used in :keyword:`match` " +"statements where comparison with structure of pattern is needed." msgstr "" -#: library/dis.rst:860 +#: library/dis.rst:861 msgid "" "If ``STACK[-1]`` is an instance of :class:`collections.abc.Mapping` (or, " "more technically: if it has the :c:macro:`Py_TPFLAGS_MAPPING` flag set in " @@ -808,7 +927,7 @@ msgid "" "Otherwise, push ``False``." msgstr "" -#: library/dis.rst:870 +#: library/dis.rst:871 msgid "" "If ``STACK[-1]`` is an instance of :class:`collections.abc.Sequence` and is " "*not* an instance of :class:`str`/:class:`bytes`/:class:`bytearray` (or, " @@ -817,20 +936,20 @@ msgid "" "Otherwise, push ``False``." msgstr "" -#: library/dis.rst:880 +#: library/dis.rst:881 msgid "" "``STACK[-1]`` is a tuple of mapping keys, and ``STACK[-2]`` is the match " "subject. If ``STACK[-2]`` contains all of the keys in ``STACK[-1]``, push a :" "class:`tuple` containing the corresponding values. Otherwise, push ``None``." msgstr "" -#: library/dis.rst:1513 +#: library/dis.rst:1521 msgid "" "Previously, this instruction also pushed a boolean value indicating success " "(``True``) or failure (``False``)." msgstr "" -#: library/dis.rst:893 +#: library/dis.rst:894 msgid "" "Implements ``name = STACK.pop()``. *namei* is the index of *name* in the " "attribute :attr:`~codeobject.co_names` of the :ref:`code object `." msgstr "" -#: library/dis.rst:906 +#: library/dis.rst:907 msgid "" "Unpacks ``STACK[-1]`` into *count* individual values, which are put onto the " "stack right-to-left. Require there to be exactly *count* values.::" msgstr "" -#: library/dis.rst:915 +#: library/dis.rst:910 +msgid "" +"assert(len(STACK[-1]) == count)\n" +"STACK.extend(STACK.pop()[:-count-1:-1])" +msgstr "" + +#: library/dis.rst:916 msgid "" "Implements assignment with a starred target: Unpacks an iterable in " "``STACK[-1]`` into individual values, where the total number of values can " @@ -858,11 +983,11 @@ msgid "" "will be a list of all leftover items." msgstr "" -#: library/dis.rst:920 +#: library/dis.rst:921 msgid "The number of values before and after the list value is limited to 255." msgstr "" -#: library/dis.rst:922 +#: library/dis.rst:923 msgid "" "The number of values before the list value is encoded in the argument of the " "opcode. The number of values after the list if any is encoded using an " @@ -871,50 +996,63 @@ msgid "" "list value, the high byte of *counts* the number of values after it." msgstr "" -#: library/dis.rst:928 +#: library/dis.rst:929 msgid "" "The extracted values are put onto the stack right-to-left, i.e. ``a, *b, c = " "d`` will be stored after execution as ``STACK.extend((a, b, c))``." msgstr "" -#: library/dis.rst:940 +#: library/dis.rst:937 +msgid "" +"obj = STACK.pop()\n" +"value = STACK.pop()\n" +"obj.name = value" +msgstr "" + +#: library/dis.rst:941 msgid "" "where *namei* is the index of name in :attr:`~codeobject.co_names` of the :" "ref:`code object `." msgstr "" -#: library/dis.rst:950 +#: library/dis.rst:948 +msgid "" +"obj = STACK.pop()\n" +"del obj.name" +msgstr "" + +#: library/dis.rst:951 msgid "" "where *namei* is the index of name into :attr:`~codeobject.co_names` of the :" "ref:`code object `." msgstr "" -#: library/dis.rst:956 +#: library/dis.rst:957 msgid "Works as :opcode:`STORE_NAME`, but stores the name as a global." msgstr "" -#: library/dis.rst:961 +#: library/dis.rst:962 msgid "Works as :opcode:`DELETE_NAME`, but deletes a global name." msgstr "" -#: library/dis.rst:966 +#: library/dis.rst:967 msgid "Pushes ``co_consts[consti]`` onto the stack." msgstr "" -#: library/dis.rst:971 +#: library/dis.rst:972 msgid "" "Pushes the value associated with ``co_names[namei]`` onto the stack. The " "name is looked up within the locals, then the globals, then the builtins." msgstr "" -#: library/dis.rst:977 +#: library/dis.rst:978 msgid "" "Pushes a reference to the locals dictionary onto the stack. This is used to " "prepare namespace dictionaries for :opcode:`LOAD_FROM_DICT_OR_DEREF` and :" "opcode:`LOAD_FROM_DICT_OR_GLOBALS`." msgstr "" -#: library/dis.rst:986 +#: library/dis.rst:987 msgid "" "Pops a mapping off the stack and looks up the value for ``co_names[namei]``. " "If the name is not found there, looks it up in the globals and then the " @@ -923,69 +1061,98 @@ msgid "" "bodies." msgstr "" -#: library/dis.rst:997 +#: library/dis.rst:998 msgid "" "Creates a tuple consuming *count* items from the stack, and pushes the " -"resulting tuple onto the stack.::" +"resulting tuple onto the stack::" msgstr "" -#: library/dis.rst:1007 -msgid "Works as :opcode:`BUILD_TUPLE`, but creates a list." +#: library/dis.rst:1001 +msgid "" +"if count == 0:\n" +" value = ()\n" +"else:\n" +" value = tuple(STACK[-count:])\n" +" STACK = STACK[:-count]\n" +"\n" +"STACK.append(value)" msgstr "" #: library/dis.rst:1012 -msgid "Works as :opcode:`BUILD_TUPLE`, but creates a set." +msgid "Works as :opcode:`BUILD_TUPLE`, but creates a list." msgstr "" #: library/dis.rst:1017 +msgid "Works as :opcode:`BUILD_TUPLE`, but creates a set." +msgstr "" + +#: library/dis.rst:1022 msgid "" "Pushes a new dictionary object onto the stack. Pops ``2 * count`` items so " "that the dictionary holds *count* entries: ``{..., STACK[-4]: STACK[-3], " "STACK[-2]: STACK[-1]}``." msgstr "" -#: library/dis.rst:1021 +#: library/dis.rst:1026 msgid "" "The dictionary is created from stack items instead of creating an empty " "dictionary pre-sized to hold *count* items." msgstr "" -#: library/dis.rst:1028 +#: library/dis.rst:1033 msgid "" "The version of :opcode:`BUILD_MAP` specialized for constant keys. Pops the " "top element on the stack which contains a tuple of keys, then starting from " "``STACK[-2]``, pops *count* values to form values in the built dictionary." msgstr "" -#: library/dis.rst:1037 +#: library/dis.rst:1042 msgid "" "Concatenates *count* strings from the stack and pushes the resulting string " "onto the stack." msgstr "" -#: library/dis.rst:1050 +#: library/dis.rst:1052 +msgid "" +"seq = STACK.pop()\n" +"list.extend(STACK[-i], seq)" +msgstr "" + +#: library/dis.rst:1055 msgid "Used to build lists." msgstr "" -#: library/dis.rst:1062 +#: library/dis.rst:1064 +msgid "" +"seq = STACK.pop()\n" +"set.update(STACK[-i], seq)" +msgstr "" + +#: library/dis.rst:1067 msgid "Used to build sets." msgstr "" -#: library/dis.rst:1074 +#: library/dis.rst:1076 +msgid "" +"map = STACK.pop()\n" +"dict.update(STACK[-i], map)" +msgstr "" + +#: library/dis.rst:1079 msgid "Used to build dicts." msgstr "" -#: library/dis.rst:1081 +#: library/dis.rst:1086 msgid "Like :opcode:`DICT_UPDATE` but raises an exception for duplicate keys." msgstr "" -#: library/dis.rst:1088 +#: library/dis.rst:1093 msgid "" "If the low bit of ``namei`` is not set, this replaces ``STACK[-1]`` with " "``getattr(STACK[-1], co_names[namei>>1])``." msgstr "" -#: library/dis.rst:1091 +#: library/dis.rst:1096 msgid "" "If the low bit of ``namei`` is set, this will attempt to load a method named " "``co_names[namei>>1]`` from the ``STACK[-1]`` object. ``STACK[-1]`` is " @@ -996,60 +1163,66 @@ msgid "" "the object returned by the attribute lookup are pushed." msgstr "" -#: library/dis.rst:1099 +#: library/dis.rst:1104 msgid "" "If the low bit of ``namei`` is set, then a ``NULL`` or ``self`` is pushed to " "the stack before the attribute or unbound method respectively." msgstr "" -#: library/dis.rst:1106 +#: library/dis.rst:1111 msgid "" "This opcode implements :func:`super`, both in its zero-argument and two-" "argument forms (e.g. ``super().method()``, ``super().attr`` and ``super(cls, " "self).method()``, ``super(cls, self).attr``)." msgstr "" -#: library/dis.rst:1110 +#: library/dis.rst:1115 msgid "" "It pops three values from the stack (from top of stack down): - ``self``: " "the first argument to the current method - ``cls``: the class within which " "the current method was defined - the global ``super``" msgstr "" -#: library/dis.rst:1115 +#: library/dis.rst:1120 msgid "" "With respect to its argument, it works similarly to :opcode:`LOAD_ATTR`, " "except that ``namei`` is shifted left by 2 bits instead of 1." msgstr "" -#: library/dis.rst:1118 +#: library/dis.rst:1123 msgid "" "The low bit of ``namei`` signals to attempt a method load, as with :opcode:" "`LOAD_ATTR`, which results in pushing ``NULL`` and the loaded method. When " "it is unset a single value is pushed to the stack." msgstr "" -#: library/dis.rst:1122 +#: library/dis.rst:1127 msgid "" "The second-low bit of ``namei``, if set, means that this was a two-argument " "call to :func:`super` (unset means zero-argument)." msgstr "" -#: library/dis.rst:1130 +#: library/dis.rst:1135 msgid "" "Performs a Boolean operation. The operation name can be found in " -"``cmp_op[opname]``." +"``cmp_op[opname >> 4]``." +msgstr "" + +#: library/dis.rst:1138 +msgid "" +"The cmp_op index is now stored in the four-highest bits of oparg instead of " +"the four-lowest bits of oparg." msgstr "" -#: library/dis.rst:1136 +#: library/dis.rst:1144 msgid "Performs ``is`` comparison, or ``is not`` if ``invert`` is 1." msgstr "" -#: library/dis.rst:1143 +#: library/dis.rst:1151 msgid "Performs ``in`` comparison, or ``not in`` if ``invert`` is 1." msgstr "" -#: library/dis.rst:1150 +#: library/dis.rst:1158 msgid "" "Imports the module ``co_names[namei]``. ``STACK[-1]`` and ``STACK[-2]`` are " "popped and provide the *fromlist* and *level* arguments of :func:" @@ -1058,67 +1231,67 @@ msgid "" "opcode:`STORE_FAST` instruction modifies the namespace." msgstr "" -#: library/dis.rst:1158 +#: library/dis.rst:1166 msgid "" "Loads the attribute ``co_names[namei]`` from the module found in " "``STACK[-1]``. The resulting object is pushed onto the stack, to be " "subsequently stored by a :opcode:`STORE_FAST` instruction." msgstr "" -#: library/dis.rst:1165 +#: library/dis.rst:1173 msgid "Increments bytecode counter by *delta*." msgstr "" -#: library/dis.rst:1170 +#: library/dis.rst:1178 msgid "Decrements bytecode counter by *delta*. Checks for interrupts." msgstr "" -#: library/dis.rst:1177 +#: library/dis.rst:1185 msgid "Decrements bytecode counter by *delta*. Does not check for interrupts." msgstr "" -#: library/dis.rst:1184 +#: library/dis.rst:1192 msgid "" "If ``STACK[-1]`` is true, increments the bytecode counter by *delta*. " "``STACK[-1]`` is popped." msgstr "" -#: library/dis.rst:1200 +#: library/dis.rst:1208 msgid "" "The oparg is now a relative delta rather than an absolute target. This " "opcode is a pseudo-instruction, replaced in final bytecode by the directed " "versions (forward/backward)." msgstr "" -#: library/dis.rst:1205 library/dis.rst:1232 +#: library/dis.rst:1213 library/dis.rst:1240 msgid "This is no longer a pseudo-instruction." msgstr "" -#: library/dis.rst:1197 +#: library/dis.rst:1205 msgid "" "If ``STACK[-1]`` is false, increments the bytecode counter by *delta*. " "``STACK[-1]`` is popped." msgstr "" -#: library/dis.rst:1210 +#: library/dis.rst:1218 msgid "" "If ``STACK[-1]`` is not ``None``, increments the bytecode counter by " "*delta*. ``STACK[-1]`` is popped." msgstr "" -#: library/dis.rst:1227 +#: library/dis.rst:1235 msgid "" "This opcode is a pseudo-instruction, replaced in final bytecode by the " "directed versions (forward/backward)." msgstr "" -#: library/dis.rst:1224 +#: library/dis.rst:1232 msgid "" "If ``STACK[-1]`` is ``None``, increments the bytecode counter by *delta*. " "``STACK[-1]`` is popped." msgstr "" -#: library/dis.rst:1237 +#: library/dis.rst:1245 msgid "" "``STACK[-1]`` is an :term:`iterator`. Call its :meth:`~iterator.__next__` " "method. If this yields a new value, push it on the stack (leaving the " @@ -1126,87 +1299,87 @@ msgid "" "code counter is incremented by *delta*." msgstr "" -#: library/dis.rst:1242 +#: library/dis.rst:1250 msgid "Up until 3.11 the iterator was popped when it was exhausted." msgstr "" -#: library/dis.rst:1247 +#: library/dis.rst:1255 msgid "Loads the global named ``co_names[namei>>1]`` onto the stack." msgstr "" -#: library/dis.rst:1249 +#: library/dis.rst:1257 msgid "" "If the low bit of ``namei`` is set, then a ``NULL`` is pushed to the stack " "before the global variable." msgstr "" -#: library/dis.rst:1255 +#: library/dis.rst:1263 msgid "" "Pushes a reference to the local ``co_varnames[var_num]`` onto the stack." msgstr "" -#: library/dis.rst:1257 +#: library/dis.rst:1265 msgid "" "This opcode is now only used in situations where the local variable is " "guaranteed to be initialized. It cannot raise :exc:`UnboundLocalError`." msgstr "" -#: library/dis.rst:1263 +#: library/dis.rst:1271 msgid "" "Pushes a reference to the local ``co_varnames[var_num]`` onto the stack, " "raising an :exc:`UnboundLocalError` if the local variable has not been " "initialized." msgstr "" -#: library/dis.rst:1271 +#: library/dis.rst:1279 msgid "" "Pushes a reference to the local ``co_varnames[var_num]`` onto the stack (or " "pushes ``NULL`` onto the stack if the local variable has not been " "initialized) and sets ``co_varnames[var_num]`` to ``NULL``." msgstr "" -#: library/dis.rst:1279 +#: library/dis.rst:1287 msgid "Stores ``STACK.pop()`` into the local ``co_varnames[var_num]``." msgstr "" -#: library/dis.rst:1284 +#: library/dis.rst:1292 msgid "Deletes local ``co_varnames[var_num]``." msgstr "" -#: library/dis.rst:1289 +#: library/dis.rst:1297 msgid "" "Creates a new cell in slot ``i``. If that slot is nonempty then that value " "is stored into the new cell." msgstr "" -#: library/dis.rst:1297 +#: library/dis.rst:1305 msgid "" "Pushes a reference to the cell contained in slot ``i`` of the \"fast " "locals\" storage. The name of the variable is ``co_fastlocalnames[i]``." msgstr "" -#: library/dis.rst:1300 +#: library/dis.rst:1308 msgid "" "Note that ``LOAD_CLOSURE`` is effectively an alias for ``LOAD_FAST``. It " "exists to keep bytecode a little more readable." msgstr "" -#: library/dis.rst:1303 +#: library/dis.rst:1311 msgid "``i`` is no longer offset by the length of ``co_varnames``." msgstr "" -#: library/dis.rst:1309 +#: library/dis.rst:1317 msgid "" "Loads the cell contained in slot ``i`` of the \"fast locals\" storage. " "Pushes a reference to the object the cell contains on the stack." msgstr "" -#: library/dis.rst:1334 library/dis.rst:1345 +#: library/dis.rst:1342 library/dis.rst:1353 msgid "" "``i`` is no longer offset by the length of :attr:`~codeobject.co_varnames`." msgstr "" -#: library/dis.rst:1318 +#: library/dis.rst:1326 msgid "" "Pops a mapping off the stack and looks up the name associated with slot " "``i`` of the \"fast locals\" storage in this mapping. If the name is not " @@ -1216,94 +1389,94 @@ msgid "" "scopes ` within class bodies." msgstr "" -#: library/dis.rst:1331 +#: library/dis.rst:1339 msgid "" "Stores ``STACK.pop()`` into the cell contained in slot ``i`` of the \"fast " "locals\" storage." msgstr "" -#: library/dis.rst:1340 +#: library/dis.rst:1348 msgid "" "Empties the cell contained in slot ``i`` of the \"fast locals\" storage. " "Used by the :keyword:`del` statement." msgstr "" -#: library/dis.rst:1351 +#: library/dis.rst:1359 msgid "" "Copies the ``n`` free variables from the closure into the frame. Removes the " "need for special code on the caller's side when calling closures." msgstr "" -#: library/dis.rst:1360 +#: library/dis.rst:1368 msgid "" "Raises an exception using one of the 3 forms of the ``raise`` statement, " "depending on the value of *argc*:" msgstr "" -#: library/dis.rst:1363 +#: library/dis.rst:1371 msgid "0: ``raise`` (re-raise previous exception)" msgstr "" -#: library/dis.rst:1364 +#: library/dis.rst:1372 msgid "" "1: ``raise STACK[-1]`` (raise exception instance or type at ``STACK[-1]``)" msgstr "" -#: library/dis.rst:1365 +#: library/dis.rst:1373 msgid "" "2: ``raise STACK[-2] from STACK[-1]`` (raise exception instance or type at " "``STACK[-2]`` with ``__cause__`` set to ``STACK[-1]``)" msgstr "" -#: library/dis.rst:1371 +#: library/dis.rst:1379 msgid "" "Calls a callable object with the number of arguments specified by ``argc``, " "including the named arguments specified by the preceding :opcode:`KW_NAMES`, " "if any. On the stack are (in ascending order), either:" msgstr "" -#: library/dis.rst:1376 +#: library/dis.rst:1384 msgid "NULL" msgstr "" -#: library/dis.rst:1383 +#: library/dis.rst:1391 msgid "The callable" msgstr "" -#: library/dis.rst:1378 +#: library/dis.rst:1386 msgid "The positional arguments" msgstr "" -#: library/dis.rst:1386 +#: library/dis.rst:1394 msgid "The named arguments" msgstr "" -#: library/dis.rst:1381 +#: library/dis.rst:1389 msgid "or:" msgstr "" -#: library/dis.rst:1384 +#: library/dis.rst:1392 msgid "``self``" msgstr "" -#: library/dis.rst:1385 +#: library/dis.rst:1393 msgid "The remaining positional arguments" msgstr "" -#: library/dis.rst:1388 +#: library/dis.rst:1396 msgid "" "``argc`` is the total of the positional and named arguments, excluding " "``self`` when a ``NULL`` is not present." msgstr "" -#: library/dis.rst:1391 +#: library/dis.rst:1399 msgid "" "``CALL`` pops all arguments and the callable object off the stack, calls the " "callable object with those arguments, and pushes the return value returned " "by the callable object." msgstr "" -#: library/dis.rst:1400 +#: library/dis.rst:1408 msgid "" "Calls a callable object with variable set of positional and keyword " "arguments. If the lowest bit of *flags* is set, the top of the stack " @@ -1315,70 +1488,85 @@ msgid "" "arguments, and pushes the return value returned by the callable object." msgstr "" -#: library/dis.rst:1415 +#: library/dis.rst:1423 msgid "" "Pushes a ``NULL`` to the stack. Used in the call sequence to match the " "``NULL`` pushed by :opcode:`LOAD_METHOD` for non-method calls." msgstr "" -#: library/dis.rst:1424 +#: library/dis.rst:1432 msgid "" "Prefixes :opcode:`CALL`. Stores a reference to ``co_consts[consti]`` into an " "internal variable for use by :opcode:`CALL`. ``co_consts[consti]`` must be a " "tuple of strings." msgstr "" -#: library/dis.rst:1433 +#: library/dis.rst:1441 msgid "" "Pushes a new function object on the stack. From bottom to top, the consumed " "stack must consist of values if the argument carries a specified flag value" msgstr "" -#: library/dis.rst:1436 +#: library/dis.rst:1444 msgid "" "``0x01`` a tuple of default values for positional-only and positional-or-" "keyword parameters in positional order" msgstr "" -#: library/dis.rst:1438 +#: library/dis.rst:1446 msgid "``0x02`` a dictionary of keyword-only parameters' default values" msgstr "" -#: library/dis.rst:1439 +#: library/dis.rst:1447 msgid "``0x04`` a tuple of strings containing parameters' annotations" msgstr "" -#: library/dis.rst:1440 +#: library/dis.rst:1448 msgid "``0x08`` a tuple containing cells for free variables, making a closure" msgstr "" -#: library/dis.rst:1441 +#: library/dis.rst:1449 msgid "the code associated with the function (at ``STACK[-1]``)" msgstr "" -#: library/dis.rst:1443 +#: library/dis.rst:1451 msgid "Flag value ``0x04`` is a tuple of strings instead of dictionary" msgstr "" -#: library/dis.rst:1446 +#: library/dis.rst:1454 msgid "Qualified name at ``STACK[-1]`` was removed." msgstr "" -#: library/dis.rst:1454 +#: library/dis.rst:1462 msgid "" "Pushes a slice object on the stack. *argc* must be 2 or 3. If it is 2, " "implements::" msgstr "" -#: library/dis.rst:1460 +#: library/dis.rst:1464 +msgid "" +"end = STACK.pop()\n" +"start = STACK.pop()\n" +"STACK.append(slice(start, end))" +msgstr "" + +#: library/dis.rst:1468 msgid "if it is 3, implements::" msgstr "" -#: library/dis.rst:1467 +#: library/dis.rst:1470 +msgid "" +"step = STACK.pop()\n" +"end = STACK.pop()\n" +"start = STACK.pop()\n" +"STACK.append(slice(start, end, step))" +msgstr "" + +#: library/dis.rst:1475 msgid "See the :func:`slice` built-in function for more information." msgstr "" -#: library/dis.rst:1472 +#: library/dis.rst:1480 msgid "" "Prefixes any opcode which has an argument too big to fit into the default " "one byte. *ext* holds an additional byte which act as higher bits in the " @@ -1386,54 +1574,54 @@ msgid "" "allowed, forming an argument from two-byte to four-byte." msgstr "" -#: library/dis.rst:1480 +#: library/dis.rst:1488 msgid "" "Used for implementing formatted literal strings (f-strings). Pops an " "optional *fmt_spec* from the stack, then a required *value*. *flags* is " "interpreted as follows:" msgstr "" -#: library/dis.rst:1484 +#: library/dis.rst:1492 msgid "``(flags & 0x03) == 0x00``: *value* is formatted as-is." msgstr "" -#: library/dis.rst:1485 +#: library/dis.rst:1493 msgid "" "``(flags & 0x03) == 0x01``: call :func:`str` on *value* before formatting it." msgstr "" -#: library/dis.rst:1487 +#: library/dis.rst:1495 msgid "" "``(flags & 0x03) == 0x02``: call :func:`repr` on *value* before formatting " "it." msgstr "" -#: library/dis.rst:1489 +#: library/dis.rst:1497 msgid "" "``(flags & 0x03) == 0x03``: call :func:`ascii` on *value* before formatting " "it." msgstr "" -#: library/dis.rst:1491 +#: library/dis.rst:1499 msgid "" "``(flags & 0x04) == 0x04``: pop *fmt_spec* from the stack and use it, else " "use an empty *fmt_spec*." msgstr "" -#: library/dis.rst:1494 +#: library/dis.rst:1502 msgid "" "Formatting is performed using :c:func:`PyObject_Format`. The result is " "pushed on the stack." msgstr "" -#: library/dis.rst:1502 +#: library/dis.rst:1510 msgid "" "``STACK[-1]`` is a tuple of keyword attribute names, ``STACK[-2]`` is the " "class being matched against, and ``STACK[-3]`` is the match subject. " "*count* is the number of positional sub-patterns." msgstr "" -#: library/dis.rst:1506 +#: library/dis.rst:1514 msgid "" "Pop ``STACK[-1]``, ``STACK[-2]``, and ``STACK[-3]``. If ``STACK[-3]`` is an " "instance of ``STACK[-2]`` and has the positional and keyword attributes " @@ -1441,257 +1629,265 @@ msgid "" "Otherwise, push ``None``." msgstr "" -#: library/dis.rst:1520 +#: library/dis.rst:1528 msgid "A no-op. Performs internal tracing, debugging and optimization checks." msgstr "" -#: library/dis.rst:1522 +#: library/dis.rst:1530 msgid "The ``where`` operand marks where the ``RESUME`` occurs:" msgstr "" -#: library/dis.rst:1524 +#: library/dis.rst:1532 msgid "" "``0`` The start of a function, which is neither a generator, coroutine nor " "an async generator" msgstr "" -#: library/dis.rst:1526 +#: library/dis.rst:1534 msgid "``1`` After a ``yield`` expression" msgstr "" -#: library/dis.rst:1527 +#: library/dis.rst:1535 msgid "``2`` After a ``yield from`` expression" msgstr "" -#: library/dis.rst:1528 +#: library/dis.rst:1536 msgid "``3`` After an ``await`` expression" msgstr "" -#: library/dis.rst:1535 +#: library/dis.rst:1543 msgid "" "Create a generator, coroutine, or async generator from the current frame. " "Used as first opcode of in code object for the above mentioned callables. " "Clear the current frame and return the newly created generator." msgstr "" -#: library/dis.rst:1544 +#: library/dis.rst:1552 msgid "" "Equivalent to ``STACK[-1] = STACK[-2].send(STACK[-1])``. Used in ``yield " "from`` and ``await`` statements." msgstr "" -#: library/dis.rst:1547 +#: library/dis.rst:1555 msgid "" "If the call raises :exc:`StopIteration`, pop the top value from the stack, " "push the exception's ``value`` attribute, and increment the bytecode counter " "by *delta*." msgstr "" -#: library/dis.rst:1556 +#: library/dis.rst:1564 msgid "" "This is not really an opcode. It identifies the dividing line between " "opcodes in the range [0,255] which don't use their argument and those that " "do (``< HAVE_ARGUMENT`` and ``>= HAVE_ARGUMENT``, respectively)." msgstr "" -#: library/dis.rst:1560 +#: library/dis.rst:1568 msgid "" "If your application uses pseudo instructions, use the :data:`hasarg` " "collection instead." msgstr "" -#: library/dis.rst:1563 +#: library/dis.rst:1571 msgid "" "Now every instruction has an argument, but opcodes ``< HAVE_ARGUMENT`` " "ignore it. Before, only opcodes ``>= HAVE_ARGUMENT`` had an argument." msgstr "" -#: library/dis.rst:1567 +#: library/dis.rst:1575 msgid "" "Pseudo instructions were added to the :mod:`dis` module, and for them it is " "not true that comparison with ``HAVE_ARGUMENT`` indicates whether they use " "their arg." msgstr "" -#: library/dis.rst:1575 +#: library/dis.rst:1583 msgid "" "Calls an intrinsic function with one argument. Passes ``STACK[-1]`` as the " "argument and sets ``STACK[-1]`` to the result. Used to implement " "functionality that is not performance critical." msgstr "" -#: library/dis.rst:1633 +#: library/dis.rst:1641 msgid "The operand determines which intrinsic function is called:" msgstr "" -#: library/dis.rst:1636 +#: library/dis.rst:1644 msgid "Operand" msgstr "" -#: library/dis.rst:1636 +#: library/dis.rst:1644 msgid "Description" msgstr "" -#: library/dis.rst:1584 +#: library/dis.rst:1592 msgid "``INTRINSIC_1_INVALID``" msgstr "" -#: library/dis.rst:1638 +#: library/dis.rst:1646 msgid "Not valid" msgstr "" -#: library/dis.rst:1586 +#: library/dis.rst:1594 msgid "``INTRINSIC_PRINT``" msgstr "" -#: library/dis.rst:1586 +#: library/dis.rst:1594 msgid "Prints the argument to standard out. Used in the REPL." msgstr "" -#: library/dis.rst:1589 +#: library/dis.rst:1597 msgid "``INTRINSIC_IMPORT_STAR``" msgstr "" -#: library/dis.rst:1589 +#: library/dis.rst:1597 msgid "Performs ``import *`` for the named module." msgstr "" -#: library/dis.rst:1592 +#: library/dis.rst:1600 msgid "``INTRINSIC_STOPITERATION_ERROR``" msgstr "" -#: library/dis.rst:1592 +#: library/dis.rst:1600 msgid "Extracts the return value from a ``StopIteration`` exception." msgstr "" -#: library/dis.rst:1595 +#: library/dis.rst:1603 msgid "``INTRINSIC_ASYNC_GEN_WRAP``" msgstr "" -#: library/dis.rst:1595 +#: library/dis.rst:1603 msgid "Wraps an async generator value" msgstr "" -#: library/dis.rst:1597 +#: library/dis.rst:1605 msgid "``INTRINSIC_UNARY_POSITIVE``" msgstr "" -#: library/dis.rst:1597 +#: library/dis.rst:1605 msgid "Performs the unary ``+`` operation" msgstr "" -#: library/dis.rst:1600 +#: library/dis.rst:1608 msgid "``INTRINSIC_LIST_TO_TUPLE``" msgstr "" -#: library/dis.rst:1600 +#: library/dis.rst:1608 msgid "Converts a list to a tuple" msgstr "" -#: library/dis.rst:1602 +#: library/dis.rst:1610 msgid "``INTRINSIC_TYPEVAR``" msgstr "" -#: library/dis.rst:1602 +#: library/dis.rst:1610 msgid "Creates a :class:`typing.TypeVar`" msgstr "" -#: library/dis.rst:1604 +#: library/dis.rst:1612 msgid "``INTRINSIC_PARAMSPEC``" msgstr "" -#: library/dis.rst:1604 +#: library/dis.rst:1612 msgid "Creates a :class:`typing.ParamSpec`" msgstr "" -#: library/dis.rst:1607 +#: library/dis.rst:1615 msgid "``INTRINSIC_TYPEVARTUPLE``" msgstr "" -#: library/dis.rst:1607 +#: library/dis.rst:1615 msgid "Creates a :class:`typing.TypeVarTuple`" msgstr "" -#: library/dis.rst:1610 +#: library/dis.rst:1618 msgid "``INTRINSIC_SUBSCRIPT_GENERIC``" msgstr "" -#: library/dis.rst:1610 +#: library/dis.rst:1618 msgid "Returns :class:`typing.Generic` subscripted with the argument" msgstr "" -#: library/dis.rst:1613 +#: library/dis.rst:1621 msgid "``INTRINSIC_TYPEALIAS``" msgstr "" -#: library/dis.rst:1613 +#: library/dis.rst:1621 msgid "" "Creates a :class:`typing.TypeAliasType`; used in the :keyword:`type` " "statement. The argument is a tuple of the type alias's name, type " "parameters, and value." msgstr "" -#: library/dis.rst:1625 +#: library/dis.rst:1633 msgid "" "Calls an intrinsic function with two arguments. Used to implement " "functionality that is not performance critical::" msgstr "" -#: library/dis.rst:1638 +#: library/dis.rst:1636 +msgid "" +"arg2 = STACK.pop()\n" +"arg1 = STACK.pop()\n" +"result = intrinsic2(arg1, arg2)\n" +"STACK.push(result)" +msgstr "" + +#: library/dis.rst:1646 msgid "``INTRINSIC_2_INVALID``" msgstr "" -#: library/dis.rst:1640 +#: library/dis.rst:1648 msgid "``INTRINSIC_PREP_RERAISE_STAR``" msgstr "" -#: library/dis.rst:1640 +#: library/dis.rst:1648 msgid "Calculates the :exc:`ExceptionGroup` to raise from a ``try-except*``." msgstr "" -#: library/dis.rst:1644 +#: library/dis.rst:1652 msgid "``INTRINSIC_TYPEVAR_WITH_BOUND``" msgstr "" -#: library/dis.rst:1644 +#: library/dis.rst:1652 msgid "Creates a :class:`typing.TypeVar` with a bound." msgstr "" -#: library/dis.rst:1647 +#: library/dis.rst:1655 msgid "``INTRINSIC_TYPEVAR_WITH_CONSTRAINTS``" msgstr "" -#: library/dis.rst:1647 +#: library/dis.rst:1655 msgid "Creates a :class:`typing.TypeVar` with constraints." msgstr "" -#: library/dis.rst:1651 +#: library/dis.rst:1659 msgid "``INTRINSIC_SET_FUNCTION_TYPE_PARAMS``" msgstr "" -#: library/dis.rst:1651 +#: library/dis.rst:1659 msgid "Sets the ``__type_params__`` attribute of a function." msgstr "" -#: library/dis.rst:1658 +#: library/dis.rst:1666 msgid "**Pseudo-instructions**" msgstr "" -#: library/dis.rst:1660 +#: library/dis.rst:1668 msgid "" "These opcodes do not appear in Python bytecode. They are used by the " "compiler but are replaced by real opcodes or removed before bytecode is " "generated." msgstr "" -#: library/dis.rst:1665 +#: library/dis.rst:1673 msgid "" "Set up an exception handler for the following code block. If an exception " "occurs, the value stack level is restored to its current state and control " "is transferred to the exception handler at ``target``." msgstr "" -#: library/dis.rst:1672 +#: library/dis.rst:1680 msgid "" "Like ``SETUP_FINALLY``, but in case of an exception also pushes the last " "instruction (``lasti``) to the stack so that ``RERAISE`` can restore it. If " @@ -1700,76 +1896,76 @@ msgid "" "exception handler at ``target``." msgstr "" -#: library/dis.rst:1681 +#: library/dis.rst:1689 msgid "" "Like ``SETUP_CLEANUP``, but in case of an exception one more item is popped " "from the stack before control is transferred to the exception handler at " "``target``." msgstr "" -#: library/dis.rst:1685 +#: library/dis.rst:1693 msgid "" "This variant is used in :keyword:`with` and :keyword:`async with` " "constructs, which push the return value of the context manager's :meth:" "`~object.__enter__` or :meth:`~object.__aenter__` to the stack." msgstr "" -#: library/dis.rst:1692 +#: library/dis.rst:1700 msgid "" "Marks the end of the code block associated with the last ``SETUP_FINALLY``, " "``SETUP_CLEANUP`` or ``SETUP_WITH``." msgstr "" -#: library/dis.rst:1698 +#: library/dis.rst:1706 msgid "" "Undirected relative jump instructions which are replaced by their directed " "(forward/backward) counterparts by the assembler." msgstr "" -#: library/dis.rst:1703 +#: library/dis.rst:1711 msgid "" "Optimized unbound method lookup. Emitted as a ``LOAD_ATTR`` opcode with a " "flag set in the arg." msgstr "" -#: library/dis.rst:1710 +#: library/dis.rst:1718 msgid "Opcode collections" msgstr "" -#: library/dis.rst:1712 +#: library/dis.rst:1720 msgid "" "These collections are provided for automatic introspection of bytecode " "instructions:" msgstr "" -#: library/dis.rst:1715 +#: library/dis.rst:1723 msgid "" "The collections now contain pseudo instructions and instrumented " "instructions as well. These are opcodes with values ``>= MIN_PSEUDO_OPCODE`` " "and ``>= MIN_INSTRUMENTED_OPCODE``." msgstr "" -#: library/dis.rst:1722 +#: library/dis.rst:1730 msgid "Sequence of operation names, indexable using the bytecode." msgstr "" -#: library/dis.rst:1727 +#: library/dis.rst:1735 msgid "Dictionary mapping operation names to bytecodes." msgstr "" -#: library/dis.rst:1732 +#: library/dis.rst:1740 msgid "Sequence of all compare operation names." msgstr "" -#: library/dis.rst:1737 +#: library/dis.rst:1745 msgid "Sequence of bytecodes that use their argument." msgstr "" -#: library/dis.rst:1744 +#: library/dis.rst:1752 msgid "Sequence of bytecodes that access a constant." msgstr "" -#: library/dis.rst:1749 +#: library/dis.rst:1757 msgid "" "Sequence of bytecodes that access a free variable. 'free' in this context " "refers to names in the current scope that are referenced by inner scopes or " @@ -1777,34 +1973,34 @@ msgid "" "include references to global or builtin scopes." msgstr "" -#: library/dis.rst:1757 +#: library/dis.rst:1765 msgid "Sequence of bytecodes that access an attribute by name." msgstr "" -#: library/dis.rst:1762 +#: library/dis.rst:1770 msgid "Sequence of bytecodes that have a relative jump target." msgstr "" -#: library/dis.rst:1767 +#: library/dis.rst:1775 msgid "Sequence of bytecodes that have an absolute jump target." msgstr "" -#: library/dis.rst:1772 +#: library/dis.rst:1780 msgid "Sequence of bytecodes that access a local variable." msgstr "" -#: library/dis.rst:1777 +#: library/dis.rst:1785 msgid "Sequence of bytecodes of Boolean operations." msgstr "" -#: library/dis.rst:1781 +#: library/dis.rst:1789 msgid "Sequence of bytecodes that set an exception handler." msgstr "" -#: library/dis.rst:1452 +#: library/dis.rst:1460 msgid "built-in function" msgstr "" -#: library/dis.rst:1452 +#: library/dis.rst:1460 msgid "slice" msgstr "" diff --git a/library/doctest.po b/library/doctest.po index 23fac7e79..64510cdc9 100644 --- a/library/doctest.po +++ b/library/doctest.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -55,12 +55,76 @@ msgstr "" msgid "Here's a complete but small example module::" msgstr "" +#: library/doctest.rst:33 +msgid "" +"\"\"\"\n" +"This is the \"example\" module.\n" +"\n" +"The example module supplies one function, factorial(). For example,\n" +"\n" +">>> factorial(5)\n" +"120\n" +"\"\"\"\n" +"\n" +"def factorial(n):\n" +" \"\"\"Return the factorial of n, an exact integer >= 0.\n" +"\n" +" >>> [factorial(n) for n in range(6)]\n" +" [1, 1, 2, 6, 24, 120]\n" +" >>> factorial(30)\n" +" 265252859812191058636308480000000\n" +" >>> factorial(-1)\n" +" Traceback (most recent call last):\n" +" ...\n" +" ValueError: n must be >= 0\n" +"\n" +" Factorials of floats are OK, but the float must be an exact integer:\n" +" >>> factorial(30.1)\n" +" Traceback (most recent call last):\n" +" ...\n" +" ValueError: n must be exact integer\n" +" >>> factorial(30.0)\n" +" 265252859812191058636308480000000\n" +"\n" +" It must also not be ridiculously large:\n" +" >>> factorial(1e100)\n" +" Traceback (most recent call last):\n" +" ...\n" +" OverflowError: n too large\n" +" \"\"\"\n" +"\n" +" import math\n" +" if not n >= 0:\n" +" raise ValueError(\"n must be >= 0\")\n" +" if math.floor(n) != n:\n" +" raise ValueError(\"n must be exact integer\")\n" +" if n+1 == n: # catch a value like 1e300\n" +" raise OverflowError(\"n too large\")\n" +" result = 1\n" +" factor = 2\n" +" while factor <= n:\n" +" result *= factor\n" +" factor += 1\n" +" return result\n" +"\n" +"\n" +"if __name__ == \"__main__\":\n" +" import doctest\n" +" doctest.testmod()" +msgstr "" + #: library/doctest.rst:88 msgid "" "If you run :file:`example.py` directly from the command line, :mod:`doctest` " "works its magic:" msgstr "" +#: library/doctest.rst:91 +msgid "" +"$ python example.py\n" +"$" +msgstr "" + #: library/doctest.rst:96 msgid "" "There's no output! That's normal, and it means all the examples worked. " @@ -68,10 +132,43 @@ msgid "" "it's trying, and prints a summary at the end:" msgstr "" +#: library/doctest.rst:100 +msgid "" +"$ python example.py -v\n" +"Trying:\n" +" factorial(5)\n" +"Expecting:\n" +" 120\n" +"ok\n" +"Trying:\n" +" [factorial(n) for n in range(6)]\n" +"Expecting:\n" +" [1, 1, 2, 6, 24, 120]\n" +"ok" +msgstr "" + #: library/doctest.rst:114 msgid "And so on, eventually ending with:" msgstr "" +#: library/doctest.rst:116 +msgid "" +"Trying:\n" +" factorial(1e100)\n" +"Expecting:\n" +" Traceback (most recent call last):\n" +" ...\n" +" OverflowError: n too large\n" +"ok\n" +"2 items passed all tests:\n" +" 1 tests in __main__\n" +" 8 tests in __main__.factorial\n" +"9 tests in 2 items.\n" +"9 passed and 0 failed.\n" +"Test passed.\n" +"$" +msgstr "" + #: library/doctest.rst:133 msgid "" "That's all you need to know to start making productive use of :mod:" @@ -91,6 +188,13 @@ msgid "" "continue to do it) is to end each module :mod:`!M` with::" msgstr "" +#: library/doctest.rst:148 +msgid "" +"if __name__ == \"__main__\":\n" +" import doctest\n" +" doctest.testmod()" +msgstr "" + #: library/doctest.rst:152 msgid ":mod:`!doctest` then examines docstrings in module :mod:`!M`." msgstr "" @@ -101,6 +205,10 @@ msgid "" "executed and verified::" msgstr "" +#: library/doctest.rst:157 +msgid "python M.py" +msgstr "" + #: library/doctest.rst:159 msgid "" "This won't display anything unless an example fails, in which case the " @@ -113,6 +221,10 @@ msgstr "" msgid "Run it with the ``-v`` switch instead::" msgstr "" +#: library/doctest.rst:166 +msgid "python M.py -v" +msgstr "" + #: library/doctest.rst:168 msgid "" "and a detailed report of all examples tried is printed to standard output, " @@ -134,6 +246,10 @@ msgid "" "standard library and pass the module name(s) on the command line::" msgstr "" +#: library/doctest.rst:180 +msgid "python -m doctest -v example.py" +msgstr "" + #: library/doctest.rst:182 msgid "" "This will import :file:`example.py` as a standalone module and run :func:" @@ -157,6 +273,12 @@ msgid "" "text file. This can be done with the :func:`testfile` function::" msgstr "" +#: library/doctest.rst:197 +msgid "" +"import doctest\n" +"doctest.testfile(\"example.txt\")" +msgstr "" + #: library/doctest.rst:200 msgid "" "That short script executes and verifies any interactive Python examples " @@ -165,12 +287,42 @@ msgid "" "Python program! For example, perhaps :file:`example.txt` contains this:" msgstr "" +#: library/doctest.rst:205 +msgid "" +"The ``example`` module\n" +"======================\n" +"\n" +"Using ``factorial``\n" +"-------------------\n" +"\n" +"This is an example text file in reStructuredText format. First import\n" +"``factorial`` from the ``example`` module:\n" +"\n" +" >>> from example import factorial\n" +"\n" +"Now use it:\n" +"\n" +" >>> factorial(6)\n" +" 120" +msgstr "" + #: library/doctest.rst:223 msgid "" "Running ``doctest.testfile(\"example.txt\")`` then finds the error in this " "documentation::" msgstr "" +#: library/doctest.rst:226 +msgid "" +"File \"./example.txt\", line 14, in example.txt\n" +"Failed example:\n" +" factorial(6)\n" +"Expected:\n" +" 120\n" +"Got:\n" +" 720" +msgstr "" + #: library/doctest.rst:234 msgid "" "As with :func:`testmod`, :func:`testfile` won't display anything unless an " @@ -200,6 +352,10 @@ msgid "" "standard library and pass the file name(s) on the command line::" msgstr "" +#: library/doctest.rst:251 +msgid "python -m doctest -v example.txt" +msgstr "" + #: library/doctest.rst:253 msgid "" "Because the file name does not end with :file:`.py`, :mod:`doctest` infers " @@ -253,6 +409,19 @@ msgstr "" msgid "For example, place this block of code at the top of :file:`example.py`:" msgstr "" +#: library/doctest.rst:291 +msgid "" +"__test__ = {\n" +" 'numbers': \"\"\"\n" +">>> factorial(6)\n" +"720\n" +"\n" +">>> [factorial(n) for n in range(6)]\n" +"[1, 1, 2, 6, 24, 120]\n" +"\"\"\"\n" +"}" +msgstr "" + #: library/doctest.rst:303 msgid "" "The value of ``example.__test__[\"numbers\"]`` will be treated as a " @@ -279,6 +448,25 @@ msgid "" "shell." msgstr "" +#: library/doctest.rst:323 +msgid "" +">>> # comments are ignored\n" +">>> x = 12\n" +">>> x\n" +"12\n" +">>> if x == 13:\n" +"... print(\"yes\")\n" +"... else:\n" +"... print(\"no\")\n" +"... print(\"NO\")\n" +"... print(\"NO!!!\")\n" +"...\n" +"no\n" +"NO\n" +"NO!!!\n" +">>>" +msgstr "" + #: library/doctest.rst:343 msgid "" "Any expected output must immediately follow the final ``'>>> '`` or ``'... " @@ -326,6 +514,15 @@ msgid "" "preserve your backslashes exactly as you type them::" msgstr "" +#: library/doctest.rst:373 +msgid "" +">>> def f(x):\n" +"... r'''Backslashes in a raw docstring: m\\n'''\n" +"...\n" +">>> print(f.__doc__)\n" +"Backslashes in a raw docstring: m\\n" +msgstr "" + #: library/doctest.rst:379 msgid "" "Otherwise, the backslash will be interpreted as part of the string. For " @@ -334,10 +531,27 @@ msgid "" "use a raw string)::" msgstr "" +#: library/doctest.rst:383 +msgid "" +">>> def f(x):\n" +"... '''Backslashes in a raw docstring: m\\\\n'''\n" +"...\n" +">>> print(f.__doc__)\n" +"Backslashes in a raw docstring: m\\n" +msgstr "" + #: library/doctest.rst:389 msgid "The starting column doesn't matter::" msgstr "" +#: library/doctest.rst:391 +msgid "" +">>> assert \"Easy!\"\n" +" >>> import math\n" +" >>> math.floor(1.9)\n" +" 1" +msgstr "" + #: library/doctest.rst:396 msgid "" "and as many leading whitespace characters are stripped from the expected " @@ -382,6 +596,14 @@ msgstr "" msgid "Simple example::" msgstr "" +#: library/doctest.rst:430 +msgid "" +">>> [1, 2, 3].remove(42)\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ValueError: list.remove(x): x not in list" +msgstr "" + #: library/doctest.rst:435 msgid "" "That doctest succeeds if :exc:`ValueError` is raised, with the ``list." @@ -395,6 +617,12 @@ msgid "" "first line of the example::" msgstr "" +#: library/doctest.rst:442 +msgid "" +"Traceback (most recent call last):\n" +"Traceback (innermost last):" +msgstr "" + #: library/doctest.rst:445 msgid "" "The traceback header is followed by an optional traceback stack, whose " @@ -410,6 +638,16 @@ msgid "" "multi-line detail::" msgstr "" +#: library/doctest.rst:454 +msgid "" +">>> raise ValueError('multi\\n line\\ndetail')\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +"ValueError: multi\n" +" line\n" +"detail" +msgstr "" + #: library/doctest.rst:461 msgid "" "The last three lines (starting with :exc:`ValueError`) are compared against " @@ -423,6 +661,16 @@ msgid "" "as::" msgstr "" +#: library/doctest.rst:467 +msgid "" +">>> raise ValueError('multi\\n line\\ndetail')\n" +"Traceback (most recent call last):\n" +" ...\n" +"ValueError: multi\n" +" line\n" +"detail" +msgstr "" + #: library/doctest.rst:474 msgid "" "Note that tracebacks are treated very specially. In particular, in the " @@ -477,6 +725,15 @@ msgid "" "markers and tildes::" msgstr "" +#: library/doctest.rst:510 +msgid "" +">>> 1 + None\n" +" File \"\", line 1\n" +" 1 + None\n" +" ~~^~~~~~\n" +"TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'" +msgstr "" + #: library/doctest.rst:516 msgid "" "Since the lines showing the position of the error come before the exception " @@ -485,6 +742,15 @@ msgid "" "location::" msgstr "" +#: library/doctest.rst:520 +msgid "" +">>> 1 + None\n" +" File \"\", line 1\n" +" 1 + None\n" +" ^~~~~~~~\n" +"TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'" +msgstr "" + #: library/doctest.rst:531 msgid "Option Flags" msgstr "" @@ -566,6 +832,21 @@ msgid "" "these variations will work with the flag specified:" msgstr "" +#: library/doctest.rst:601 +msgid "" +">>> raise Exception('message')\n" +"Traceback (most recent call last):\n" +"Exception: message\n" +"\n" +">>> raise Exception('message')\n" +"Traceback (most recent call last):\n" +"builtins.Exception: message\n" +"\n" +">>> raise Exception('message')\n" +"Traceback (most recent call last):\n" +"__main__.Exception: message" +msgstr "" + #: library/doctest.rst:615 msgid "" "Note that :const:`ELLIPSIS` can also be used to ignore the details of the " @@ -667,6 +948,10 @@ msgid "" "be called using the following idiom::" msgstr "" +#: library/doctest.rst:704 +msgid "MY_FLAG = register_optionflag('MY_FLAG')" +msgstr "" + #: library/doctest.rst:714 msgid "Directives" msgstr "" @@ -695,6 +980,13 @@ msgstr "" msgid "For example, this test passes:" msgstr "" +#: library/doctest.rst:736 +msgid "" +">>> print(list(range(20))) # doctest: +NORMALIZE_WHITESPACE\n" +"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n" +"10, 11, 12, 13, 14, 15, 16, 17, 18, 19]" +msgstr "" + #: library/doctest.rst:743 msgid "" "Without the directive it would fail, both because the actual output doesn't " @@ -703,18 +995,37 @@ msgid "" "a directive to do so:" msgstr "" +#: library/doctest.rst:748 +msgid "" +">>> print(list(range(20))) # doctest: +ELLIPSIS\n" +"[0, 1, ..., 18, 19]" +msgstr "" + #: library/doctest.rst:754 msgid "" "Multiple directives can be used on a single physical line, separated by " "commas:" msgstr "" +#: library/doctest.rst:757 +msgid "" +">>> print(list(range(20))) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE\n" +"[0, 1, ..., 18, 19]" +msgstr "" + #: library/doctest.rst:763 msgid "" "If multiple directive comments are used for a single example, then they are " "combined:" msgstr "" +#: library/doctest.rst:766 +msgid "" +">>> print(list(range(20))) # doctest: +ELLIPSIS\n" +"... # doctest: +NORMALIZE_WHITESPACE\n" +"[0, 1, ..., 18, 19]" +msgstr "" + #: library/doctest.rst:773 msgid "" "As the previous example shows, you can add ``...`` lines to your example " @@ -722,6 +1033,13 @@ msgid "" "for a directive to comfortably fit on the same line:" msgstr "" +#: library/doctest.rst:777 +msgid "" +">>> print(list(range(5)) + list(range(10, 20)) + list(range(30, 40)))\n" +"... # doctest: +ELLIPSIS\n" +"[0, ..., 4, 10, ..., 19, 30, ..., 39]" +msgstr "" + #: library/doctest.rst:784 msgid "" "Note that since all options are disabled by default, and directives apply " @@ -746,14 +1064,33 @@ msgid "" "test like ::" msgstr "" +#: library/doctest.rst:802 +msgid "" +">>> foo()\n" +"{\"spam\", \"eggs\"}" +msgstr "" + #: library/doctest.rst:805 msgid "is vulnerable! One workaround is to do ::" msgstr "" +#: library/doctest.rst:807 +msgid "" +">>> foo() == {\"spam\", \"eggs\"}\n" +"True" +msgstr "" + #: library/doctest.rst:810 msgid "instead. Another is to do ::" msgstr "" +#: library/doctest.rst:812 +msgid "" +">>> d = sorted(foo())\n" +">>> d\n" +"['eggs', 'spam']" +msgstr "" + #: library/doctest.rst:816 msgid "There are others, but you get the idea." msgstr "" @@ -762,11 +1099,26 @@ msgstr "" msgid "Another bad idea is to print things that embed an object address, like" msgstr "" +#: library/doctest.rst:820 +msgid "" +">>> id(1.0) # certain to fail some of the time \n" +"7948648\n" +">>> class C: pass\n" +">>> C() # the default repr() for instances embeds an address \n" +"" +msgstr "" + #: library/doctest.rst:828 msgid "" "The :const:`ELLIPSIS` directive gives a nice approach for the last example:" msgstr "" +#: library/doctest.rst:830 +msgid "" +">>> C() # doctest: +ELLIPSIS\n" +"" +msgstr "" + #: library/doctest.rst:836 msgid "" "Floating-point numbers are also subject to small output variations across " @@ -774,12 +1126,28 @@ msgid "" "formatting, and C libraries vary widely in quality here. ::" msgstr "" +#: library/doctest.rst:840 +msgid "" +">>> 1./7 # risky\n" +"0.14285714285714285\n" +">>> print(1./7) # safer\n" +"0.142857142857\n" +">>> print(round(1./7, 6)) # much safer\n" +"0.142857" +msgstr "" + #: library/doctest.rst:847 msgid "" "Numbers of the form ``I/2.**J`` are safe across all platforms, and I often " "contrive doctest examples to produce numbers of that form::" msgstr "" +#: library/doctest.rst:850 +msgid "" +">>> 3./4 # utterly safe\n" +"0.75" +msgstr "" + #: library/doctest.rst:853 msgid "" "Simple fractions are also easier for people to understand, and that makes " @@ -1016,6 +1384,17 @@ msgid "" "your test module::" msgstr "" +#: library/doctest.rst:1003 +msgid "" +"import unittest\n" +"import doctest\n" +"import my_module_with_doctests\n" +"\n" +"def load_tests(loader, tests, ignore):\n" +" tests.addTests(doctest.DocTestSuite(my_module_with_doctests))\n" +" return tests" +msgstr "" + #: library/doctest.rst:1011 msgid "" "There are two main functions for creating :class:`unittest.TestSuite` " @@ -1304,6 +1683,18 @@ msgid "" "following diagram::" msgstr "" +#: library/doctest.rst:1205 +msgid "" +" list of:\n" +"+------+ +---------+\n" +"|module| --DocTestFinder-> | DocTest | --DocTestRunner-> results\n" +"+------+ | ^ +---------+ | ^ (printed)\n" +" | | | Example | | |\n" +" v | | ... | v |\n" +" DocTestParser | Example | OutputChecker\n" +" +---------+" +msgstr "" + #: library/doctest.rst:1218 msgid "DocTest Objects" msgstr "" @@ -1785,10 +2176,56 @@ msgid "" "`a.py` contains just this module docstring::" msgstr "" +#: library/doctest.rst:1612 +msgid "" +"\"\"\"\n" +">>> def f(x):\n" +"... g(x*2)\n" +">>> def g(x):\n" +"... print(x+3)\n" +"... import pdb; pdb.set_trace()\n" +">>> f(3)\n" +"9\n" +"\"\"\"" +msgstr "" + #: library/doctest.rst:1622 msgid "Then an interactive Python session may look like this::" msgstr "" +#: library/doctest.rst:1624 +msgid "" +">>> import a, doctest\n" +">>> doctest.testmod(a)\n" +"--Return--\n" +"> (3)g()->None\n" +"-> import pdb; pdb.set_trace()\n" +"(Pdb) list\n" +" 1 def g(x):\n" +" 2 print(x+3)\n" +" 3 -> import pdb; pdb.set_trace()\n" +"[EOF]\n" +"(Pdb) p x\n" +"6\n" +"(Pdb) step\n" +"--Return--\n" +"> (2)f()->None\n" +"-> g(x*2)\n" +"(Pdb) list\n" +" 1 def f(x):\n" +" 2 -> g(x*2)\n" +"[EOF]\n" +"(Pdb) p x\n" +"3\n" +"(Pdb) step\n" +"--Return--\n" +"> (1)?()->None\n" +"-> f(3)\n" +"(Pdb) cont\n" +"(0, 3)\n" +">>>" +msgstr "" + #: library/doctest.rst:1655 msgid "" "Functions that convert doctests to Python code, and possibly run the " @@ -1807,10 +2244,34 @@ msgid "" "generated script is returned as a string. For example, ::" msgstr "" +#: library/doctest.rst:1668 +msgid "" +"import doctest\n" +"print(doctest.script_from_examples(r\"\"\"\n" +" Set x and y to 1 and 2.\n" +" >>> x, y = 1, 2\n" +"\n" +" Print their sum:\n" +" >>> print(x+y)\n" +" 3\n" +"\"\"\"))" +msgstr "" + #: library/doctest.rst:1678 msgid "displays::" msgstr "" +#: library/doctest.rst:1680 +msgid "" +"# Set x and y to 1 and 2.\n" +"x, y = 1, 2\n" +"#\n" +"# Print their sum:\n" +"print(x+y)\n" +"# Expected:\n" +"## 3" +msgstr "" + #: library/doctest.rst:1688 msgid "" "This function is used internally by other functions (see below), but can " @@ -1832,6 +2293,12 @@ msgid "" "module :file:`a.py` contains a top-level function :func:`!f`, then ::" msgstr "" +#: library/doctest.rst:1704 +msgid "" +"import a, doctest\n" +"print(doctest.testsource(a, \"a.f\"))" +msgstr "" + #: library/doctest.rst:1707 msgid "" "prints a script version of function :func:`!f`'s docstring, with doctests " @@ -2060,6 +2527,24 @@ msgid "" "example of such a test runner::" msgstr "" +#: library/doctest.rst:1880 +msgid "" +"if __name__ == '__main__':\n" +" import doctest\n" +" flags = doctest.REPORT_NDIFF|doctest.FAIL_FAST\n" +" if len(sys.argv) > 1:\n" +" name = sys.argv[1]\n" +" if name in globals():\n" +" obj = globals()[name]\n" +" else:\n" +" obj = __test__[name]\n" +" doctest.run_docstring_examples(obj, globals(), name=name,\n" +" optionflags=flags)\n" +" else:\n" +" fail, total = doctest.testmod(optionflags=flags)\n" +" print(\"{} failures out of {} tests\".format(fail, total))" +msgstr "" + #: library/doctest.rst:1897 msgid "Footnotes" msgstr "" diff --git a/library/email.compat32-message.po b/library/email.compat32-message.po index 8b5073ad1..918070742 100644 --- a/library/email.compat32-message.po +++ b/library/email.compat32-message.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -128,6 +128,16 @@ msgid "" "method directly. For example::" msgstr "" +#: library/email.compat32-message.rst:91 +msgid "" +"from io import StringIO\n" +"from email.generator import Generator\n" +"fp = StringIO()\n" +"g = Generator(fp, mangle_from_=True, maxheaderlen=60)\n" +"g.flatten(msg)\n" +"text = fp.getvalue()" +msgstr "" + #: library/email.compat32-message.rst:98 msgid "" "If the message object contains binary data that is not encoded according to " @@ -142,7 +152,7 @@ msgstr "" #: library/email.compat32-message.rst:108 msgid "" -"Equivalent to :meth:`.as_string()`. Allows ``str(msg)`` to produce a string " +"Equivalent to :meth:`.as_string`. Allows ``str(msg)`` to produce a string " "containing the formatted message." msgstr "" @@ -166,9 +176,19 @@ msgid "" "flatten` method directly. For example::" msgstr "" +#: library/email.compat32-message.rst:134 +msgid "" +"from io import BytesIO\n" +"from email.generator import BytesGenerator\n" +"fp = BytesIO()\n" +"g = BytesGenerator(fp, mangle_from_=True, maxheaderlen=60)\n" +"g.flatten(msg)\n" +"text = fp.getvalue()" +msgstr "" + #: library/email.compat32-message.rst:146 msgid "" -"Equivalent to :meth:`.as_bytes()`. Allows ``bytes(msg)`` to produce a bytes " +"Equivalent to :meth:`.as_bytes`. Allows ``bytes(msg)`` to produce a bytes " "object containing the formatted message." msgstr "" @@ -367,6 +387,12 @@ msgid "" "Used for the ``in`` operator, e.g.::" msgstr "" +#: library/email.compat32-message.rst:316 +msgid "" +"if 'message-id' in myMessage:\n" +" print('Message-ID:', myMessage['message-id'])" +msgstr "" + #: library/email.compat32-message.rst:322 msgid "" "Return the value of the named header field. *name* should not include the " @@ -395,6 +421,12 @@ msgid "" "present in the message with field name *name*, delete the field first, e.g.::" msgstr "" +#: library/email.compat32-message.rst:341 +msgid "" +"del msg['subject']\n" +"msg['subject'] = 'Python roolz!'" +msgstr "" + #: library/email.compat32-message.rst:347 msgid "" "Delete all occurrences of the field with name *name* from the message's " @@ -463,18 +495,37 @@ msgstr "" msgid "Here's an example::" msgstr "" +#: library/email.compat32-message.rst:407 +msgid "msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')" +msgstr "" + #: library/email.compat32-message.rst:409 msgid "This will add a header that looks like ::" msgstr "" +#: library/email.compat32-message.rst:411 +msgid "Content-Disposition: attachment; filename=\"bud.gif\"" +msgstr "" + #: library/email.compat32-message.rst:413 msgid "An example with non-ASCII characters::" msgstr "" +#: library/email.compat32-message.rst:415 +msgid "" +"msg.add_header('Content-Disposition', 'attachment',\n" +" filename=('iso-8859-1', '', 'Fußballer.ppt'))" +msgstr "" + #: library/email.compat32-message.rst:418 msgid "Which produces ::" msgstr "" +#: library/email.compat32-message.rst:420 +msgid "" +"Content-Disposition: attachment; filename*=\"iso-8859-1''Fu%DFballer.ppt\"" +msgstr "" + #: library/email.compat32-message.rst:425 msgid "" "Replace a header. Replace the first header found in the message that " @@ -586,6 +637,12 @@ msgid "" "value is a tuple, or the original string unquoted if it isn't. For example::" msgstr "" +#: library/email.compat32-message.rst:519 +msgid "" +"rawparam = msg.get_param('foo')\n" +"param = email.utils.collapse_rfc2231_value(rawparam)" +msgstr "" + #: library/email.compat32-message.rst:522 msgid "" "In any case, the parameter value (either the returned string, or the " @@ -753,6 +810,19 @@ msgid "" "message structure:" msgstr "" +#: library/email.compat32-message.rst:674 +msgid "" +">>> for part in msg.walk():\n" +"... print(part.get_content_type())\n" +"multipart/report\n" +"text/plain\n" +"message/delivery-status\n" +"text/plain\n" +"text/plain\n" +"message/rfc822\n" +"text/plain" +msgstr "" + #: library/email.compat32-message.rst:686 msgid "" "``walk`` iterates over the subparts of any part where :meth:`is_multipart` " @@ -761,6 +831,28 @@ msgid "" "``_structure`` debug helper function:" msgstr "" +#: library/email.compat32-message.rst:692 +msgid "" +">>> for part in msg.walk():\n" +"... print(part.get_content_maintype() == 'multipart',\n" +"... part.is_multipart())\n" +"True True\n" +"False False\n" +"False True\n" +"False False\n" +"False False\n" +"False True\n" +"False False\n" +">>> _structure(msg)\n" +"multipart/report\n" +" text/plain\n" +" message/delivery-status\n" +" text/plain\n" +" text/plain\n" +" message/rfc822\n" +" text/plain" +msgstr "" + #: library/email.compat32-message.rst:713 msgid "" "Here the ``message`` parts are not ``multiparts``, but they do contain " diff --git a/library/email.contentmanager.po b/library/email.contentmanager.po index bfd0ac607..79f1403dc 100644 --- a/library/email.contentmanager.po +++ b/library/email.contentmanager.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -96,46 +96,46 @@ msgid "" msgstr "" #: library/email.contentmanager.rst:61 -msgid "the type's qualname (``typ.__qualname__``)" +msgid "the type's :attr:`qualname ` (``typ.__qualname__``)" msgstr "" #: library/email.contentmanager.rst:62 -msgid "the type's name (``typ.__name__``)." +msgid "the type's :attr:`name ` (``typ.__name__``)." msgstr "" #: library/email.contentmanager.rst:64 msgid "" "If none of the above match, repeat all of the checks above for each of the " -"types in the :term:`MRO` (``typ.__mro__``). Finally, if no other key yields " -"a handler, check for a handler for the key ``None``. If there is no handler " -"for ``None``, raise a :exc:`KeyError` for the fully qualified name of the " -"type." +"types in the :term:`MRO` (:attr:`typ.__mro__ `). Finally, if " +"no other key yields a handler, check for a handler for the key ``None``. If " +"there is no handler for ``None``, raise a :exc:`KeyError` for the fully " +"qualified name of the type." msgstr "" -#: library/email.contentmanager.rst:70 +#: library/email.contentmanager.rst:71 msgid "" "Also add a :mailheader:`MIME-Version` header if one is not present (see " "also :class:`.MIMEPart`)." msgstr "" -#: library/email.contentmanager.rst:76 +#: library/email.contentmanager.rst:77 msgid "" "Record the function *handler* as the handler for *key*. For the possible " "values of *key*, see :meth:`get_content`." msgstr "" -#: library/email.contentmanager.rst:82 +#: library/email.contentmanager.rst:83 msgid "" "Record *handler* as the function to call when an object of a type matching " "*typekey* is passed to :meth:`set_content`. For the possible values of " "*typekey*, see :meth:`set_content`." msgstr "" -#: library/email.contentmanager.rst:88 +#: library/email.contentmanager.rst:89 msgid "Content Manager Instances" msgstr "" -#: library/email.contentmanager.rst:90 +#: library/email.contentmanager.rst:91 msgid "" "Currently the email package provides only one concrete content manager, :" "data:`raw_data_manager`, although more may be added in the future. :data:" @@ -143,7 +143,7 @@ msgid "" "provided by :attr:`~email.policy.EmailPolicy` and its derivatives." msgstr "" -#: library/email.contentmanager.rst:99 +#: library/email.contentmanager.rst:100 msgid "" "This content manager provides only a minimum interface beyond that provided " "by :class:`~email.message.Message` itself: it deals only with text, raw " @@ -156,7 +156,7 @@ msgid "" "simplifying the creation of multipart messages." msgstr "" -#: library/email.contentmanager.rst:111 +#: library/email.contentmanager.rst:112 msgid "" "Return the payload of the part as either a string (for ``text`` parts), an :" "class:`~email.message.EmailMessage` object (for ``message/rfc822`` parts), " @@ -166,28 +166,28 @@ msgid "" "to unicode. The default error handler is ``replace``." msgstr "" -#: library/email.contentmanager.rst:130 +#: library/email.contentmanager.rst:131 msgid "Add headers and payload to *msg*:" msgstr "" -#: library/email.contentmanager.rst:132 +#: library/email.contentmanager.rst:133 msgid "" "Add a :mailheader:`Content-Type` header with a ``maintype/subtype`` value." msgstr "" -#: library/email.contentmanager.rst:135 +#: library/email.contentmanager.rst:136 msgid "" "For ``str``, set the MIME ``maintype`` to ``text``, and set the subtype to " "*subtype* if it is specified, or ``plain`` if it is not." msgstr "" -#: library/email.contentmanager.rst:137 +#: library/email.contentmanager.rst:138 msgid "" "For ``bytes``, use the specified *maintype* and *subtype*, or raise a :exc:" "`TypeError` if they are not specified." msgstr "" -#: library/email.contentmanager.rst:139 +#: library/email.contentmanager.rst:140 msgid "" "For :class:`~email.message.EmailMessage` objects, set the maintype to " "``message``, and set the subtype to *subtype* if it is specified or " @@ -195,7 +195,7 @@ msgid "" "(``bytes`` objects must be used to construct ``message/partial`` parts)." msgstr "" -#: library/email.contentmanager.rst:145 +#: library/email.contentmanager.rst:146 msgid "" "If *charset* is provided (which is valid only for ``str``), encode the " "string to bytes using the specified character set. The default is " @@ -203,7 +203,7 @@ msgid "" "charset name, use the standard charset instead." msgstr "" -#: library/email.contentmanager.rst:150 +#: library/email.contentmanager.rst:151 msgid "" "If *cte* is set, encode the payload using the specified content transfer " "encoding, and set the :mailheader:`Content-Transfer-Encoding` header to that " @@ -213,13 +213,13 @@ msgid "" "that contains non-ASCII values), raise a :exc:`ValueError`." msgstr "" -#: library/email.contentmanager.rst:158 +#: library/email.contentmanager.rst:159 msgid "" "For ``str`` objects, if *cte* is not set use heuristics to determine the " "most compact encoding." msgstr "" -#: library/email.contentmanager.rst:160 +#: library/email.contentmanager.rst:161 msgid "" "For :class:`~email.message.EmailMessage`, per :rfc:`2046`, raise an error if " "a *cte* of ``quoted-printable`` or ``base64`` is requested for *subtype* " @@ -228,14 +228,14 @@ msgid "" "For all other values of *subtype*, use ``7bit``." msgstr "" -#: library/email.contentmanager.rst:167 +#: library/email.contentmanager.rst:168 msgid "" "A *cte* of ``binary`` does not actually work correctly yet. The " "``EmailMessage`` object as modified by ``set_content`` is correct, but :" "class:`~email.generator.BytesGenerator` does not serialize it correctly." msgstr "" -#: library/email.contentmanager.rst:172 +#: library/email.contentmanager.rst:173 msgid "" "If *disposition* is set, use it as the value of the :mailheader:`Content-" "Disposition` header. If not specified, and *filename* is specified, add the " @@ -244,37 +244,37 @@ msgid "" "values for *disposition* are ``attachment`` and ``inline``." msgstr "" -#: library/email.contentmanager.rst:179 +#: library/email.contentmanager.rst:180 msgid "" "If *filename* is specified, use it as the value of the ``filename`` " "parameter of the :mailheader:`Content-Disposition` header." msgstr "" -#: library/email.contentmanager.rst:182 +#: library/email.contentmanager.rst:183 msgid "" "If *cid* is specified, add a :mailheader:`Content-ID` header with *cid* as " "its value." msgstr "" -#: library/email.contentmanager.rst:185 +#: library/email.contentmanager.rst:186 msgid "" "If *params* is specified, iterate its ``items`` method and use the resulting " "``(key, value)`` pairs to set additional parameters on the :mailheader:" "`Content-Type` header." msgstr "" -#: library/email.contentmanager.rst:189 +#: library/email.contentmanager.rst:190 msgid "" "If *headers* is specified and is a list of strings of the form ``headername: " "headervalue`` or a list of ``header`` objects (distinguished from strings by " "having a ``name`` attribute), add the headers to *msg*." msgstr "" -#: library/email.contentmanager.rst:196 +#: library/email.contentmanager.rst:197 msgid "Footnotes" msgstr "" -#: library/email.contentmanager.rst:197 +#: library/email.contentmanager.rst:198 msgid "" "Originally added in 3.4 as a :term:`provisional module `" msgstr "" diff --git a/library/email.errors.po b/library/email.errors.po index 0471d855f..b7d88e421 100644 --- a/library/email.errors.po +++ b/library/email.errors.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -78,19 +78,24 @@ msgid "" "`~email.mime.image.MIMEImage`)." msgstr "" -#: library/email.errors.rst:63 +#: library/email.errors.rst:64 +msgid "" +"Raised when an error occurs when the :mod:`~email.generator` outputs headers." +msgstr "" + +#: library/email.errors.rst:70 msgid "" "This is the base class for all defects found when parsing email messages. It " "is derived from :exc:`ValueError`." msgstr "" -#: library/email.errors.rst:68 +#: library/email.errors.rst:75 msgid "" "This is the base class for all defects found when parsing email headers. It " "is derived from :exc:`MessageDefect`." msgstr "" -#: library/email.errors.rst:71 +#: library/email.errors.rst:78 msgid "" "Here is the list of the defects that the :class:`~email.parser.FeedParser` " "can find while parsing messages. Note that the defects are added to the " @@ -100,59 +105,59 @@ msgid "" "not." msgstr "" -#: library/email.errors.rst:77 +#: library/email.errors.rst:84 msgid "" "All defect classes are subclassed from :class:`email.errors.MessageDefect`." msgstr "" -#: library/email.errors.rst:79 +#: library/email.errors.rst:86 msgid "" ":class:`NoBoundaryInMultipartDefect` -- A message claimed to be a multipart, " "but had no :mimetype:`boundary` parameter." msgstr "" -#: library/email.errors.rst:82 +#: library/email.errors.rst:89 msgid "" ":class:`StartBoundaryNotFoundDefect` -- The start boundary claimed in the :" "mailheader:`Content-Type` header was never found." msgstr "" -#: library/email.errors.rst:85 +#: library/email.errors.rst:92 msgid "" ":class:`CloseBoundaryNotFoundDefect` -- A start boundary was found, but no " "corresponding close boundary was ever found." msgstr "" -#: library/email.errors.rst:90 +#: library/email.errors.rst:97 msgid "" ":class:`FirstHeaderLineIsContinuationDefect` -- The message had a " "continuation line as its first header line." msgstr "" -#: library/email.errors.rst:93 +#: library/email.errors.rst:100 msgid "" ":class:`MisplacedEnvelopeHeaderDefect` - A \"Unix From\" header was found in " "the middle of a header block." msgstr "" -#: library/email.errors.rst:96 +#: library/email.errors.rst:103 msgid "" ":class:`MissingHeaderBodySeparatorDefect` - A line was found while parsing " "headers that had no leading white space but contained no ':'. Parsing " "continues assuming that the line represents the first line of the body." msgstr "" -#: library/email.errors.rst:102 +#: library/email.errors.rst:109 msgid "" ":class:`MalformedHeaderDefect` -- A header was found that was missing a " "colon, or was otherwise malformed." msgstr "" -#: library/email.errors.rst:105 +#: library/email.errors.rst:112 msgid "This defect has not been used for several Python versions." msgstr "" -#: library/email.errors.rst:108 +#: library/email.errors.rst:115 msgid "" ":class:`MultipartInvariantViolationDefect` -- A message claimed to be a :" "mimetype:`multipart`, but no subparts were found. Note that when a message " @@ -161,28 +166,28 @@ msgid "" "`multipart`." msgstr "" -#: library/email.errors.rst:113 +#: library/email.errors.rst:120 msgid "" ":class:`InvalidBase64PaddingDefect` -- When decoding a block of base64 " "encoded bytes, the padding was not correct. Enough padding is added to " "perform the decode, but the resulting decoded bytes may be invalid." msgstr "" -#: library/email.errors.rst:117 +#: library/email.errors.rst:124 msgid "" ":class:`InvalidBase64CharactersDefect` -- When decoding a block of base64 " "encoded bytes, characters outside the base64 alphabet were encountered. The " "characters are ignored, but the resulting decoded bytes may be invalid." msgstr "" -#: library/email.errors.rst:121 +#: library/email.errors.rst:128 msgid "" ":class:`InvalidBase64LengthDefect` -- When decoding a block of base64 " "encoded bytes, the number of non-padding base64 characters was invalid (1 " "more than a multiple of 4). The encoded block was kept as-is." msgstr "" -#: library/email.errors.rst:125 +#: library/email.errors.rst:132 msgid "" ":class:`InvalidDateDefect` -- When decoding an invalid or unparsable date " "field. The original value is kept as-is." diff --git a/library/email.examples.po b/library/email.examples.po index 45c3977b6..dfdbe9301 100644 --- a/library/email.examples.po +++ b/library/email.examples.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2022-12-17 01:28+0300\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -32,30 +32,261 @@ msgid "" "content and the addresses may contain unicode characters):" msgstr "" +#: library/email.examples.rst:12 +msgid "" +"# Import smtplib for the actual sending function\n" +"import smtplib\n" +"\n" +"# Import the email modules we'll need\n" +"from email.message import EmailMessage\n" +"\n" +"# Open the plain text file whose name is in textfile for reading.\n" +"with open(textfile) as fp:\n" +" # Create a text/plain message\n" +" msg = EmailMessage()\n" +" msg.set_content(fp.read())\n" +"\n" +"# me == the sender's email address\n" +"# you == the recipient's email address\n" +"msg['Subject'] = f'The contents of {textfile}'\n" +"msg['From'] = me\n" +"msg['To'] = you\n" +"\n" +"# Send the message via our own SMTP server.\n" +"s = smtplib.SMTP('localhost')\n" +"s.send_message(msg)\n" +"s.quit()\n" +msgstr "" + #: library/email.examples.rst:15 msgid "" "Parsing :rfc:`822` headers can easily be done by the using the classes from " "the :mod:`~email.parser` module:" msgstr "" +#: library/email.examples.rst:18 +msgid "" +"# Import the email modules we'll need\n" +"#from email.parser import BytesParser\n" +"from email.parser import Parser\n" +"from email.policy import default\n" +"\n" +"# If the e-mail headers are in a file, uncomment these two lines:\n" +"# with open(messagefile, 'rb') as fp:\n" +"# headers = BytesParser(policy=default).parse(fp)\n" +"\n" +"# Or for parsing headers in a string (this is an uncommon operation), use:\n" +"headers = Parser(policy=default).parsestr(\n" +" 'From: Foo Bar \\n'\n" +" 'To: \\n'\n" +" 'Subject: Test message\\n'\n" +" '\\n'\n" +" 'Body would go here\\n')\n" +"\n" +"# Now the header items can be accessed as a dictionary:\n" +"print('To: {}'.format(headers['to']))\n" +"print('From: {}'.format(headers['from']))\n" +"print('Subject: {}'.format(headers['subject']))\n" +"\n" +"# You can also access the parts of the addresses:\n" +"print('Recipient username: {}'.format(headers['to'].addresses[0].username))\n" +"print('Sender name: {}'.format(headers['from'].addresses[0].display_name))\n" +msgstr "" + #: library/email.examples.rst:21 msgid "" "Here's an example of how to send a MIME message containing a bunch of family " "pictures that may be residing in a directory:" msgstr "" +#: library/email.examples.rst:24 +msgid "" +"# Import smtplib for the actual sending function.\n" +"import smtplib\n" +"\n" +"# Here are the email package modules we'll need.\n" +"from email.message import EmailMessage\n" +"\n" +"# Create the container email message.\n" +"msg = EmailMessage()\n" +"msg['Subject'] = 'Our family reunion'\n" +"# me == the sender's email address\n" +"# family = the list of all recipients' email addresses\n" +"msg['From'] = me\n" +"msg['To'] = ', '.join(family)\n" +"msg.preamble = 'You will not see this in a MIME-aware mail reader.\\n'\n" +"\n" +"# Open the files in binary mode. You can also omit the subtype\n" +"# if you want MIMEImage to guess it.\n" +"for file in pngfiles:\n" +" with open(file, 'rb') as fp:\n" +" img_data = fp.read()\n" +" msg.add_attachment(img_data, maintype='image',\n" +" subtype='png')\n" +"\n" +"# Send the email via our own SMTP server.\n" +"with smtplib.SMTP('localhost') as s:\n" +" s.send_message(msg)\n" +msgstr "" + #: library/email.examples.rst:27 msgid "" "Here's an example of how to send the entire contents of a directory as an " "email message: [1]_" msgstr "" +#: library/email.examples.rst:30 +msgid "" +"#!/usr/bin/env python3\n" +"\n" +"\"\"\"Send the contents of a directory as a MIME message.\"\"\"\n" +"\n" +"import os\n" +"import smtplib\n" +"# For guessing MIME type based on file name extension\n" +"import mimetypes\n" +"\n" +"from argparse import ArgumentParser\n" +"\n" +"from email.message import EmailMessage\n" +"from email.policy import SMTP\n" +"\n" +"\n" +"def main():\n" +" parser = ArgumentParser(description=\"\"\"\\\n" +"Send the contents of a directory as a MIME message.\n" +"Unless the -o option is given, the email is sent by forwarding to your " +"local\n" +"SMTP server, which then does the normal delivery process. Your local " +"machine\n" +"must be running an SMTP server.\n" +"\"\"\")\n" +" parser.add_argument('-d', '--directory',\n" +" help=\"\"\"Mail the contents of the specified " +"directory,\n" +" otherwise use the current directory. Only the " +"regular\n" +" files in the directory are sent, and we don't " +"recurse to\n" +" subdirectories.\"\"\")\n" +" parser.add_argument('-o', '--output',\n" +" metavar='FILE',\n" +" help=\"\"\"Print the composed message to FILE " +"instead of\n" +" sending the message to the SMTP server.\"\"\")\n" +" parser.add_argument('-s', '--sender', required=True,\n" +" help='The value of the From: header (required)')\n" +" parser.add_argument('-r', '--recipient', required=True,\n" +" action='append', metavar='RECIPIENT',\n" +" default=[], dest='recipients',\n" +" help='A To: header value (at least one required)')\n" +" args = parser.parse_args()\n" +" directory = args.directory\n" +" if not directory:\n" +" directory = '.'\n" +" # Create the message\n" +" msg = EmailMessage()\n" +" msg['Subject'] = f'Contents of directory {os.path.abspath(directory)}'\n" +" msg['To'] = ', '.join(args.recipients)\n" +" msg['From'] = args.sender\n" +" msg.preamble = 'You will not see this in a MIME-aware mail reader.\\n'\n" +"\n" +" for filename in os.listdir(directory):\n" +" path = os.path.join(directory, filename)\n" +" if not os.path.isfile(path):\n" +" continue\n" +" # Guess the content type based on the file's extension. Encoding\n" +" # will be ignored, although we should check for simple things like\n" +" # gzip'd or compressed files.\n" +" ctype, encoding = mimetypes.guess_type(path)\n" +" if ctype is None or encoding is not None:\n" +" # No guess could be made, or the file is encoded (compressed), " +"so\n" +" # use a generic bag-of-bits type.\n" +" ctype = 'application/octet-stream'\n" +" maintype, subtype = ctype.split('/', 1)\n" +" with open(path, 'rb') as fp:\n" +" msg.add_attachment(fp.read(),\n" +" maintype=maintype,\n" +" subtype=subtype,\n" +" filename=filename)\n" +" # Now send or store the message\n" +" if args.output:\n" +" with open(args.output, 'wb') as fp:\n" +" fp.write(msg.as_bytes(policy=SMTP))\n" +" else:\n" +" with smtplib.SMTP('localhost') as s:\n" +" s.send_message(msg)\n" +"\n" +"\n" +"if __name__ == '__main__':\n" +" main()\n" +msgstr "" + #: library/email.examples.rst:33 msgid "" "Here's an example of how to unpack a MIME message like the one above, into a " "directory of files:" msgstr "" +#: library/email.examples.rst:36 +msgid "" +"#!/usr/bin/env python3\n" +"\n" +"\"\"\"Unpack a MIME message into a directory of files.\"\"\"\n" +"\n" +"import os\n" +"import email\n" +"import mimetypes\n" +"\n" +"from email.policy import default\n" +"\n" +"from argparse import ArgumentParser\n" +"\n" +"\n" +"def main():\n" +" parser = ArgumentParser(description=\"\"\"\\\n" +"Unpack a MIME message into a directory of files.\n" +"\"\"\")\n" +" parser.add_argument('-d', '--directory', required=True,\n" +" help=\"\"\"Unpack the MIME message into the named\n" +" directory, which will be created if it doesn't " +"already\n" +" exist.\"\"\")\n" +" parser.add_argument('msgfile')\n" +" args = parser.parse_args()\n" +"\n" +" with open(args.msgfile, 'rb') as fp:\n" +" msg = email.message_from_binary_file(fp, policy=default)\n" +"\n" +" try:\n" +" os.mkdir(args.directory)\n" +" except FileExistsError:\n" +" pass\n" +"\n" +" counter = 1\n" +" for part in msg.walk():\n" +" # multipart/* are just containers\n" +" if part.get_content_maintype() == 'multipart':\n" +" continue\n" +" # Applications should really sanitize the given filename so that an\n" +" # email message can't be used to overwrite important files\n" +" filename = part.get_filename()\n" +" if not filename:\n" +" ext = mimetypes.guess_extension(part.get_content_type())\n" +" if not ext:\n" +" # Use a generic bag-of-bits extension\n" +" ext = '.bin'\n" +" filename = f'part-{counter:03d}{ext}'\n" +" counter += 1\n" +" with open(os.path.join(args.directory, filename), 'wb') as fp:\n" +" fp.write(part.get_payload(decode=True))\n" +"\n" +"\n" +"if __name__ == '__main__':\n" +" main()\n" +msgstr "" + #: library/email.examples.rst:39 msgid "" "Here's an example of how to create an HTML message with an alternative plain " @@ -64,16 +295,182 @@ msgid "" "disk, as well as sending it." msgstr "" +#: library/email.examples.rst:44 +msgid "" +"#!/usr/bin/env python3\n" +"\n" +"import smtplib\n" +"\n" +"from email.message import EmailMessage\n" +"from email.headerregistry import Address\n" +"from email.utils import make_msgid\n" +"\n" +"# Create the base text message.\n" +"msg = EmailMessage()\n" +"msg['Subject'] = \"Ayons asperges pour le déjeuner\"\n" +"msg['From'] = Address(\"Pepé Le Pew\", \"pepe\", \"example.com\")\n" +"msg['To'] = (Address(\"Penelope Pussycat\", \"penelope\", \"example.com\"),\n" +" Address(\"Fabrette Pussycat\", \"fabrette\", \"example.com\"))\n" +"msg.set_content(\"\"\"\\\n" +"Salut!\n" +"\n" +"Cela ressemble à un excellent recipie[1] déjeuner.\n" +"\n" +"[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718\n" +"\n" +"--Pepé\n" +"\"\"\")\n" +"\n" +"# Add the html version. This converts the message into a multipart/" +"alternative\n" +"# container, with the original text message as the first part and the new " +"html\n" +"# message as the second part.\n" +"asparagus_cid = make_msgid()\n" +"msg.add_alternative(\"\"\"\\\n" +"\n" +" \n" +" \n" +"

Salut!

\n" +"

Cela ressemble à un excellent\n" +" \n" +" recipie\n" +" déjeuner.\n" +"

\n" +" \n" +" \n" +"\n" +"\"\"\".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')\n" +"# note that we needed to peel the <> off the msgid for use in the html.\n" +"\n" +"# Now add the related image to the html part.\n" +"with open(\"roasted-asparagus.jpg\", 'rb') as img:\n" +" msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',\n" +" cid=asparagus_cid)\n" +"\n" +"# Make a local copy of what we are going to send.\n" +"with open('outgoing.msg', 'wb') as f:\n" +" f.write(bytes(msg))\n" +"\n" +"# Send the message via local SMTP server.\n" +"with smtplib.SMTP('localhost') as s:\n" +" s.send_message(msg)\n" +msgstr "" + #: library/email.examples.rst:47 msgid "" "If we were sent the message from the last example, here is one way we could " "process it:" msgstr "" +#: library/email.examples.rst:50 +msgid "" +"import os\n" +"import sys\n" +"import tempfile\n" +"import mimetypes\n" +"import webbrowser\n" +"\n" +"# Import the email modules we'll need\n" +"from email import policy\n" +"from email.parser import BytesParser\n" +"\n" +"\n" +"def magic_html_parser(html_text, partfiles):\n" +" \"\"\"Return safety-sanitized html linked to partfiles.\n" +"\n" +" Rewrite the href=\"cid:....\" attributes to point to the filenames in " +"partfiles.\n" +" Though not trivial, this should be possible using html.parser.\n" +" \"\"\"\n" +" raise NotImplementedError(\"Add the magic needed\")\n" +"\n" +"\n" +"# In a real program you'd get the filename from the arguments.\n" +"with open('outgoing.msg', 'rb') as fp:\n" +" msg = BytesParser(policy=policy.default).parse(fp)\n" +"\n" +"# Now the header items can be accessed as a dictionary, and any non-ASCII " +"will\n" +"# be converted to unicode:\n" +"print('To:', msg['to'])\n" +"print('From:', msg['from'])\n" +"print('Subject:', msg['subject'])\n" +"\n" +"# If we want to print a preview of the message content, we can extract " +"whatever\n" +"# the least formatted payload is and print the first three lines. Of " +"course,\n" +"# if the message has no plain text part printing the first three lines of " +"html\n" +"# is probably useless, but this is just a conceptual example.\n" +"simplest = msg.get_body(preferencelist=('plain', 'html'))\n" +"print()\n" +"print(''.join(simplest.get_content().splitlines(keepends=True)[:3]))\n" +"\n" +"ans = input(\"View full message?\")\n" +"if ans.lower()[0] == 'n':\n" +" sys.exit()\n" +"\n" +"# We can extract the richest alternative in order to display it:\n" +"richest = msg.get_body()\n" +"partfiles = {}\n" +"if richest['content-type'].maintype == 'text':\n" +" if richest['content-type'].subtype == 'plain':\n" +" for line in richest.get_content().splitlines():\n" +" print(line)\n" +" sys.exit()\n" +" elif richest['content-type'].subtype == 'html':\n" +" body = richest\n" +" else:\n" +" print(\"Don't know how to display {}\".format(richest." +"get_content_type()))\n" +" sys.exit()\n" +"elif richest['content-type'].content_type == 'multipart/related':\n" +" body = richest.get_body(preferencelist=('html'))\n" +" for part in richest.iter_attachments():\n" +" fn = part.get_filename()\n" +" if fn:\n" +" extension = os.path.splitext(part.get_filename())[1]\n" +" else:\n" +" extension = mimetypes.guess_extension(part.get_content_type())\n" +" with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as " +"f:\n" +" f.write(part.get_content())\n" +" # again strip the <> to go from email form of cid to html form.\n" +" partfiles[part['content-id'][1:-1]] = f.name\n" +"else:\n" +" print(\"Don't know how to display {}\".format(richest." +"get_content_type()))\n" +" sys.exit()\n" +"with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:\n" +" f.write(magic_html_parser(body.get_content(), partfiles))\n" +"webbrowser.open(f.name)\n" +"os.remove(f.name)\n" +"for fn in partfiles.values():\n" +" os.remove(fn)\n" +"\n" +"# Of course, there are lots of email messages that could break this simple\n" +"# minded program, but it will handle the most common ones.\n" +msgstr "" + #: library/email.examples.rst:52 msgid "Up to the prompt, the output from the above is:" msgstr "" +#: library/email.examples.rst:54 +msgid "" +"To: Penelope Pussycat , Fabrette Pussycat " +"\n" +"From: Pepé Le Pew \n" +"Subject: Ayons asperges pour le déjeuner\n" +"\n" +"Salut!\n" +"\n" +"Cela ressemble à un excellent recipie[1] déjeuner." +msgstr "" + #: library/email.examples.rst:66 msgid "Footnotes" msgstr "" diff --git a/library/email.header.po b/library/email.header.po index ac581dd70..21dc41801 100644 --- a/library/email.header.po +++ b/library/email.header.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -71,6 +71,17 @@ msgid "" "header` module. For example::" msgstr "" +#: library/email.header.rst:40 +msgid "" +">>> from email.message import Message\n" +">>> from email.header import Header\n" +">>> msg = Message()\n" +">>> h = Header('p\\xf6stal', 'iso-8859-1')\n" +">>> msg['Subject'] = h\n" +">>> msg.as_string()\n" +"'Subject: =?iso-8859-1?q?p=F6stal?=\\n\\n'" +msgstr "" + #: library/email.header.rst:50 msgid "" "Notice here how we wanted the :mailheader:`Subject` field to contain a non-" @@ -265,6 +276,13 @@ msgstr "" msgid "Here's an example::" msgstr "" +#: library/email.header.rst:188 +msgid "" +">>> from email.header import decode_header\n" +">>> decode_header('=?iso-8859-1?q?p=F6stal?=')\n" +"[(b'p\\xf6stal', 'iso-8859-1')]" +msgstr "" + #: library/email.header.rst:195 msgid "" "Create a :class:`Header` instance from a sequence of pairs as returned by :" diff --git a/library/email.headerregistry.po b/library/email.headerregistry.po index 75017efda..fde8fe325 100644 --- a/library/email.headerregistry.po +++ b/library/email.headerregistry.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -122,6 +122,10 @@ msgid "" "method is called as follows::" msgstr "" +#: library/email.headerregistry.rst:94 +msgid "parse(string, kwds)" +msgstr "" + #: library/email.headerregistry.rst:96 msgid "" "``kwds`` is a dictionary containing one pre-initialized key, ``defects``. " @@ -143,6 +147,13 @@ msgid "" "``BaseHeader`` itself. Such an ``init`` method should look like this::" msgstr "" +#: library/email.headerregistry.rst:110 +msgid "" +"def init(self, /, *args, **kw):\n" +" self._myattr = kw.pop('myattr')\n" +" super().init(*args, **kw)" +msgstr "" + #: library/email.headerregistry.rst:114 msgid "" "That is, anything extra that the specialized class puts in to the ``kwds`` " @@ -205,6 +216,10 @@ msgid "" "``datetime`` according to the :rfc:`5322` rules; that is, it is set to::" msgstr "" +#: library/email.headerregistry.rst:163 +msgid "email.utils.format_datetime(self.datetime)" +msgstr "" + #: library/email.headerregistry.rst:165 msgid "" "When creating a ``DateHeader``, *value* may be :class:`~datetime.datetime` " @@ -212,6 +227,10 @@ msgid "" "does what one would expect::" msgstr "" +#: library/email.headerregistry.rst:169 +msgid "msg['Date'] = datetime(2011, 7, 15, 21)" +msgstr "" + #: library/email.headerregistry.rst:171 msgid "" "Because this is a naive ``datetime`` it will be interpreted as a UTC " @@ -220,6 +239,10 @@ msgid "" "mod:`~email.utils` module::" msgstr "" +#: library/email.headerregistry.rst:176 +msgid "msg['Date'] = utils.localtime()" +msgstr "" + #: library/email.headerregistry.rst:178 msgid "" "This example sets the date header to the current time and date using the " @@ -361,7 +384,7 @@ msgid "" "class. When *use_default_map* is ``True`` (the default), the standard " "mapping of header names to classes is copied in to the registry during " "initialization. *base_class* is always the last class in the generated " -"class's ``__bases__`` list." +"class's :class:`~type.__bases__` list." msgstr "" #: library/email.headerregistry.rst:322 @@ -537,10 +560,18 @@ msgid "" "address is::" msgstr "" +#: library/email.headerregistry.rst:380 +msgid "[display_name] " +msgstr "" + #: library/email.headerregistry.rst:382 msgid "or::" msgstr "" +#: library/email.headerregistry.rst:384 +msgid "username@domain" +msgstr "" + #: library/email.headerregistry.rst:386 msgid "" "where each part must conform to specific syntax rules spelled out in :rfc:" @@ -598,6 +629,10 @@ msgid "" "address group is::" msgstr "" +#: library/email.headerregistry.rst:432 +msgid "display_name: [address-list];" +msgstr "" + #: library/email.headerregistry.rst:434 msgid "" "As a convenience for processing lists of addresses that consist of a mixture " diff --git a/library/email.iterators.po b/library/email.iterators.po index 7408c1a6a..c2cd0493d 100644 --- a/library/email.iterators.po +++ b/library/email.iterators.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -79,6 +79,27 @@ msgid "" "structure. For example:" msgstr "" +#: library/email.iterators.rst:57 +msgid "" +">>> msg = email.message_from_file(somefile)\n" +">>> _structure(msg)\n" +"multipart/mixed\n" +" text/plain\n" +" text/plain\n" +" multipart/digest\n" +" message/rfc822\n" +" text/plain\n" +" message/rfc822\n" +" text/plain\n" +" message/rfc822\n" +" text/plain\n" +" message/rfc822\n" +" text/plain\n" +" message/rfc822\n" +" text/plain\n" +" text/plain" +msgstr "" + #: library/email.iterators.rst:81 msgid "" "Optional *fp* is a file-like object to print the output to. It must be " diff --git a/library/email.message.po b/library/email.message.po index 272d039e8..b1e0fc122 100644 --- a/library/email.message.po +++ b/library/email.message.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -163,7 +163,7 @@ msgstr "" #: library/email.message.rst:127 msgid "" -"Equivalent to :meth:`.as_bytes()`. Allows ``bytes(msg)`` to produce a bytes " +"Equivalent to :meth:`.as_bytes`. Allows ``bytes(msg)`` to produce a bytes " "object containing the serialized message." msgstr "" @@ -228,6 +228,12 @@ msgid "" "Used for the ``in`` operator. For example::" msgstr "" +#: library/email.message.rst:185 +msgid "" +"if 'message-id' in myMessage:\n" +" print('Message-ID:', myMessage['message-id'])" +msgstr "" + #: library/email.message.rst:191 msgid "" "Return the value of the named header field. *name* does not include the " @@ -262,6 +268,12 @@ msgid "" "present in the message with field name *name*, delete the field first, e.g.::" msgstr "" +#: library/email.message.rst:213 +msgid "" +"del msg['subject']\n" +"msg['subject'] = 'Python roolz!'" +msgstr "" + #: library/email.message.rst:216 msgid "" "If the :mod:`policy ` defines certain headers to be unique (as " @@ -345,14 +357,28 @@ msgstr "" msgid "Here is an example::" msgstr "" +#: library/email.message.rst:289 +msgid "msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')" +msgstr "" + #: library/email.message.rst:291 msgid "This will add a header that looks like ::" msgstr "" +#: library/email.message.rst:293 +msgid "Content-Disposition: attachment; filename=\"bud.gif\"" +msgstr "" + #: library/email.message.rst:295 msgid "An example of the extended interface with non-ASCII characters::" msgstr "" +#: library/email.message.rst:297 +msgid "" +"msg.add_header('Content-Disposition', 'attachment',\n" +" filename=('iso-8859-1', '', 'Fußballer.ppt'))" +msgstr "" + #: library/email.message.rst:303 msgid "" "Replace a header. Replace the first header found in the message that " @@ -558,6 +584,19 @@ msgid "" "message structure:" msgstr "" +#: library/email.message.rst:491 +msgid "" +">>> for part in msg.walk():\n" +"... print(part.get_content_type())\n" +"multipart/report\n" +"text/plain\n" +"message/delivery-status\n" +"text/plain\n" +"text/plain\n" +"message/rfc822\n" +"text/plain" +msgstr "" + #: library/email.message.rst:503 msgid "" "``walk`` iterates over the subparts of any part where :meth:`is_multipart` " @@ -566,6 +605,29 @@ msgid "" "``_structure`` debug helper function:" msgstr "" +#: library/email.message.rst:509 +msgid "" +">>> from email.iterators import _structure\n" +">>> for part in msg.walk():\n" +"... print(part.get_content_maintype() == 'multipart',\n" +"... part.is_multipart())\n" +"True True\n" +"False False\n" +"False True\n" +"False False\n" +"False False\n" +"False True\n" +"False False\n" +">>> _structure(msg)\n" +"multipart/report\n" +" text/plain\n" +" message/delivery-status\n" +" text/plain\n" +" text/plain\n" +" message/rfc822\n" +" text/plain" +msgstr "" + #: library/email.message.rst:531 msgid "" "Here the ``message`` parts are not ``multiparts``, but they do contain " diff --git a/library/email.parser.po b/library/email.parser.po index 30df3c1cb..213fc5565 100644 --- a/library/email.parser.po +++ b/library/email.parser.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -323,6 +323,12 @@ msgid "" "interactive Python prompt::" msgstr "" +#: library/email.parser.rst:286 +msgid "" +">>> import email\n" +">>> msg = email.message_from_bytes(myBytes) " +msgstr "" + #: library/email.parser.rst:291 msgid "Additional notes" msgstr "" diff --git a/library/email.policy.po b/library/email.policy.po index dfb4d9817..fef8afc59 100644 --- a/library/email.policy.po +++ b/library/email.policy.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -120,6 +120,22 @@ msgid "" "system:" msgstr "" +#: library/email.policy.rst:92 +msgid "" +">>> from email import message_from_binary_file\n" +">>> from email.generator import BytesGenerator\n" +">>> from email import policy\n" +">>> from subprocess import Popen, PIPE\n" +">>> with open('mymsg.txt', 'rb') as f:\n" +"... msg = message_from_binary_file(f, policy=policy.default)\n" +"...\n" +">>> p = Popen(['sendmail', msg['To'].addresses[0]], stdin=PIPE)\n" +">>> g = BytesGenerator(p.stdin, policy=msg.policy.clone(linesep='\\r\\n'))\n" +">>> g.flatten(msg)\n" +">>> p.stdin.close()\n" +">>> rc = p.wait()" +msgstr "" + #: library/email.policy.rst:114 msgid "" "Here we are telling :class:`~email.generator.BytesGenerator` to use the RFC " @@ -137,6 +153,14 @@ msgid "" "line separators for the platform on which it is running::" msgstr "" +#: library/email.policy.rst:125 +msgid "" +">>> import os\n" +">>> with open('converted.txt', 'wb') as f:\n" +"... f.write(msg.as_bytes(policy=msg.policy.clone(linesep=os.linesep)))\n" +"17" +msgstr "" + #: library/email.policy.rst:130 msgid "" "Policy objects can also be combined using the addition operator, producing a " @@ -144,12 +168,31 @@ msgid "" "the summed objects::" msgstr "" +#: library/email.policy.rst:134 +msgid "" +">>> compat_SMTP = policy.compat32.clone(linesep='\\r\\n')\n" +">>> compat_strict = policy.compat32.clone(raise_on_defect=True)\n" +">>> compat_strict_SMTP = compat_SMTP + compat_strict" +msgstr "" + #: library/email.policy.rst:138 msgid "" "This operation is not commutative; that is, the order in which the objects " "are added matters. To illustrate::" msgstr "" +#: library/email.policy.rst:141 +msgid "" +">>> policy100 = policy.compat32.clone(max_line_length=100)\n" +">>> policy80 = policy.compat32.clone(max_line_length=80)\n" +">>> apolicy = policy100 + policy80\n" +">>> apolicy.max_line_length\n" +"80\n" +">>> apolicy = policy80 + policy100\n" +">>> apolicy.max_line_length\n" +"100" +msgstr "" + #: library/email.policy.rst:153 msgid "" "This is the :term:`abstract base class` for all policy classes. It provides " @@ -245,46 +288,62 @@ msgid "" "`~email.message.Message` is used." msgstr "" -#: library/email.policy.rst:232 +#: library/email.policy.rst:235 +msgid "" +"If ``True`` (the default), the generator will raise :exc:`~email.errors." +"HeaderWriteError` instead of writing a header that is improperly folded or " +"delimited, such that it would be parsed as multiple headers or joined with " +"adjacent data. Such headers can be generated by custom header classes or " +"bugs in the ``email`` module." +msgstr "" + +#: library/email.policy.rst:242 +msgid "" +"As it's a security feature, this defaults to ``True`` even in the :class:" +"`~email.policy.Compat32` policy. For backwards compatible, but unsafe, " +"behavior, it must be set to ``False`` explicitly." +msgstr "" + +#: library/email.policy.rst:250 msgid "" "The following :class:`Policy` method is intended to be called by code using " "the email library to create policy instances with custom settings:" msgstr "" -#: library/email.policy.rst:238 +#: library/email.policy.rst:256 msgid "" "Return a new :class:`Policy` instance whose attributes have the same values " "as the current instance, except where those attributes are given new values " "by the keyword arguments." msgstr "" -#: library/email.policy.rst:243 +#: library/email.policy.rst:261 msgid "" "The remaining :class:`Policy` methods are called by the email package code, " "and are not intended to be called by an application using the email package. " "A custom policy must implement all of these methods." msgstr "" -#: library/email.policy.rst:250 +#: library/email.policy.rst:268 msgid "" "Handle a *defect* found on *obj*. When the email package calls this method, " "*defect* will always be a subclass of :class:`~email.errors.Defect`." msgstr "" -#: library/email.policy.rst:254 +#: library/email.policy.rst:272 msgid "" "The default implementation checks the :attr:`raise_on_defect` flag. If it " "is ``True``, *defect* is raised as an exception. If it is ``False`` (the " "default), *obj* and *defect* are passed to :meth:`register_defect`." msgstr "" -#: library/email.policy.rst:261 +#: library/email.policy.rst:279 msgid "" "Register a *defect* on *obj*. In the email package, *defect* will always be " "a subclass of :class:`~email.errors.Defect`." msgstr "" -#: library/email.policy.rst:264 +#: library/email.policy.rst:282 msgid "" "The default implementation calls the ``append`` method of the ``defects`` " "attribute of *obj*. When the email package calls :attr:`handle_defect`, " @@ -294,11 +353,11 @@ msgid "" "defects in parsed messages will raise unexpected errors." msgstr "" -#: library/email.policy.rst:274 +#: library/email.policy.rst:292 msgid "Return the maximum allowed number of headers named *name*." msgstr "" -#: library/email.policy.rst:276 +#: library/email.policy.rst:294 msgid "" "Called when a header is added to an :class:`~email.message.EmailMessage` or :" "class:`~email.message.Message` object. If the returned value is not ``0`` " @@ -306,7 +365,7 @@ msgid "" "greater than or equal to the value returned, a :exc:`ValueError` is raised." msgstr "" -#: library/email.policy.rst:282 +#: library/email.policy.rst:300 msgid "" "Because the default behavior of ``Message.__setitem__`` is to append the " "value to the list of headers, it is easy to create duplicate headers without " @@ -316,11 +375,11 @@ msgid "" "faithfully produce as many headers as exist in the message being parsed.)" msgstr "" -#: library/email.policy.rst:290 +#: library/email.policy.rst:308 msgid "The default implementation returns ``None`` for all header names." msgstr "" -#: library/email.policy.rst:295 +#: library/email.policy.rst:313 msgid "" "The email package calls this method with a list of strings, each string " "ending with the line separation characters found in the source being " @@ -330,7 +389,7 @@ msgid "" "the parsed header." msgstr "" -#: library/email.policy.rst:302 +#: library/email.policy.rst:320 msgid "" "If an implementation wishes to retain compatibility with the existing email " "package policies, *name* should be the case preserved name (all characters " @@ -339,15 +398,15 @@ msgid "" "stripped of leading whitespace." msgstr "" -#: library/email.policy.rst:308 +#: library/email.policy.rst:326 msgid "*sourcelines* may contain surrogateescaped binary data." msgstr "" -#: library/email.policy.rst:326 library/email.policy.rst:342 +#: library/email.policy.rst:344 library/email.policy.rst:360 msgid "There is no default implementation" msgstr "" -#: library/email.policy.rst:315 +#: library/email.policy.rst:333 msgid "" "The email package calls this method with the name and value provided by the " "application program when the application program is modifying a ``Message`` " @@ -356,14 +415,14 @@ msgid "" "``Message`` to represent the header." msgstr "" -#: library/email.policy.rst:321 +#: library/email.policy.rst:339 msgid "" "If an implementation wishes to retain compatibility with the existing email " "package policies, the *name* and *value* should be strings or string " "subclasses that do not change the content of the passed in arguments." msgstr "" -#: library/email.policy.rst:331 +#: library/email.policy.rst:349 msgid "" "The email package calls this method with the *name* and *value* currently " "stored in the ``Message`` when that header is requested by the application " @@ -374,13 +433,13 @@ msgid "" "returned to the application." msgstr "" -#: library/email.policy.rst:339 +#: library/email.policy.rst:357 msgid "" "*value* may contain surrogateescaped binary data. There should be no " "surrogateescaped binary data in the value returned by the method." msgstr "" -#: library/email.policy.rst:347 +#: library/email.policy.rst:365 msgid "" "The email package calls this method with the *name* and *value* currently " "stored in the ``Message`` for a given header. The method should return a " @@ -390,32 +449,32 @@ msgid "" "discussion of the rules for folding email headers." msgstr "" -#: library/email.policy.rst:354 +#: library/email.policy.rst:372 msgid "" "*value* may contain surrogateescaped binary data. There should be no " "surrogateescaped binary data in the string returned by the method." msgstr "" -#: library/email.policy.rst:360 +#: library/email.policy.rst:378 msgid "" "The same as :meth:`fold`, except that the returned value should be a bytes " "object rather than a string." msgstr "" -#: library/email.policy.rst:363 +#: library/email.policy.rst:381 msgid "" "*value* may contain surrogateescaped binary data. These could be converted " "back into binary data in the returned bytes object." msgstr "" -#: library/email.policy.rst:370 +#: library/email.policy.rst:388 msgid "" "This concrete :class:`Policy` provides behavior that is intended to be fully " "compliant with the current email RFCs. These include (but are not limited " "to) :rfc:`5322`, :rfc:`2047`, and the current MIME RFCs." msgstr "" -#: library/email.policy.rst:374 +#: library/email.policy.rst:392 msgid "" "This policy adds new header parsing and folding algorithms. Instead of " "simple strings, headers are ``str`` subclasses with attributes that depend " @@ -423,23 +482,23 @@ msgid "" "implement :rfc:`2047` and :rfc:`5322`." msgstr "" -#: library/email.policy.rst:379 +#: library/email.policy.rst:397 msgid "" "The default value for the :attr:`~email.policy.Policy.message_factory` " "attribute is :class:`~email.message.EmailMessage`." msgstr "" -#: library/email.policy.rst:382 +#: library/email.policy.rst:400 msgid "" "In addition to the settable attributes listed above that apply to all " "policies, this policy adds the following additional attributes:" msgstr "" -#: library/email.policy.rst:385 +#: library/email.policy.rst:403 msgid "[1]_" msgstr "" -#: library/email.policy.rst:390 +#: library/email.policy.rst:408 msgid "" "If ``False``, follow :rfc:`5322`, supporting non-ASCII characters in headers " "by encoding them as \"encoded words\". If ``True``, follow :rfc:`6532` and " @@ -447,7 +506,7 @@ msgid "" "passed to SMTP servers that support the ``SMTPUTF8`` extension (:rfc:`6531`)." msgstr "" -#: library/email.policy.rst:399 +#: library/email.policy.rst:417 msgid "" "If the value for a header in the ``Message`` object originated from a :mod:" "`~email.parser` (as opposed to being set by a program), this attribute " @@ -455,37 +514,37 @@ msgid "" "transforming the message back into serialized form. The possible values are:" msgstr "" -#: library/email.policy.rst:406 +#: library/email.policy.rst:424 msgid "``none``" msgstr "" -#: library/email.policy.rst:406 +#: library/email.policy.rst:424 msgid "all source values use original folding" msgstr "" -#: library/email.policy.rst:408 +#: library/email.policy.rst:426 msgid "``long``" msgstr "" -#: library/email.policy.rst:408 +#: library/email.policy.rst:426 msgid "" "source values that have any line that is longer than ``max_line_length`` " "will be refolded" msgstr "" -#: library/email.policy.rst:411 +#: library/email.policy.rst:429 msgid "``all``" msgstr "" -#: library/email.policy.rst:411 +#: library/email.policy.rst:429 msgid "all values are refolded." msgstr "" -#: library/email.policy.rst:414 +#: library/email.policy.rst:432 msgid "The default is ``long``." msgstr "" -#: library/email.policy.rst:419 +#: library/email.policy.rst:437 msgid "" "A callable that takes two arguments, ``name`` and ``value``, where ``name`` " "is a header field name and ``value`` is an unfolded header field value, and " @@ -496,7 +555,7 @@ msgid "" "custom parsing will be added in the future." msgstr "" -#: library/email.policy.rst:430 +#: library/email.policy.rst:448 msgid "" "An object with at least two methods: get_content and set_content. When the :" "meth:`~email.message.EmailMessage.get_content` or :meth:`~email.message." @@ -507,20 +566,20 @@ msgid "" "``content_manager`` is set to :data:`~email.contentmanager.raw_data_manager`." msgstr "" -#: library/email.policy.rst:600 +#: library/email.policy.rst:618 msgid "" "The class provides the following concrete implementations of the abstract " "methods of :class:`Policy`:" msgstr "" -#: library/email.policy.rst:448 +#: library/email.policy.rst:466 msgid "" "Returns the value of the :attr:`~email.headerregistry.BaseHeader.max_count` " "attribute of the specialized class used to represent the header with the " "given name." msgstr "" -#: library/email.policy.rst:606 +#: library/email.policy.rst:624 msgid "" "The name is parsed as everything up to the '``:``' and returned unmodified. " "The value is determined by stripping leading whitespace off the remainder of " @@ -528,7 +587,7 @@ msgid "" "trailing carriage return or linefeed characters." msgstr "" -#: library/email.policy.rst:464 +#: library/email.policy.rst:482 msgid "" "The name is returned unchanged. If the input value has a ``name`` attribute " "and it matches *name* ignoring case, the value is returned unchanged. " @@ -537,7 +596,7 @@ msgid "" "``ValueError`` is raised if the input value contains CR or LF characters." msgstr "" -#: library/email.policy.rst:474 +#: library/email.policy.rst:492 msgid "" "If the value has a ``name`` attribute, it is returned to unmodified. " "Otherwise the *name*, and the *value* with any CR or LF characters removed, " @@ -546,7 +605,7 @@ msgid "" "character glyph." msgstr "" -#: library/email.policy.rst:483 +#: library/email.policy.rst:501 msgid "" "Header folding is controlled by the :attr:`refold_source` policy setting. A " "value is considered to be a 'source value' if and only if it does not have a " @@ -558,7 +617,7 @@ msgid "" "current policy." msgstr "" -#: library/email.policy.rst:492 +#: library/email.policy.rst:510 msgid "" "Source values are split into lines using :meth:`~str.splitlines`. If the " "value is not to be refolded, the lines are rejoined using the ``linesep`` " @@ -568,13 +627,13 @@ msgid "" "using the ``unknown-8bit`` charset." msgstr "" -#: library/email.policy.rst:502 +#: library/email.policy.rst:520 msgid "" "The same as :meth:`fold` if :attr:`~Policy.cte_type` is ``7bit``, except " "that the returned value is bytes." msgstr "" -#: library/email.policy.rst:505 +#: library/email.policy.rst:523 msgid "" "If :attr:`~Policy.cte_type` is ``8bit``, non-ASCII binary data is converted " "back into bytes. Headers with binary data are not refolded, regardless of " @@ -582,7 +641,7 @@ msgid "" "binary data consists of single byte characters or multibyte characters." msgstr "" -#: library/email.policy.rst:512 +#: library/email.policy.rst:530 msgid "" "The following instances of :class:`EmailPolicy` provide defaults suitable " "for specific application domains. Note that in the future the behavior of " @@ -590,20 +649,20 @@ msgid "" "conform even more closely to the RFCs relevant to their domains." msgstr "" -#: library/email.policy.rst:520 +#: library/email.policy.rst:538 msgid "" "An instance of ``EmailPolicy`` with all defaults unchanged. This policy " "uses the standard Python ``\\n`` line endings rather than the RFC-correct " "``\\r\\n``." msgstr "" -#: library/email.policy.rst:527 +#: library/email.policy.rst:545 msgid "" "Suitable for serializing messages in conformance with the email RFCs. Like " "``default``, but with ``linesep`` set to ``\\r\\n``, which is RFC compliant." msgstr "" -#: library/email.policy.rst:534 +#: library/email.policy.rst:552 msgid "" "The same as ``SMTP`` except that :attr:`~EmailPolicy.utf8` is ``True``. " "Useful for serializing messages to a message store without using encoded " @@ -612,46 +671,50 @@ msgid "" "SMTP.send_message` method handles this automatically)." msgstr "" -#: library/email.policy.rst:543 +#: library/email.policy.rst:561 msgid "" "Suitable for serializing headers with for use in HTTP traffic. Like " "``SMTP`` except that ``max_line_length`` is set to ``None`` (unlimited)." msgstr "" -#: library/email.policy.rst:549 +#: library/email.policy.rst:567 msgid "" "Convenience instance. The same as ``default`` except that " "``raise_on_defect`` is set to ``True``. This allows any policy to be made " "strict by writing::" msgstr "" -#: library/email.policy.rst:556 +#: library/email.policy.rst:571 +msgid "somepolicy + policy.strict" +msgstr "" + +#: library/email.policy.rst:574 msgid "" "With all of these :class:`EmailPolicies <.EmailPolicy>`, the effective API " "of the email package is changed from the Python 3.2 API in the following " "ways:" msgstr "" -#: library/email.policy.rst:559 +#: library/email.policy.rst:577 msgid "" "Setting a header on a :class:`~email.message.Message` results in that header " "being parsed and a header object created." msgstr "" -#: library/email.policy.rst:562 +#: library/email.policy.rst:580 msgid "" "Fetching a header value from a :class:`~email.message.Message` results in " "that header being parsed and a header object created and returned." msgstr "" -#: library/email.policy.rst:566 +#: library/email.policy.rst:584 msgid "" "Any header object, or any header that is refolded due to the policy " "settings, is folded using an algorithm that fully implements the RFC folding " "algorithms, including knowing where encoded words are required and allowed." msgstr "" -#: library/email.policy.rst:571 +#: library/email.policy.rst:589 msgid "" "From the application view, this means that any header obtained through the :" "class:`~email.message.EmailMessage` is a header object with extra " @@ -661,13 +724,13 @@ msgid "" "the unicode string into the correct RFC encoded form." msgstr "" -#: library/email.policy.rst:578 +#: library/email.policy.rst:596 msgid "" "The header objects and their attributes are described in :mod:`~email." "headerregistry`." msgstr "" -#: library/email.policy.rst:585 +#: library/email.policy.rst:603 msgid "" "This concrete :class:`Policy` is the backward compatibility policy. It " "replicates the behavior of the email package in Python 3.2. The :mod:" @@ -676,28 +739,28 @@ msgid "" "of the email package is to maintain compatibility with Python 3.2." msgstr "" -#: library/email.policy.rst:591 +#: library/email.policy.rst:609 msgid "" "The following attributes have values that are different from the :class:" "`Policy` default:" msgstr "" -#: library/email.policy.rst:597 +#: library/email.policy.rst:615 msgid "The default is ``True``." msgstr "" -#: library/email.policy.rst:614 +#: library/email.policy.rst:632 msgid "The name and value are returned unmodified." msgstr "" -#: library/email.policy.rst:619 +#: library/email.policy.rst:637 msgid "" "If the value contains binary data, it is converted into a :class:`~email." "header.Header` object using the ``unknown-8bit`` charset. Otherwise it is " "returned unmodified." msgstr "" -#: library/email.policy.rst:626 +#: library/email.policy.rst:644 msgid "" "Headers are folded using the :class:`~email.header.Header` folding " "algorithm, which preserves existing line breaks in the value, and wraps each " @@ -705,7 +768,7 @@ msgid "" "encoded using the ``unknown-8bit`` charset." msgstr "" -#: library/email.policy.rst:634 +#: library/email.policy.rst:652 msgid "" "Headers are folded using the :class:`~email.header.Header` folding " "algorithm, which preserves existing line breaks in the value, and wraps each " @@ -715,17 +778,17 @@ msgid "" "and any (RFC invalid) binary data it may contain." msgstr "" -#: library/email.policy.rst:644 +#: library/email.policy.rst:662 msgid "" "An instance of :class:`Compat32`, providing backward compatibility with the " "behavior of the email package in Python 3.2." msgstr "" -#: library/email.policy.rst:649 +#: library/email.policy.rst:667 msgid "Footnotes" msgstr "" -#: library/email.policy.rst:650 +#: library/email.policy.rst:668 msgid "" "Originally added in 3.3 as a :term:`provisional feature `." diff --git a/library/email.utils.po b/library/email.utils.po index 82fe1b73e..e61f659d7 100644 --- a/library/email.utils.po +++ b/library/email.utils.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -88,7 +88,16 @@ msgid "" "unless the parse fails, in which case a 2-tuple of ``('', '')`` is returned." msgstr "" -#: library/email.utils.rst:71 +#: library/email.utils.rst:96 +msgid "" +"If *strict* is true, use a strict parser which rejects malformed inputs." +msgstr "" + +#: library/email.utils.rst:108 +msgid "Add *strict* optional parameter and reject malformed inputs by default." +msgstr "" + +#: library/email.utils.rst:76 msgid "" "The inverse of :meth:`parseaddr`, this takes a 2-tuple of the form " "``(realname, email_address)`` and returns the string value suitable for a :" @@ -96,7 +105,7 @@ msgid "" "is false, then the second element is returned unmodified." msgstr "" -#: library/email.utils.rst:76 +#: library/email.utils.rst:81 msgid "" "Optional *charset* is the character set that will be used in the :rfc:`2047` " "encoding of the ``realname`` if the ``realname`` contains non-ASCII " @@ -104,19 +113,33 @@ msgid "" "Charset`. Defaults to ``utf-8``." msgstr "" -#: library/email.utils.rst:81 +#: library/email.utils.rst:86 msgid "Added the *charset* option." msgstr "" -#: library/email.utils.rst:87 +#: library/email.utils.rst:92 msgid "" "This method returns a list of 2-tuples of the form returned by " "``parseaddr()``. *fieldvalues* is a sequence of header field values as might " -"be returned by :meth:`Message.get_all `. " -"Here's a simple example that gets all the recipients of a message::" +"be returned by :meth:`Message.get_all `." +msgstr "" + +#: library/email.utils.rst:98 +msgid "Here's a simple example that gets all the recipients of a message::" +msgstr "" + +#: library/email.utils.rst:100 +msgid "" +"from email.utils import getaddresses\n" +"\n" +"tos = msg.get_all('to', [])\n" +"ccs = msg.get_all('cc', [])\n" +"resent_tos = msg.get_all('resent-to', [])\n" +"resent_ccs = msg.get_all('resent-cc', [])\n" +"all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)" msgstr "" -#: library/email.utils.rst:103 +#: library/email.utils.rst:114 msgid "" "Attempts to parse a date according to the rules in :rfc:`2822`. however, " "some mailers don't follow that format as specified, so :func:`parsedate` " @@ -127,7 +150,7 @@ msgid "" "returned. Note that indexes 6, 7, and 8 of the result tuple are not usable." msgstr "" -#: library/email.utils.rst:114 +#: library/email.utils.rst:125 msgid "" "Performs the same function as :func:`parsedate`, but returns either ``None`` " "or a 10-tuple; the first 9 elements make up a tuple that can be passed " @@ -138,7 +161,7 @@ msgid "" "the result tuple are not usable." msgstr "" -#: library/email.utils.rst:124 +#: library/email.utils.rst:135 msgid "" "The inverse of :func:`format_datetime`. Performs the same function as :func:" "`parsedate`, but on success returns a :mod:`~datetime.datetime`; otherwise " @@ -152,25 +175,29 @@ msgid "" "corresponding a :class:`~datetime.timezone` :class:`~datetime.tzinfo`." msgstr "" -#: library/email.utils.rst:140 +#: library/email.utils.rst:151 msgid "" "Turn a 10-tuple as returned by :func:`parsedate_tz` into a UTC timestamp " "(seconds since the Epoch). If the timezone item in the tuple is ``None``, " "assume local time." msgstr "" -#: library/email.utils.rst:147 +#: library/email.utils.rst:158 msgid "Returns a date string as per :rfc:`2822`, e.g.::" msgstr "" -#: library/email.utils.rst:151 +#: library/email.utils.rst:160 +msgid "Fri, 09 Nov 2001 01:08:47 -0000" +msgstr "" + +#: library/email.utils.rst:162 msgid "" "Optional *timeval* if given is a floating-point time value as accepted by :" "func:`time.gmtime` and :func:`time.localtime`, otherwise the current time is " "used." msgstr "" -#: library/email.utils.rst:155 +#: library/email.utils.rst:166 msgid "" "Optional *localtime* is a flag that when ``True``, interprets *timeval*, and " "returns a date relative to the local timezone instead of UTC, properly " @@ -178,7 +205,7 @@ msgid "" "UTC is used." msgstr "" -#: library/email.utils.rst:160 +#: library/email.utils.rst:171 msgid "" "Optional *usegmt* is a flag that when ``True``, outputs a date string with " "the timezone as an ascii string ``GMT``, rather than a numeric ``-0000``. " @@ -186,7 +213,7 @@ msgid "" "*localtime* is ``False``. The default is ``False``." msgstr "" -#: library/email.utils.rst:168 +#: library/email.utils.rst:179 msgid "" "Like ``formatdate``, but the input is a :mod:`datetime` instance. If it is " "a naive datetime, it is assumed to be \"UTC with no information about the " @@ -198,11 +225,11 @@ msgid "" "date headers." msgstr "" -#: library/email.utils.rst:182 +#: library/email.utils.rst:193 msgid "Decode the string *s* according to :rfc:`2231`." msgstr "" -#: library/email.utils.rst:187 +#: library/email.utils.rst:198 msgid "" "Encode the string *s* according to :rfc:`2231`. Optional *charset* and " "*language*, if given is the character set name and language name to use. If " @@ -211,7 +238,7 @@ msgid "" "*language*." msgstr "" -#: library/email.utils.rst:195 +#: library/email.utils.rst:206 msgid "" "When a header parameter is encoded in :rfc:`2231` format, :meth:`Message." "get_param ` may return a 3-tuple containing " @@ -223,23 +250,23 @@ msgid "" "defaults to ``'us-ascii'``." msgstr "" -#: library/email.utils.rst:204 +#: library/email.utils.rst:215 msgid "" "For convenience, if the *value* passed to :func:`collapse_rfc2231_value` is " "not a tuple, it should be a string and it is returned unquoted." msgstr "" -#: library/email.utils.rst:210 +#: library/email.utils.rst:221 msgid "" "Decode parameters list according to :rfc:`2231`. *params* is a sequence of " "2-tuples containing elements of the form ``(content-type, string-value)``." msgstr "" -#: library/email.utils.rst:215 +#: library/email.utils.rst:226 msgid "Footnotes" msgstr "" -#: library/email.utils.rst:216 +#: library/email.utils.rst:227 msgid "" "Note that the sign of the timezone offset is the opposite of the sign of the " "``time.timezone`` variable for the same timezone; the latter variable " diff --git a/library/ensurepip.po b/library/ensurepip.po index 6a7e21f0e..489dee190 100644 --- a/library/ensurepip.po +++ b/library/ensurepip.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -65,7 +65,7 @@ msgid "The original rationale and specification for this module." msgstr "" #: includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not Emscripten, not WASI." +msgid "Availability" msgstr "" #: includes/wasm-notavail.rst:5 @@ -88,6 +88,10 @@ msgstr "" msgid "The simplest possible invocation is::" msgstr "" +#: library/ensurepip.rst:50 +msgid "python -m ensurepip" +msgstr "" + #: library/ensurepip.rst:52 msgid "" "This invocation will install ``pip`` if it is not already installed, but " @@ -96,6 +100,10 @@ msgid "" "upgrade`` option::" msgstr "" +#: library/ensurepip.rst:57 +msgid "python -m ensurepip --upgrade" +msgstr "" + #: library/ensurepip.rst:59 msgid "" "By default, ``pip`` is installed into the current virtual environment (if " @@ -207,7 +215,9 @@ msgid "" msgstr "" #: library/ensurepip.rst:125 -msgid "Raises an auditing event ensurepip.bootstrap with argument root." +msgid "" +"Raises an :ref:`auditing event ` ``ensurepip.bootstrap`` with " +"argument ``root``." msgstr "" #: library/ensurepip.rst:129 diff --git a/library/enum.po b/library/enum.po index 73d5bacea..be20d405a 100644 --- a/library/enum.po +++ b/library/enum.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -70,6 +70,20 @@ msgid "" "using function-call syntax::" msgstr "" +#: library/enum.rst:38 +msgid "" +">>> from enum import Enum\n" +"\n" +">>> # class syntax\n" +">>> class Color(Enum):\n" +"... RED = 1\n" +"... GREEN = 2\n" +"... BLUE = 3\n" +"\n" +">>> # functional syntax\n" +">>> Color = Enum('Color', ['RED', 'GREEN', 'BLUE'])" +msgstr "" + #: library/enum.rst:49 msgid "" "Even though we can use :keyword:`class` syntax to create Enums, Enums are " @@ -382,6 +396,15 @@ msgstr "" msgid "Returns ``True`` if member belongs to the ``cls``::" msgstr "" +#: library/enum.rst:198 +msgid "" +">>> some_var = Color.RED\n" +">>> some_var in Color\n" +"True\n" +">>> Color.RED.value in Color\n" +"True" +msgstr "" + #: library/enum.rst:206 msgid "" "Before Python 3.12, a ``TypeError`` is raised if a non-Enum-member is used " @@ -394,20 +417,46 @@ msgid "" "names of the members in *cls*::" msgstr "" +#: library/enum.rst:214 +msgid "" +">>> dir(Color)\n" +"['BLUE', 'GREEN', 'RED', '__class__', '__contains__', '__doc__', " +"'__getitem__', '__init_subclass__', '__iter__', '__len__', '__members__', " +"'__module__', '__name__', '__qualname__']" +msgstr "" + #: library/enum.rst:219 msgid "" "Returns the Enum member in *cls* matching *name*, or raises a :exc:" "`KeyError`::" msgstr "" +#: library/enum.rst:221 +msgid "" +">>> Color['BLUE']\n" +"" +msgstr "" + #: library/enum.rst:226 msgid "Returns each member in *cls* in definition order::" msgstr "" +#: library/enum.rst:228 +msgid "" +">>> list(Color)\n" +"[, , ]" +msgstr "" + #: library/enum.rst:233 msgid "Returns the number of member in *cls*::" msgstr "" +#: library/enum.rst:235 +msgid "" +">>> len(Color)\n" +"3" +msgstr "" + #: library/enum.rst:240 msgid "Returns a mapping of every enum name to its member, including aliases" msgstr "" @@ -416,6 +465,12 @@ msgstr "" msgid "Returns each member in *cls* in reverse definition order::" msgstr "" +#: library/enum.rst:246 +msgid "" +">>> list(reversed(Color))\n" +"[, , ]" +msgstr "" + #: library/enum.rst:251 msgid "Before 3.11 ``enum`` used ``EnumMeta`` type, which is kept as an alias." msgstr "" @@ -428,10 +483,22 @@ msgstr "" msgid "The name used to define the ``Enum`` member::" msgstr "" +#: library/enum.rst:262 +msgid "" +">>> Color.BLUE.name\n" +"'BLUE'" +msgstr "" + #: library/enum.rst:267 msgid "The value given to the ``Enum`` member::" msgstr "" +#: library/enum.rst:269 +msgid "" +">>> Color.RED.value\n" +"1" +msgstr "" + #: library/enum.rst:292 msgid "Value of the member, can be set in :meth:`~Enum.__new__`." msgstr "" @@ -484,6 +551,26 @@ msgid "" "public methods defined on *self.__class__*::" msgstr "" +#: library/enum.rst:313 +msgid "" +">>> from datetime import date\n" +">>> class Weekday(Enum):\n" +"... MONDAY = 1\n" +"... TUESDAY = 2\n" +"... WEDNESDAY = 3\n" +"... THURSDAY = 4\n" +"... FRIDAY = 5\n" +"... SATURDAY = 6\n" +"... SUNDAY = 7\n" +"... @classmethod\n" +"... def today(cls):\n" +"... print('today is %s' % cls(date.today().isoweekday()).name)\n" +"...\n" +">>> dir(Weekday.SATURDAY)\n" +"['__class__', '__doc__', '__eq__', '__hash__', '__module__', 'name', " +"'today', 'value']" +msgstr "" + #: library/enum.rst:0 msgid "name" msgstr "" @@ -518,6 +605,20 @@ msgid "" "`auto`::" msgstr "" +#: library/enum.rst:339 +msgid "" +">>> from enum import auto\n" +">>> class PowersOfThree(Enum):\n" +"... @staticmethod\n" +"... def _generate_next_value_(name, start, count, last_values):\n" +"... return 3 ** (count + 1)\n" +"... FIRST = auto()\n" +"... SECOND = auto()\n" +"...\n" +">>> PowersOfThree.SECOND.value\n" +"9" +msgstr "" + #: library/enum.rst:352 msgid "" "By default, does nothing. If multiple values are given in the member " @@ -542,6 +643,26 @@ msgid "" "does nothing, but can be overridden to implement custom search behavior::" msgstr "" +#: library/enum.rst:371 +msgid "" +">>> from enum import StrEnum\n" +">>> class Build(StrEnum):\n" +"... DEBUG = auto()\n" +"... OPTIMIZED = auto()\n" +"... @classmethod\n" +"... def _missing_(cls, value):\n" +"... value = value.lower()\n" +"... for member in cls:\n" +"... if member.value == value:\n" +"... return member\n" +"... return None\n" +"...\n" +">>> Build.DEBUG.value\n" +"'debug'\n" +">>> Build('deBUG')\n" +"" +msgstr "" + #: library/enum.rst:390 msgid "" "By default, doesn't exist. If specified, either in the enum class " @@ -566,18 +687,61 @@ msgid "" "name, member name, and value, but can be overridden::" msgstr "" +#: library/enum.rst:410 +msgid "" +">>> class OtherStyle(Enum):\n" +"... ALTERNATE = auto()\n" +"... OTHER = auto()\n" +"... SOMETHING_ELSE = auto()\n" +"... def __repr__(self):\n" +"... cls_name = self.__class__.__name__\n" +"... return f'{cls_name}.{self.name}'\n" +"...\n" +">>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f\"{OtherStyle." +"ALTERNATE}\"\n" +"(OtherStyle.ALTERNATE, 'OtherStyle.ALTERNATE', 'OtherStyle.ALTERNATE')" +msgstr "" + #: library/enum.rst:423 msgid "" "Returns the string used for *str()* calls. By default, returns the *Enum* " "name and member name, but can be overridden::" msgstr "" +#: library/enum.rst:426 +msgid "" +">>> class OtherStyle(Enum):\n" +"... ALTERNATE = auto()\n" +"... OTHER = auto()\n" +"... SOMETHING_ELSE = auto()\n" +"... def __str__(self):\n" +"... return f'{self.name}'\n" +"...\n" +">>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f\"{OtherStyle." +"ALTERNATE}\"\n" +"(, 'ALTERNATE', 'ALTERNATE')" +msgstr "" + #: library/enum.rst:438 msgid "" "Returns the string used for *format()* and *f-string* calls. By default, " "returns :meth:`__str__` return value, but can be overridden::" msgstr "" +#: library/enum.rst:441 +msgid "" +">>> class OtherStyle(Enum):\n" +"... ALTERNATE = auto()\n" +"... OTHER = auto()\n" +"... SOMETHING_ELSE = auto()\n" +"... def __format__(self, spec):\n" +"... return f'{self.name}'\n" +"...\n" +">>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f\"{OtherStyle." +"ALTERNATE}\"\n" +"(, 'OtherStyle.ALTERNATE', 'ALTERNATE')" +msgstr "" + #: library/enum.rst:453 msgid "" "Using :class:`auto` with :class:`Enum` results in integers of increasing " @@ -649,256 +813,424 @@ msgstr "" msgid "Returns *True* if value is in self::" msgstr "" +#: library/enum.rst:526 +msgid "" +">>> from enum import Flag, auto\n" +">>> class Color(Flag):\n" +"... RED = auto()\n" +"... GREEN = auto()\n" +"... BLUE = auto()\n" +"...\n" +">>> purple = Color.RED | Color.BLUE\n" +">>> white = Color.RED | Color.GREEN | Color.BLUE\n" +">>> Color.GREEN in purple\n" +"False\n" +">>> Color.GREEN in white\n" +"True\n" +">>> purple in white\n" +"True\n" +">>> white in purple\n" +"False" +msgstr "" + #: library/enum.rst:545 msgid "Returns all contained non-alias members::" msgstr "" +#: library/enum.rst:547 +msgid "" +">>> list(Color.RED)\n" +"[]\n" +">>> list(purple)\n" +"[, ]" +msgstr "" + #: library/enum.rst:556 msgid "Returns number of members in flag::" msgstr "" -#: library/enum.rst:565 +#: library/enum.rst:558 +msgid "" +">>> len(Color.GREEN)\n" +"1\n" +">>> len(white)\n" +"3" +msgstr "" + +#: library/enum.rst:567 msgid "Returns *True* if any members in flag, *False* otherwise::" msgstr "" -#: library/enum.rst:577 +#: library/enum.rst:569 +msgid "" +">>> bool(Color.GREEN)\n" +"True\n" +">>> bool(white)\n" +"True\n" +">>> black = Color(0)\n" +">>> bool(black)\n" +"False" +msgstr "" + +#: library/enum.rst:579 msgid "Returns current flag binary or'ed with other::" msgstr "" -#: library/enum.rst:584 +#: library/enum.rst:581 +msgid "" +">>> Color.RED | Color.GREEN\n" +"" +msgstr "" + +#: library/enum.rst:586 msgid "Returns current flag binary and'ed with other::" msgstr "" -#: library/enum.rst:593 +#: library/enum.rst:588 +msgid "" +">>> purple & white\n" +"\n" +">>> purple & Color.GREEN\n" +"" +msgstr "" + +#: library/enum.rst:595 msgid "Returns current flag binary xor'ed with other::" msgstr "" -#: library/enum.rst:602 +#: library/enum.rst:597 +msgid "" +">>> purple ^ white\n" +"\n" +">>> purple ^ Color.GREEN\n" +"" +msgstr "" + +#: library/enum.rst:604 msgid "Returns all the flags in *type(self)* that are not in self::" msgstr "" -#: library/enum.rst:613 +#: library/enum.rst:606 +msgid "" +">>> ~white\n" +"\n" +">>> ~purple\n" +"\n" +">>> ~Color.RED\n" +"" +msgstr "" + +#: library/enum.rst:615 msgid "" "Function used to format any remaining unnamed numeric values. Default is " "the value's repr; common choices are :func:`hex` and :func:`oct`." msgstr "" -#: library/enum.rst:618 +#: library/enum.rst:620 msgid "" "Using :class:`auto` with :class:`Flag` results in integers that are powers " "of two, starting with ``1``." msgstr "" -#: library/enum.rst:621 +#: library/enum.rst:623 msgid "The *repr()* of zero-valued flags has changed. It is now::" msgstr "" -#: library/enum.rst:629 +#: library/enum.rst:631 msgid "" "*IntFlag* is the same as *Flag*, but its members are also integers and can " "be used anywhere that an integer can be used." msgstr "" -#: library/enum.rst:643 +#: library/enum.rst:645 msgid "" "If any integer operation is performed with an *IntFlag* member, the result " "is not an *IntFlag*::" msgstr "" -#: library/enum.rst:649 -msgid "If a *Flag* operation is performed with an *IntFlag* member and:" +#: library/enum.rst:648 +msgid "" +">>> Color.RED + 2\n" +"3" msgstr "" #: library/enum.rst:651 +msgid "If a *Flag* operation is performed with an *IntFlag* member and:" +msgstr "" + +#: library/enum.rst:653 msgid "the result is a valid *IntFlag*: an *IntFlag* is returned" msgstr "" -#: library/enum.rst:652 +#: library/enum.rst:654 msgid "" "the result is not a valid *IntFlag*: the result depends on the " "*FlagBoundary* setting" msgstr "" -#: library/enum.rst:654 +#: library/enum.rst:656 msgid "The *repr()* of unnamed zero-valued flags has changed. It is now:" msgstr "" -#: library/enum.rst:661 +#: library/enum.rst:663 msgid "" "Using :class:`auto` with :class:`IntFlag` results in integers that are " "powers of two, starting with ``1``." msgstr "" -#: library/enum.rst:666 +#: library/enum.rst:668 msgid "" ":meth:`~object.__str__` is now :meth:`!int.__str__` to better support the " "*replacement of existing constants* use-case. :meth:`~object.__format__` " "was already :meth:`!int.__format__` for that same reason." msgstr "" -#: library/enum.rst:670 +#: library/enum.rst:672 msgid "" "Inversion of an :class:`!IntFlag` now returns a positive value that is the " "union of all flags not in the given flag, rather than a negative value. This " "matches the existing :class:`Flag` behavior." msgstr "" -#: library/enum.rst:676 +#: library/enum.rst:678 msgid "" ":class:`!ReprEnum` uses the :meth:`repr() ` of :class:`Enum`, " "but the :class:`str() ` of the mixed-in data type:" msgstr "" -#: library/enum.rst:679 +#: library/enum.rst:681 msgid ":meth:`!int.__str__` for :class:`IntEnum` and :class:`IntFlag`" msgstr "" -#: library/enum.rst:680 +#: library/enum.rst:682 msgid ":meth:`!str.__str__` for :class:`StrEnum`" msgstr "" -#: library/enum.rst:682 +#: library/enum.rst:684 msgid "" "Inherit from :class:`!ReprEnum` to keep the :class:`str() ` / :func:" "`format` of the mixed-in data type instead of using the :class:`Enum`-" "default :meth:`str() `." msgstr "" -#: library/enum.rst:691 +#: library/enum.rst:693 msgid "" "*EnumCheck* contains the options used by the :func:`verify` decorator to " "ensure various constraints; failed constraints result in a :exc:`ValueError`." msgstr "" -#: library/enum.rst:696 +#: library/enum.rst:698 msgid "Ensure that each value has only one name::" msgstr "" -#: library/enum.rst:712 +#: library/enum.rst:700 +msgid "" +">>> from enum import Enum, verify, UNIQUE\n" +">>> @verify(UNIQUE)\n" +"... class Color(Enum):\n" +"... RED = 1\n" +"... GREEN = 2\n" +"... BLUE = 3\n" +"... CRIMSON = 1\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: aliases found in : CRIMSON -> RED" +msgstr "" + +#: library/enum.rst:714 msgid "" "Ensure that there are no missing values between the lowest-valued member and " "the highest-valued member::" msgstr "" -#: library/enum.rst:727 +#: library/enum.rst:717 +msgid "" +">>> from enum import Enum, verify, CONTINUOUS\n" +">>> @verify(CONTINUOUS)\n" +"... class Color(Enum):\n" +"... RED = 1\n" +"... GREEN = 2\n" +"... BLUE = 5\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: invalid enum 'Color': missing values 3, 4" +msgstr "" + +#: library/enum.rst:729 msgid "" "Ensure that any flag groups/masks contain only named flags -- useful when " "values are specified instead of being generated by :func:`auto`::" msgstr "" -#: library/enum.rst:744 +#: library/enum.rst:732 +msgid "" +">>> from enum import Flag, verify, NAMED_FLAGS\n" +">>> @verify(NAMED_FLAGS)\n" +"... class Color(Flag):\n" +"... RED = 1\n" +"... GREEN = 2\n" +"... BLUE = 4\n" +"... WHITE = 15\n" +"... NEON = 31\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: invalid Flag 'Color': aliases WHITE and NEON are missing " +"combined values of 0x18 [use enum.show_flag_values(value) for details]" +msgstr "" + +#: library/enum.rst:746 msgid "" "CONTINUOUS and NAMED_FLAGS are designed to work with integer-valued members." msgstr "" -#: library/enum.rst:750 +#: library/enum.rst:752 msgid "" "*FlagBoundary* controls how out-of-range values are handled in *Flag* and " "its subclasses." msgstr "" -#: library/enum.rst:755 +#: library/enum.rst:757 msgid "" "Out-of-range values cause a :exc:`ValueError` to be raised. This is the " "default for :class:`Flag`::" msgstr "" -#: library/enum.rst:773 +#: library/enum.rst:760 +msgid "" +">>> from enum import Flag, STRICT, auto\n" +">>> class StrictFlag(Flag, boundary=STRICT):\n" +"... RED = auto()\n" +"... GREEN = auto()\n" +"... BLUE = auto()\n" +"...\n" +">>> StrictFlag(2**2 + 2**4)\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: invalid value 20\n" +" given 0b0 10100\n" +" allowed 0b0 00111" +msgstr "" + +#: library/enum.rst:775 msgid "" "Out-of-range values have invalid values removed, leaving a valid *Flag* " "value::" msgstr "" -#: library/enum.rst:787 +#: library/enum.rst:778 +msgid "" +">>> from enum import Flag, CONFORM, auto\n" +">>> class ConformFlag(Flag, boundary=CONFORM):\n" +"... RED = auto()\n" +"... GREEN = auto()\n" +"... BLUE = auto()\n" +"...\n" +">>> ConformFlag(2**2 + 2**4)\n" +"" +msgstr "" + +#: library/enum.rst:789 msgid "" "Out-of-range values lose their *Flag* membership and revert to :class:`int`." msgstr "" -#: library/enum.rst:800 +#: library/enum.rst:802 msgid "" "Out-of-range values are kept, and the *Flag* membership is kept. This is the " "default for :class:`IntFlag`::" msgstr "" -#: library/enum.rst:817 -msgid "Supported ``__dunder__`` names" +#: library/enum.rst:805 +msgid "" +">>> from enum import Flag, KEEP, auto\n" +">>> class KeepFlag(Flag, boundary=KEEP):\n" +"... RED = auto()\n" +"... GREEN = auto()\n" +"... BLUE = auto()\n" +"...\n" +">>> KeepFlag(2**2 + 2**4)\n" +"" msgstr "" #: library/enum.rst:819 +msgid "Supported ``__dunder__`` names" +msgstr "" + +#: library/enum.rst:821 msgid "" ":attr:`~EnumType.__members__` is a read-only ordered mapping of " "``member_name``:``member`` items. It is only available on the class." msgstr "" -#: library/enum.rst:822 +#: library/enum.rst:824 msgid "" ":meth:`~Enum.__new__`, if specified, must create and return the enum " "members; it is also a very good idea to set the member's :attr:`!_value_` " "appropriately. Once all the members are created it is no longer used." msgstr "" -#: library/enum.rst:828 +#: library/enum.rst:830 msgid "Supported ``_sunder_`` names" msgstr "" -#: library/enum.rst:830 +#: library/enum.rst:832 msgid ":attr:`~Enum._name_` -- name of the member" msgstr "" -#: library/enum.rst:831 +#: library/enum.rst:833 msgid ":attr:`~Enum._value_` -- value of the member; can be set in ``__new__``" msgstr "" -#: library/enum.rst:832 +#: library/enum.rst:834 msgid "" ":meth:`~Enum._missing_` -- a lookup function used when a value is not found; " "may be overridden" msgstr "" -#: library/enum.rst:834 +#: library/enum.rst:836 msgid "" ":attr:`~Enum._ignore_` -- a list of names, either as a :class:`list` or a :" "class:`str`, that will not be transformed into members, and will be removed " "from the final class" msgstr "" -#: library/enum.rst:837 +#: library/enum.rst:839 msgid "" ":attr:`~Enum._order_` -- no longer used, kept for backward compatibility " "(class attribute, removed during class creation)" msgstr "" -#: library/enum.rst:839 +#: library/enum.rst:841 msgid "" ":meth:`~Enum._generate_next_value_` -- used to get an appropriate value for " "an enum member; may be overridden" msgstr "" -#: library/enum.rst:844 +#: library/enum.rst:846 msgid "" "For standard :class:`Enum` classes the next value chosen is the last value " "seen incremented by one." msgstr "" -#: library/enum.rst:847 +#: library/enum.rst:849 msgid "" "For :class:`Flag` classes the next value chosen will be the next highest " "power-of-two, regardless of the last value seen." msgstr "" -#: library/enum.rst:850 +#: library/enum.rst:852 msgid "``_missing_``, ``_order_``, ``_generate_next_value_``" msgstr "" -#: library/enum.rst:851 +#: library/enum.rst:853 msgid "``_ignore_``" msgstr "" -#: library/enum.rst:856 +#: library/enum.rst:858 msgid "Utilities and Decorators" msgstr "" -#: library/enum.rst:860 +#: library/enum.rst:862 msgid "" "*auto* can be used in place of a value. If used, the *Enum* machinery will " "call an *Enum*'s :meth:`~Enum._generate_next_value_` to get an appropriate " @@ -909,54 +1241,54 @@ msgid "" "manually specified values." msgstr "" -#: library/enum.rst:868 +#: library/enum.rst:870 msgid "" "*auto* instances are only resolved when at the top level of an assignment:" msgstr "" -#: library/enum.rst:870 +#: library/enum.rst:872 msgid "``FIRST = auto()`` will work (auto() is replaced with ``1``);" msgstr "" -#: library/enum.rst:871 +#: library/enum.rst:873 msgid "" "``SECOND = auto(), -2`` will work (auto is replaced with ``2``, so ``2, -2`` " "is used to create the ``SECOND`` enum member;" msgstr "" -#: library/enum.rst:873 +#: library/enum.rst:875 msgid "" "``THREE = [auto(), -3]`` will *not* work (``, -3`` is used to " "create the ``THREE`` enum member)" msgstr "" -#: library/enum.rst:878 +#: library/enum.rst:880 msgid "" "In prior versions, ``auto()`` had to be the only thing on the assignment " "line to work properly." msgstr "" -#: library/enum.rst:881 +#: library/enum.rst:883 msgid "" "``_generate_next_value_`` can be overridden to customize the values used by " "*auto*." msgstr "" -#: library/enum.rst:884 +#: library/enum.rst:886 msgid "" "in 3.13 the default ``_generate_next_value_`` will always return the highest " "member value incremented by 1, and will fail if any member is an " "incompatible type." msgstr "" -#: library/enum.rst:890 +#: library/enum.rst:892 msgid "" "A decorator similar to the built-in *property*, but specifically for " "enumerations. It allows member attributes to have the same names as members " "themselves." msgstr "" -#: library/enum.rst:894 +#: library/enum.rst:896 msgid "" "the *property* and the member must be defined in separate classes; for " "example, the *value* and *name* attributes are defined in the *Enum* class, " @@ -964,29 +1296,44 @@ msgid "" "``name``." msgstr "" -#: library/enum.rst:903 +#: library/enum.rst:905 msgid "" "A :keyword:`class` decorator specifically for enumerations. It searches an " "enumeration's :attr:`~EnumType.__members__`, gathering any aliases it finds; " "if any are found :exc:`ValueError` is raised with the details::" msgstr "" -#: library/enum.rst:921 +#: library/enum.rst:909 +msgid "" +">>> from enum import Enum, unique\n" +">>> @unique\n" +"... class Mistake(Enum):\n" +"... ONE = 1\n" +"... TWO = 2\n" +"... THREE = 3\n" +"... FOUR = 3\n" +"...\n" +"Traceback (most recent call last):\n" +"...\n" +"ValueError: duplicate values found in : FOUR -> THREE" +msgstr "" + +#: library/enum.rst:923 msgid "" "A :keyword:`class` decorator specifically for enumerations. Members from :" "class:`EnumCheck` are used to specify which constraints should be checked on " "the decorated enumeration." msgstr "" -#: library/enum.rst:929 +#: library/enum.rst:931 msgid "A decorator for use in enums: its target will become a member." msgstr "" -#: library/enum.rst:935 +#: library/enum.rst:937 msgid "A decorator for use in enums: its target will not become a member." msgstr "" -#: library/enum.rst:941 +#: library/enum.rst:943 msgid "" "A decorator to change the :class:`str() ` and :func:`repr` of an enum " "to show its members as belonging to the module instead of its class. Should " @@ -994,40 +1341,54 @@ msgid "" "namespace (see :class:`re.RegexFlag` for an example)." msgstr "" -#: library/enum.rst:951 +#: library/enum.rst:953 msgid "Return a list of all power-of-two integers contained in a flag *value*." msgstr "" -#: library/enum.rst:958 +#: library/enum.rst:960 msgid "Notes" msgstr "" -#: library/enum.rst:960 +#: library/enum.rst:962 msgid ":class:`IntEnum`, :class:`StrEnum`, and :class:`IntFlag`" msgstr "" -#: library/enum.rst:962 +#: library/enum.rst:964 msgid "" "These three enum types are designed to be drop-in replacements for existing " "integer- and string-based values; as such, they have extra limitations:" msgstr "" -#: library/enum.rst:965 +#: library/enum.rst:967 msgid "``__str__`` uses the value and not the name of the enum member" msgstr "" -#: library/enum.rst:967 +#: library/enum.rst:969 msgid "" "``__format__``, because it uses ``__str__``, will also use the value of the " "enum member instead of its name" msgstr "" -#: library/enum.rst:970 +#: library/enum.rst:972 msgid "" "If you do not need/want those limitations, you can either create your own " "base class by mixing in the ``int`` or ``str`` type yourself::" msgstr "" -#: library/enum.rst:977 +#: library/enum.rst:975 +msgid "" +">>> from enum import Enum\n" +">>> class MyIntEnum(int, Enum):\n" +"... pass" +msgstr "" + +#: library/enum.rst:979 msgid "or you can reassign the appropriate :meth:`str`, etc., in your enum::" msgstr "" + +#: library/enum.rst:981 +msgid "" +">>> from enum import Enum, IntEnum\n" +">>> class MyIntEnum(IntEnum):\n" +"... __str__ = Enum.__str__" +msgstr "" diff --git a/library/errno.po b/library/errno.po index 73bc54a8f..9d157e2cb 100644 --- a/library/errno.po +++ b/library/errno.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -586,7 +586,7 @@ msgid "" msgstr "" #: library/errno.rst:673 -msgid ":ref:`Availability `: WASI, FreeBSD" +msgid "Availability" msgstr "" #: library/errno.rst:680 diff --git a/library/exceptions.po b/library/exceptions.po index fccc08854..d7f038ad3 100644 --- a/library/exceptions.po +++ b/library/exceptions.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: 2024-02-17 13:11+0300\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -116,6 +116,10 @@ msgstr "" "Bu örtük istisna bağlamı(implicit exception context), :keyword:`!from` ile :" "keyword:`raise`: kullanılarak açık bir neden ile desteklenebilir:" +#: library/exceptions.rst:63 +msgid "raise new_exc from original_exc" +msgstr "" + #: library/exceptions.rst:65 msgid "" "The expression following :keyword:`from` must be an exception or " @@ -254,6 +258,15 @@ msgstr "" "izlemesinde olduğu gibi, ``OtherException`` ın geri izlemesine itilir, eğer " "arayan kişiye yayılmasına izin verseydik:" +#: library/exceptions.rst:135 +msgid "" +"try:\n" +" ...\n" +"except SomeException:\n" +" tb = sys.exception().__traceback__\n" +" raise OtherException(...).with_traceback(tb)" +msgstr "" + #: library/exceptions.rst:143 msgid "" "A writable field that holds the :ref:`traceback object ` " @@ -1557,6 +1570,35 @@ msgstr "" "`derive` tarafından döndürülene kopyalar, böylece bu alanların :meth:" "`derive` tarafından güncellenmesi gerekmez." +#: library/exceptions.rst:983 +msgid "" +">>> class MyGroup(ExceptionGroup):\n" +"... def derive(self, excs):\n" +"... return MyGroup(self.message, excs)\n" +"...\n" +">>> e = MyGroup(\"eg\", [ValueError(1), TypeError(2)])\n" +">>> e.add_note(\"a note\")\n" +">>> e.__context__ = Exception(\"context\")\n" +">>> e.__cause__ = Exception(\"cause\")\n" +">>> try:\n" +"... raise e\n" +"... except Exception as e:\n" +"... exc = e\n" +"...\n" +">>> match, rest = exc.split(ValueError)\n" +">>> exc, exc.__context__, exc.__cause__, exc.__notes__\n" +"(MyGroup('eg', [ValueError(1), TypeError(2)]), Exception('context'), " +"Exception('cause'), ['a note'])\n" +">>> match, match.__context__, match.__cause__, match.__notes__\n" +"(MyGroup('eg', [ValueError(1)]), Exception('context'), Exception('cause'), " +"['a note'])\n" +">>> rest, rest.__context__, rest.__cause__, rest.__notes__\n" +"(MyGroup('eg', [TypeError(2)]), Exception('context'), Exception('cause'), " +"['a note'])\n" +">>> exc.__traceback__ is match.__traceback__ is rest.__traceback__\n" +"True" +msgstr "" + #: library/exceptions.rst:1009 msgid "" "Note that :exc:`BaseExceptionGroup` defines :meth:`~object.__new__`, so " @@ -1571,6 +1613,18 @@ msgstr "" "gerekir. Örneğin, aşağıda bir exit_code kabul eden ve grubun mesajını bundan " "oluşturan bir istisna grubu alt sınıfı tanımlanmaktadır:" +#: library/exceptions.rst:1015 +msgid "" +"class Errors(ExceptionGroup):\n" +" def __new__(cls, errors, exit_code):\n" +" self = super().__new__(Errors, f\"exit code: {exit_code}\", errors)\n" +" self.exit_code = exit_code\n" +" return self\n" +"\n" +" def derive(self, excs):\n" +" return Errors(excs, self.exit_code)" +msgstr "" + #: library/exceptions.rst:1024 msgid "" "Like :exc:`ExceptionGroup`, any subclass of :exc:`BaseExceptionGroup` which " @@ -1589,6 +1643,77 @@ msgstr "İstisna hiyerarşisi" msgid "The class hierarchy for built-in exceptions is:" msgstr "Gömülü istisnalar için sınıf hiyerarşisi şöyledir:" +#: library/exceptions.rst:1036 +msgid "" +"BaseException\n" +" ├── BaseExceptionGroup\n" +" ├── GeneratorExit\n" +" ├── KeyboardInterrupt\n" +" ├── SystemExit\n" +" └── Exception\n" +" ├── ArithmeticError\n" +" │ ├── FloatingPointError\n" +" │ ├── OverflowError\n" +" │ └── ZeroDivisionError\n" +" ├── AssertionError\n" +" ├── AttributeError\n" +" ├── BufferError\n" +" ├── EOFError\n" +" ├── ExceptionGroup [BaseExceptionGroup]\n" +" ├── ImportError\n" +" │ └── ModuleNotFoundError\n" +" ├── LookupError\n" +" │ ├── IndexError\n" +" │ └── KeyError\n" +" ├── MemoryError\n" +" ├── NameError\n" +" │ └── UnboundLocalError\n" +" ├── OSError\n" +" │ ├── BlockingIOError\n" +" │ ├── ChildProcessError\n" +" │ ├── ConnectionError\n" +" │ │ ├── BrokenPipeError\n" +" │ │ ├── ConnectionAbortedError\n" +" │ │ ├── ConnectionRefusedError\n" +" │ │ └── ConnectionResetError\n" +" │ ├── FileExistsError\n" +" │ ├── FileNotFoundError\n" +" │ ├── InterruptedError\n" +" │ ├── IsADirectoryError\n" +" │ ├── NotADirectoryError\n" +" │ ├── PermissionError\n" +" │ ├── ProcessLookupError\n" +" │ └── TimeoutError\n" +" ├── ReferenceError\n" +" ├── RuntimeError\n" +" │ ├── NotImplementedError\n" +" │ └── RecursionError\n" +" ├── StopAsyncIteration\n" +" ├── StopIteration\n" +" ├── SyntaxError\n" +" │ └── IndentationError\n" +" │ └── TabError\n" +" ├── SystemError\n" +" ├── TypeError\n" +" ├── ValueError\n" +" │ └── UnicodeError\n" +" │ ├── UnicodeDecodeError\n" +" │ ├── UnicodeEncodeError\n" +" │ └── UnicodeTranslateError\n" +" └── Warning\n" +" ├── BytesWarning\n" +" ├── DeprecationWarning\n" +" ├── EncodingWarning\n" +" ├── FutureWarning\n" +" ├── ImportWarning\n" +" ├── PendingDeprecationWarning\n" +" ├── ResourceWarning\n" +" ├── RuntimeWarning\n" +" ├── SyntaxWarning\n" +" ├── UnicodeWarning\n" +" └── UserWarning\n" +msgstr "" + #: library/exceptions.rst:17 library/exceptions.rst:196 msgid "statement" msgstr "statement" diff --git a/library/faulthandler.po b/library/faulthandler.po index 1f45e072f..19402fc2b 100644 --- a/library/faulthandler.po +++ b/library/faulthandler.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -250,3 +250,20 @@ msgid "" "Example of a segmentation fault on Linux with and without enabling the fault " "handler:" msgstr "" + +#: library/faulthandler.rst:178 +msgid "" +"$ python -c \"import ctypes; ctypes.string_at(0)\"\n" +"Segmentation fault\n" +"\n" +"$ python -q -X faulthandler\n" +">>> import ctypes\n" +">>> ctypes.string_at(0)\n" +"Fatal Python error: Segmentation fault\n" +"\n" +"Current thread 0x00007fb899f39700 (most recent call first):\n" +" File \"/home/python/cpython/Lib/ctypes/__init__.py\", line 486 in " +"string_at\n" +" File \"\", line 1 in \n" +"Segmentation fault" +msgstr "" diff --git a/library/fcntl.po b/library/fcntl.po index bfba0d34e..b18aa2b32 100644 --- a/library/fcntl.po +++ b/library/fcntl.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -29,7 +29,7 @@ msgid "" msgstr "" #: library/fcntl.rst:21 -msgid ":ref:`Availability `: Unix, not Emscripten, not WASI." +msgid "Availability" msgstr "" #: library/fcntl.rst:23 @@ -112,7 +112,9 @@ msgid "If the :c:func:`fcntl` call fails, an :exc:`OSError` is raised." msgstr "" #: library/fcntl.rst:85 -msgid "Raises an auditing event fcntl.fcntl with arguments fd, cmd, arg." +msgid "" +"Raises an :ref:`auditing event ` ``fcntl.fcntl`` with arguments " +"``fd``, ``cmd``, ``arg``." msgstr "" #: library/fcntl.rst:90 @@ -176,8 +178,24 @@ msgstr "" msgid "An example::" msgstr "" +#: library/fcntl.rst:125 +msgid "" +">>> import array, fcntl, struct, termios, os\n" +">>> os.getpgrp()\n" +"13341\n" +">>> struct.unpack('h', fcntl.ioctl(0, termios.TIOCGPGRP, \" \"))[0]\n" +"13341\n" +">>> buf = array.array('h', [0])\n" +">>> fcntl.ioctl(0, termios.TIOCGPGRP, buf, 1)\n" +"0\n" +">>> buf\n" +"array('h', [13341])" +msgstr "" + #: library/fcntl.rst:136 -msgid "Raises an auditing event fcntl.ioctl with arguments fd, request, arg." +msgid "" +"Raises an :ref:`auditing event ` ``fcntl.ioctl`` with arguments " +"``fd``, ``request``, ``arg``." msgstr "" #: library/fcntl.rst:141 @@ -194,7 +212,9 @@ msgid "" msgstr "" #: library/fcntl.rst:148 -msgid "Raises an auditing event fcntl.flock with arguments fd, operation." +msgid "" +"Raises an :ref:`auditing event ` ``fcntl.flock`` with arguments " +"``fd``, ``operation``." msgstr "" #: library/fcntl.rst:153 @@ -261,14 +281,25 @@ msgstr "" #: library/fcntl.rst:194 msgid "" -"Raises an auditing event fcntl.lockf with arguments fd, cmd, len, start, " -"whence." +"Raises an :ref:`auditing event ` ``fcntl.lockf`` with arguments " +"``fd``, ``cmd``, ``len``, ``start``, ``whence``." msgstr "" #: library/fcntl.rst:196 msgid "Examples (all on a SVR4 compliant system)::" msgstr "" +#: library/fcntl.rst:198 +msgid "" +"import struct, fcntl, os\n" +"\n" +"f = open(...)\n" +"rv = fcntl.fcntl(f, fcntl.F_SETFL, os.O_NDELAY)\n" +"\n" +"lockdata = struct.pack('hhllhh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)\n" +"rv = fcntl.fcntl(f, fcntl.F_SETLKW, lockdata)" +msgstr "" + #: library/fcntl.rst:206 msgid "" "Note that in the first example the return value variable *rv* will hold an " diff --git a/library/filecmp.po b/library/filecmp.po index f9d9d1755..0154f2b14 100644 --- a/library/filecmp.po +++ b/library/filecmp.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -234,3 +234,17 @@ msgid "" "Here is a simplified example of using the ``subdirs`` attribute to search " "recursively through two directories to show common different files::" msgstr "" + +#: library/filecmp.rst:197 +msgid "" +">>> from filecmp import dircmp\n" +">>> def print_diff_files(dcmp):\n" +"... for name in dcmp.diff_files:\n" +"... print(\"diff_file %s found in %s and %s\" % (name, dcmp.left,\n" +"... dcmp.right))\n" +"... for sub_dcmp in dcmp.subdirs.values():\n" +"... print_diff_files(sub_dcmp)\n" +"...\n" +">>> dcmp = dircmp('dir1', 'dir2') \n" +">>> print_diff_files(dcmp) " +msgstr "" diff --git a/library/fileinput.po b/library/fileinput.po index e4361e12b..f24cb502f 100644 --- a/library/fileinput.po +++ b/library/fileinput.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -35,6 +35,13 @@ msgstr "" msgid "The typical use is::" msgstr "" +#: library/fileinput.rst:20 +msgid "" +"import fileinput\n" +"for line in fileinput.input(encoding=\"utf-8\"):\n" +" process(line)" +msgstr "" + #: library/fileinput.rst:24 msgid "" "This iterates over the lines of all files listed in ``sys.argv[1:]``, " @@ -107,6 +114,14 @@ msgid "" "keyword:`!with` statement is exited, even if an exception occurs::" msgstr "" +#: library/fileinput.rst:70 +msgid "" +"with fileinput.input(files=('spam.txt', 'eggs.txt'), encoding=\"utf-8\") as " +"f:\n" +" for line in f:\n" +" process(line)" +msgstr "" + #: library/fileinput.rst:170 msgid "Can be used as a context manager." msgstr "" @@ -222,6 +237,12 @@ msgid "" "keyword:`!with` statement is exited, even if an exception occurs::" msgstr "" +#: library/fileinput.rst:167 +msgid "" +"with FileInput(files=('spam.txt', 'eggs.txt')) as input:\n" +" process(input)" +msgstr "" + #: library/fileinput.rst:173 msgid "The keyword parameter *mode* and *openhook* are now keyword-only." msgstr "" diff --git a/library/fnmatch.po b/library/fnmatch.po index dfd53cb3c..a638d06db 100644 --- a/library/fnmatch.po +++ b/library/fnmatch.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -108,6 +108,16 @@ msgid "" "extension ``.txt``::" msgstr "" +#: library/fnmatch.rst:64 +msgid "" +"import fnmatch\n" +"import os\n" +"\n" +"for file in os.listdir('.'):\n" +" if fnmatch.fnmatch(file, '*.txt'):\n" +" print(file)" +msgstr "" + #: library/fnmatch.rst:74 msgid "" "Test whether the filename string *name* matches the pattern string *pat*, " diff --git a/library/fractions.po b/library/fractions.po index eaf4fbb2d..5789a26c8 100644 --- a/library/fractions.po +++ b/library/fractions.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -53,6 +53,10 @@ msgid "" "instance. The usual form for this instance is::" msgstr "" +#: library/fractions.rst:41 +msgid "[sign] numerator ['/' denominator]" +msgstr "" + #: library/fractions.rst:43 msgid "" "where the optional ``sign`` may be either '+' or '-' and ``numerator`` and " @@ -64,6 +68,34 @@ msgid "" "whitespace. Here are some examples::" msgstr "" +#: library/fractions.rst:52 +msgid "" +">>> from fractions import Fraction\n" +">>> Fraction(16, -10)\n" +"Fraction(-8, 5)\n" +">>> Fraction(123)\n" +"Fraction(123, 1)\n" +">>> Fraction()\n" +"Fraction(0, 1)\n" +">>> Fraction('3/7')\n" +"Fraction(3, 7)\n" +">>> Fraction(' -3/7 ')\n" +"Fraction(-3, 7)\n" +">>> Fraction('1.414213 \\t\\n')\n" +"Fraction(1414213, 1000000)\n" +">>> Fraction('-.125')\n" +"Fraction(-1, 8)\n" +">>> Fraction('7e-6')\n" +"Fraction(7, 1000000)\n" +">>> Fraction(2.25)\n" +"Fraction(9, 4)\n" +">>> Fraction(1.1)\n" +"Fraction(2476979795053773, 2251799813685248)\n" +">>> from decimal import Decimal\n" +">>> Fraction(Decimal('1.1'))\n" +"Fraction(11, 10)" +msgstr "" + #: library/fractions.rst:78 msgid "" "The :class:`Fraction` class inherits from the abstract base class :class:" @@ -200,6 +232,20 @@ msgstr "" msgid "Here are some examples::" msgstr "" +#: library/fractions.rst:214 +msgid "" +">>> from fractions import Fraction\n" +">>> format(Fraction(1, 7), '.40g')\n" +"'0.1428571428571428571428571428571428571429'\n" +">>> format(Fraction('1234567.855'), '_.2f')\n" +"'1_234_567.86'\n" +">>> f\"{Fraction(355, 113):*>20.6e}\"\n" +"'********3.141593e+00'\n" +">>> old_price, new_price = 499, 672\n" +">>> \"{:.2%} price increase\".format(Fraction(new_price, old_price) - 1)\n" +"'34.67% price increase'" +msgstr "" + #: library/fractions.rst:228 msgid "Module :mod:`numbers`" msgstr "" diff --git a/library/ftplib.po b/library/ftplib.po index 112a6750a..5ce318550 100644 --- a/library/ftplib.po +++ b/library/ftplib.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -39,7 +39,7 @@ msgid "The default encoding is UTF-8, following :rfc:`2640`." msgstr "" #: includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not Emscripten, not WASI." +msgid "Availability" msgstr "" #: includes/wasm-notavail.rst:5 @@ -53,6 +53,28 @@ msgstr "" msgid "Here's a sample session using the :mod:`ftplib` module::" msgstr "" +#: library/ftplib.rst:28 +msgid "" +">>> from ftplib import FTP\n" +">>> ftp = FTP('ftp.us.debian.org') # connect to host, default port\n" +">>> ftp.login() # user anonymous, passwd anonymous@\n" +"'230 Login successful.'\n" +">>> ftp.cwd('debian') # change into \"debian\" directory\n" +"'250 Directory successfully changed.'\n" +">>> ftp.retrlines('LIST') # list directory contents\n" +"-rw-rw-r-- 1 1176 1176 1063 Jun 15 10:18 README\n" +"...\n" +"drwxr-sr-x 5 1176 1176 4096 Dec 19 2000 pool\n" +"drwxr-sr-x 4 1176 1176 4096 Nov 17 2008 project\n" +"drwxr-xr-x 3 1176 1176 4096 Oct 10 2012 tools\n" +"'226 Directory send OK.'\n" +">>> with open('README', 'wb') as fp:\n" +">>> ftp.retrbinary('RETR README', fp.write)\n" +"'226 Transfer complete.'\n" +">>> ftp.quit()\n" +"'221 Goodbye.'" +msgstr "" + #: library/ftplib.rst:51 msgid "Reference" msgstr "" @@ -184,7 +206,8 @@ msgstr "" #: library/ftplib.rst:187 msgid "" -"Raises an auditing event ftplib.connect with arguments self, host, port." +"Raises an :ref:`auditing event ` ``ftplib.connect`` with arguments " +"``self``, ``host``, ``port``." msgstr "" #: library/ftplib.rst:195 @@ -219,7 +242,9 @@ msgid "" msgstr "" #: library/ftplib.rst:238 -msgid "Raises an auditing event ftplib.sendcmd with arguments self, cmd." +msgid "" +"Raises an :ref:`auditing event ` ``ftplib.sendcmd`` with arguments " +"``self``, ``cmd``." msgstr "" #: library/ftplib.rst:234 @@ -477,6 +502,23 @@ msgstr "" msgid "Here's a sample session using the :class:`FTP_TLS` class::" msgstr "" +#: library/ftplib.rst:516 +msgid "" +">>> ftps = FTP_TLS('ftp.pureftpd.org')\n" +">>> ftps.login()\n" +"'230 Anonymous user logged in'\n" +">>> ftps.prot_p()\n" +"'200 Data protection level set to \"private\"'\n" +">>> ftps.nlst()\n" +"['6jack', 'OpenBSD', 'antilink', 'blogbench', 'bsdcam', 'clockspeed', " +"'djbdns-jedi', 'docs', 'eaccelerator-jedi', 'favicon.ico', 'francotone', " +"'fugu', 'ignore', 'libpuzzle', 'metalog', 'minidentd', 'misc', 'mysql-udf-" +"global-user-variables', 'php-jenkins-hash', 'php-skein-hash', 'php-webdav', " +"'phpaudit', 'phpbench', 'pincaster', 'ping', 'posto', 'pub', 'public', " +"'public_keys', 'pure-ftpd', 'qscan', 'qtc', 'sharedance', 'skycache', " +"'sound', 'tmp', 'ucarp']" +msgstr "" + #: library/ftplib.rst:524 msgid "" ":class:`!FTP_TLS` class inherits from :class:`FTP`, defining these " diff --git a/library/functions.po b/library/functions.po index 5176de222..74464a713 100644 --- a/library/functions.po +++ b/library/functions.po @@ -6,7 +6,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: 2023-03-08 10:13-0500\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -426,6 +426,15 @@ msgstr "" "Eğer *iterable* 'ın tüm elementleri doğruysa, ``True`` döndürür. Şuna eş " "değerdir::" +#: library/functions.rst:79 +msgid "" +"def all(iterable):\n" +" for element in iterable:\n" +" if not element:\n" +" return False\n" +" return True" +msgstr "" + #: library/functions.rst:89 msgid "" "When awaited, return the next item from the given :term:`asynchronous " @@ -462,6 +471,15 @@ msgstr "" "Eğer *iterable* 'ın elementlerinden herhangi biri doğru ise ``True`` " "döndürür. Eğer *iterable* boş ise, ``False`` döndürür. Şuna eşittir::" +#: library/functions.rst:107 +msgid "" +"def any(iterable):\n" +" for element in iterable:\n" +" if element:\n" +" return True\n" +" return False" +msgstr "" + #: library/functions.rst:116 msgid "" "As :func:`repr`, return a string containing a printable representation of an " @@ -496,7 +514,7 @@ msgstr "" "Eğer ön ek olarak \"0b\" isteniyorsa veya istenmiyorsa, aşağıdaki gibi iki " "şekilde de kullanabilirsiniz." -#: library/functions.rst:909 library/functions.rst:1246 +#: library/functions.rst:921 library/functions.rst:1260 msgid "See also :func:`format` for more information." msgstr "Ayrıca daha fazla bilgi için :func:`format` 'a bakabilirsiniz." @@ -517,16 +535,17 @@ msgstr "" "sınıfıdır (bkz. :ref:`typesnumeric`). Daha fazla alt sınıfa ayrılamaz. Bunun " "tek örnekleri ``False`` ve ``True`` 'dur (bkz. :ref:`bltin-boolean-values`)." -#: library/functions.rst:774 +#: library/functions.rst:786 #, fuzzy msgid "The parameter is now positional-only." msgstr "*x* artık yalnızca konumsal bir parametredir." #: library/functions.rst:161 +#, fuzzy msgid "" "This function drops you into the debugger at the call site. Specifically, " "it calls :func:`sys.breakpointhook`, passing ``args`` and ``kws`` straight " -"through. By default, ``sys.breakpointhook()`` calls :func:`pdb.set_trace()` " +"through. By default, ``sys.breakpointhook()`` calls :func:`pdb.set_trace` " "expecting no arguments. In this case, it is purely a convenience function " "so you don't have to explicitly import :mod:`pdb` or type as much code to " "enter the debugger. However, :func:`sys.breakpointhook` can be set to some " @@ -561,10 +580,11 @@ msgstr "" #: library/functions.rst:180 #, fuzzy msgid "" -"Raises an auditing event builtins.breakpoint with argument breakpointhook." +"Raises an :ref:`auditing event ` ``builtins.breakpoint`` with " +"argument ``breakpointhook``." msgstr "" -"``breakpointhook`` parametresi ile :ref:`denetleme olayı ` " -"``builtins.breakpoint`` ortaya çıkartır." +"``prompt`` argümanıyla birlikte bir :ref:`denetleme olayı ` " +"``builtins.input`` ortaya çıkartır." #: library/functions.rst:190 msgid "" @@ -716,6 +736,13 @@ msgstr "" "türeyen bir örneğin metodunun örneği aldığı gibi. Bir sınıf metodunu bu " "şekilde tanımlayabilirsiniz::" +#: library/functions.rst:265 +msgid "" +"class C:\n" +" @classmethod\n" +" def f(cls, arg1, arg2): ..." +msgstr "" + #: library/functions.rst:269 msgid "" "The ``@classmethod`` form is a function :term:`decorator` -- see :ref:" @@ -755,16 +782,18 @@ msgstr "" "` 'ları sarmalayabilir." #: library/functions.rst:285 +#, fuzzy msgid "" -"Class methods now inherit the method attributes (``__module__``, " -"``__name__``, ``__qualname__``, ``__doc__`` and ``__annotations__``) and " -"have a new ``__wrapped__`` attribute." +"Class methods now inherit the method attributes (:attr:`~function." +"__module__`, :attr:`~function.__name__`, :attr:`~function.__qualname__`, :" +"attr:`~function.__doc__` and :attr:`~function.__annotations__`) and have a " +"new ``__wrapped__`` attribute." msgstr "" "Sınıf metotları artık (``__module__``, ``__name__``, ``__qualname__``, " "``__doc__`` and ``__annotations__``) metot özelliklerini miras alır ve yeni " "bir ``__wrapped__`` özelliğine sahiplerdir." -#: library/functions.rst:290 +#: library/functions.rst:292 msgid "" "Class methods can no longer wrap other :term:`descriptors ` such " "as :func:`property`." @@ -772,7 +801,7 @@ msgstr "" "Sınıf metotları artık :func:`property` gibi diğer :term:`descriptor` 'ları " "sarmalayamaz." -#: library/functions.rst:297 +#: library/functions.rst:299 msgid "" "Compile the *source* into a code or AST object. Code objects can be " "executed by :func:`exec` or :func:`eval`. *source* can either be a normal " @@ -784,7 +813,7 @@ msgstr "" "normal bir dize, bayt dizesi veya bir AST nesnesi olabilir. AST nesneleriyle " "nasıl çalışılacağını öğrenmek için :mod:`ast` modülüne bkz." -#: library/functions.rst:302 +#: library/functions.rst:304 msgid "" "The *filename* argument should give the file from which the code was read; " "pass some recognizable value if it wasn't read from a file (``''`` " @@ -794,7 +823,7 @@ msgstr "" "okunmuyorsa ayırtedilebilir bir değer verebilirsin (genellikle " "``''`` kullanılır)." -#: library/functions.rst:306 +#: library/functions.rst:308 msgid "" "The *mode* argument specifies what kind of code must be compiled; it can be " "``'exec'`` if *source* consists of a sequence of statements, ``'eval'`` if " @@ -808,7 +837,7 @@ msgstr "" "olabilir (ikinci durumda, \"None\" dışında bir değere sahip ifadeler " "yazdırılacaktır)." -#: library/functions.rst:312 +#: library/functions.rst:314 msgid "" "The optional arguments *flags* and *dont_inherit* control which :ref:" "`compiler options ` should be activated and which :ref:" @@ -833,7 +862,7 @@ msgstr "" "koddaki bayraklar (gelecekteki özellikler ve derleyici seçenekleri) " "yoksayılır." -#: library/functions.rst:323 +#: library/functions.rst:325 msgid "" "Compiler options and future statements are specified by bits which can be " "bitwise ORed together to specify multiple options. The bitfield required to " @@ -850,7 +879,7 @@ msgstr "" "`Derleyici bayrakları ` , :mod:`ast` modülünde ``PyCF_`` " "öneki ile bulunabilir." -#: library/functions.rst:331 +#: library/functions.rst:333 msgid "" "The argument *optimize* specifies the optimization level of the compiler; " "the default value of ``-1`` selects the optimization level of the " @@ -864,7 +893,7 @@ msgstr "" "(optimizasyon yok; ``__debug__`` doğru), ``1`` (iddialar kaldırılır, " "``__debug__`` yanlış) veya ``2`` (Ekstradan doküman dizeleri de kaldırıldı)." -#: library/functions.rst:337 +#: library/functions.rst:339 msgid "" "This function raises :exc:`SyntaxError` if the compiled source is invalid, " "and :exc:`ValueError` if the source contains null bytes." @@ -872,7 +901,7 @@ msgstr "" "Bu fonksiyon derlenmiş kaynak geçerli değil ise :exc:`SyntaxError` , null " "baytlar içeriyorsa :exc:`ValueError` hatalarını ortaya çıkarır." -#: library/functions.rst:340 +#: library/functions.rst:342 msgid "" "If you want to parse Python code into its AST representation, see :func:`ast." "parse`." @@ -880,17 +909,7 @@ msgstr "" "Python kodunu onun AST temsiline ayrıştırmak isterseniz, :func:`ast.parse` " "'a bakınız." -#: library/functions.rst:343 -#, fuzzy -msgid "" -"Raises an auditing event compile with arguments source and filename. This " -"event may also be raised by implicit compilation." -msgstr "" -"``source`` ve ``filename`` argümanlarıyla :ref:`denetleme olayı ` " -"``compile`` ortaya çıkartır. Bu durum, örtük derleme ile de ortaya " -"çıkarılabilir." - -#: library/functions.rst:345 +#: library/functions.rst:347 msgid "" "Raises an :ref:`auditing event ` ``compile`` with arguments " "``source`` and ``filename``. This event may also be raised by implicit " @@ -900,7 +919,7 @@ msgstr "" "``compile`` ortaya çıkartır. Bu durum, örtük derleme ile de ortaya " "çıkarılabilir." -#: library/functions.rst:351 +#: library/functions.rst:353 msgid "" "When compiling a string with multi-line code in ``'single'`` or ``'eval'`` " "mode, input must be terminated by at least one newline character. This is " @@ -912,7 +931,7 @@ msgstr "" "`code` modülündeki tamamlanmış ve tamamlanmamış ifadelerin tespitini " "kolaylaştırmak içindir." -#: library/functions.rst:358 +#: library/functions.rst:360 msgid "" "It is possible to crash the Python interpreter with a sufficiently large/" "complex string when compiling to an AST object due to stack depth " @@ -922,7 +941,7 @@ msgstr "" "yeterince büyük/karmaşık bir dizeyi bir AST nesnesine derlerken Python " "yorumlayıcısını çökertmek mümkündür." -#: library/functions.rst:362 +#: library/functions.rst:364 msgid "" "Allowed use of Windows and Mac newlines. Also, input in ``'exec'`` mode " "does not have to end in a newline anymore. Added the *optimize* parameter." @@ -931,7 +950,7 @@ msgstr "" "böyle ``'exec'`` modunda iken veri girişinin yeni satırda sonlanması " "gerekmiyor. *optimize* parametresi eklendi." -#: library/functions.rst:366 +#: library/functions.rst:368 msgid "" "Previously, :exc:`TypeError` was raised when null bytes were encountered in " "*source*." @@ -939,7 +958,7 @@ msgstr "" "Önceden, *source* , null baytlar içeriyorsa :exc:`TypeError` hatası ortaya " "çıkardı." -#: library/functions.rst:370 +#: library/functions.rst:372 msgid "" "``ast.PyCF_ALLOW_TOP_LEVEL_AWAIT`` can now be passed in flags to enable " "support for top-level ``await``, ``async for``, and ``async with``." @@ -947,18 +966,38 @@ msgstr "" "``ast.PyCF_ALLOW_TOP_LEVEL_AWAIT`` artık üst düze ``await``, ``async for``, " "ve ``async with`` desteğini etkinleştirmek için bayraklarla iletilebilir." -#: library/functions.rst:379 +#: library/functions.rst:381 msgid "" "Convert a single string or number to a complex number, or create a complex " "number from real and imaginary parts." msgstr "" -#: library/functions.rst:719 library/functions.rst:965 +#: library/functions.rst:731 library/functions.rst:977 #, fuzzy msgid "Examples:" msgstr "Örnekler::" -#: library/functions.rst:403 +#: library/functions.rst:386 +msgid "" +">>> complex('+1.23')\n" +"(1.23+0j)\n" +">>> complex('-4.5j')\n" +"-4.5j\n" +">>> complex('-1.23+4.5j')\n" +"(-1.23+4.5j)\n" +">>> complex('\\t( -1.23+4.5J )\\n')\n" +"(-1.23+4.5j)\n" +">>> complex('-Infinity+NaNj')\n" +"(-inf+nanj)\n" +">>> complex(1.23)\n" +"(1.23+0j)\n" +">>> complex(imag=-4.5)\n" +"-4.5j\n" +">>> complex(-1.23, 4.5)\n" +"(-1.23+4.5j)" +msgstr "" + +#: library/functions.rst:405 msgid "" "If the argument is a string, it must contain either a real part (in the same " "format as for :func:`float`) or an imaginary part (in the same format but " @@ -973,7 +1012,7 @@ msgid "" "parentheses and leading and trailing whitespace characters are removed:" msgstr "" -#: library/functions.rst:422 +#: library/functions.rst:424 #, fuzzy msgid "" "If the argument is a number, the constructor serves as a numeric conversion " @@ -987,7 +1026,7 @@ msgstr "" "temsil eder. Eğer ``__complex__()`` tanımlanmadıysa, :meth:`__float__` 'a " "geri döner. ``__float__()`` tanımlanmadıysa, :meth:`__index__` 'e geri döner." -#: library/functions.rst:431 +#: library/functions.rst:433 msgid "" "If two arguments are provided or keyword arguments are used, each argument " "may be any numeric type (including complex). If both arguments are real " @@ -998,21 +1037,21 @@ msgid "" "number, only its real component is used in the above expressions." msgstr "" -#: library/functions.rst:441 +#: library/functions.rst:443 msgid "If all arguments are omitted, returns ``0j``." msgstr "" -#: library/functions.rst:443 +#: library/functions.rst:445 msgid "The complex type is described in :ref:`typesnumeric`." msgstr "Karmaşık tür, :ref:`typesnumeric` kısmında açıklanmıştır." -#: library/functions.rst:771 library/functions.rst:1014 +#: library/functions.rst:783 library/functions.rst:1026 msgid "Grouping digits with underscores as in code literals is allowed." msgstr "" "Rakamların, kod sabitlerinde olduğu gibi alt çizgi ile gruplandırılmasına " "izin verilir." -#: library/functions.rst:448 +#: library/functions.rst:450 #, fuzzy msgid "" "Falls back to :meth:`~object.__index__` if :meth:`~object.__complex__` and :" @@ -1021,7 +1060,7 @@ msgstr "" "Eğer :meth:`__complex__` ve :meth:`__float__` tanımlanmadıysa, :meth:" "`__index__` 'e geri döner." -#: library/functions.rst:455 +#: library/functions.rst:457 msgid "" "This is a relative of :func:`setattr`. The arguments are an object and a " "string. The string must be the name of one of the object's attributes. The " @@ -1036,7 +1075,7 @@ msgstr "" "değerdir. *name* bir Python tanımlayıcısı olmak zorunda değildir (:func:" "`setattr` bkz.)." -#: library/functions.rst:468 +#: library/functions.rst:470 msgid "" "Create a new dictionary. The :class:`dict` object is the dictionary class. " "See :class:`dict` and :ref:`typesmapping` for documentation about this class." @@ -1045,7 +1084,7 @@ msgstr "" "sınıf hakkındaki dokümantasyon için :class:`dict` ve :ref:`typesmapping` 'e " "bakınız." -#: library/functions.rst:471 +#: library/functions.rst:473 msgid "" "For other containers see the built-in :class:`list`, :class:`set`, and :" "class:`tuple` classes, as well as the :mod:`collections` module." @@ -1053,7 +1092,7 @@ msgstr "" "Diğer konteynerler için dahili :class:`list` , :class:`set` , :class:`tuple` " "sınıfları ve :mod:`collections` modülüne bakınız." -#: library/functions.rst:478 +#: library/functions.rst:480 msgid "" "Without arguments, return the list of names in the current local scope. " "With an argument, attempt to return a list of valid attributes for that " @@ -1063,7 +1102,7 @@ msgstr "" "Argüman varsa, o nesne için geçerli özelliklerin bir listesini döndürmeye " "çalışır." -#: library/functions.rst:481 +#: library/functions.rst:483 #, fuzzy msgid "" "If the object has a method named :meth:`~object.__dir__`, this method will " @@ -1078,7 +1117,7 @@ msgstr "" "nesnelerin, :func:`dir` 'in özellikleri bildirme şeklini özelleştirmesine " "izin verir." -#: library/functions.rst:488 +#: library/functions.rst:490 #, fuzzy msgid "" "If the object does not provide :meth:`~object.__dir__`, the function tries " @@ -1092,7 +1131,7 @@ msgstr "" "dener. Sonuç listesinin tamamlanmış olmasına gerek yoktur ve nesnenin özel " "bir :func:`__getattr__` fonksiyonu varsa kusurlu olabilir." -#: library/functions.rst:494 +#: library/functions.rst:496 msgid "" "The default :func:`dir` mechanism behaves differently with different types " "of objects, as it attempts to produce the most relevant, rather than " @@ -1101,7 +1140,7 @@ msgstr "" "Varsayılan :func:`dir` mekanizması, eksiksiz bilgi yerine en alakalı bilgiyi " "üretmeye çalıştığı için farklı nesne türleriyle farklı çalışır:" -#: library/functions.rst:498 +#: library/functions.rst:500 msgid "" "If the object is a module object, the list contains the names of the " "module's attributes." @@ -1109,7 +1148,7 @@ msgstr "" "Eğer nesne bir modül nesnesiyse, liste modülün özelliklerinin isimlerini " "içerir." -#: library/functions.rst:501 +#: library/functions.rst:503 msgid "" "If the object is a type or class object, the list contains the names of its " "attributes, and recursively of the attributes of its bases." @@ -1117,7 +1156,7 @@ msgstr "" "Eğer nesne bir tür veya sınıf nesnesiyse, liste onun özelliklerini ve " "yinelemeli olarak tabanlarının özelliklerini içerir." -#: library/functions.rst:504 +#: library/functions.rst:506 msgid "" "Otherwise, the list contains the object's attributes' names, the names of " "its class's attributes, and recursively of the attributes of its class's " @@ -1126,11 +1165,11 @@ msgstr "" "Aksi takdirde, liste nesnenin özelliklerini, sınıfının özelliklerini ve " "yinelemeli olarak sınıfının temel sınıflarının özelliklerini içerir." -#: library/functions.rst:508 +#: library/functions.rst:510 msgid "The resulting list is sorted alphabetically. For example:" msgstr "Sonuç listesi alfabetik olarak sıralanmıştır. Örnek olarak:" -#: library/functions.rst:528 +#: library/functions.rst:530 msgid "" "Because :func:`dir` is supplied primarily as a convenience for use at an " "interactive prompt, it tries to supply an interesting set of names more than " @@ -1144,7 +1183,7 @@ msgstr "" "arasında değişikliğe uğrayabilir. Örnek olarak, argüman sınıf ise metasınıf " "özellikleri sonuç listesinde yer almaz." -#: library/functions.rst:538 +#: library/functions.rst:540 #, fuzzy msgid "" "Take two (non-complex) numbers as arguments and return a pair of numbers " @@ -1165,7 +1204,7 @@ msgstr "" "yakındır. Eğer ``a % b`` sıfır değilse, *b* ile aynı işarete sahiptir ve ``0 " "<= abs(a % b) < abs(b)``." -#: library/functions.rst:550 +#: library/functions.rst:552 msgid "" "Return an enumerate object. *iterable* must be a sequence, an :term:" "`iterator`, or some other object which supports iteration. The :meth:" @@ -1179,23 +1218,32 @@ msgstr "" "sayıyı (varsayılan olarak 0 olan *start* 'dan) ve *iterable* üzerinde " "yinelemeden elde edilen değerleri içeren bir demet döndürür." -#: library/functions.rst:562 +#: library/functions.rst:564 msgid "Equivalent to::" msgstr "Şuna eşittir::" +#: library/functions.rst:566 +msgid "" +"def enumerate(iterable, start=0):\n" +" n = start\n" +" for elem in iterable:\n" +" yield n, elem\n" +" n += 1" +msgstr "" + #: library/functions.rst:0 msgid "Parameters" msgstr "" -#: library/functions.rst:574 +#: library/functions.rst:576 msgid "A Python expression." msgstr "" -#: library/functions.rst:578 +#: library/functions.rst:580 msgid "The global namespace (default: ``None``)." msgstr "" -#: library/functions.rst:582 +#: library/functions.rst:584 msgid "The local namespace (default: ``None``)." msgstr "" @@ -1203,7 +1251,7 @@ msgstr "" msgid "Returns" msgstr "" -#: library/functions.rst:586 +#: library/functions.rst:588 msgid "The result of the evaluated expression." msgstr "" @@ -1211,11 +1259,17 @@ msgstr "" msgid "raises" msgstr "" -#: library/functions.rst:587 +#: library/functions.rst:589 msgid "Syntax errors are reported as exceptions." msgstr "" -#: library/functions.rst:589 +#: library/functions.rst:644 +msgid "" +"This function executes arbitrary code. Calling it with user-supplied input " +"may lead to security vulnerabilities." +msgstr "" + +#: library/functions.rst:596 msgid "" "The *expression* argument is parsed and evaluated as a Python expression " "(technically speaking, a condition list) using the *globals* and *locals* " @@ -1245,12 +1299,12 @@ msgstr "" "kapsama ortamında :term:`iç içe kapsamlar ` (yerel olmayan) " "erişimi yoktur." -#: library/functions.rst:604 +#: library/functions.rst:611 #, fuzzy msgid "Example:" msgstr "Örnek::" -#: library/functions.rst:610 +#: library/functions.rst:617 msgid "" "This function can also be used to execute arbitrary code objects (such as " "those created by :func:`compile`). In this case, pass a code object instead " @@ -1263,7 +1317,7 @@ msgstr "" "``'exec'`` ile derlendiyse, :func:`eval` 'in döndürdüğü değer ``None`` " "olacaktır." -#: library/functions.rst:615 +#: library/functions.rst:622 msgid "" "Hints: dynamic execution of statements is supported by the :func:`exec` " "function. The :func:`globals` and :func:`locals` functions return the " @@ -1275,7 +1329,7 @@ msgstr "" "mevcut global ve yerel sözlüğü döndürür. :func:`eval` veya :func:`exec` " "tarafından kullanım için dolaşmak yararlı olabilir." -#: library/functions.rst:620 +#: library/functions.rst:627 msgid "" "If the given source is a string, then leading and trailing spaces and tabs " "are stripped." @@ -1283,7 +1337,7 @@ msgstr "" "Eğer verilen kaynak dize ise, baştaki ve sondaki boşluklar ve tab'lar " "çıkarılır." -#: library/functions.rst:623 +#: library/functions.rst:630 msgid "" "See :func:`ast.literal_eval` for a function that can safely evaluate strings " "with expressions containing only literals." @@ -1292,17 +1346,7 @@ msgstr "" "değerlendirebilen bir fonksiyon arıyorsanız, :func:`ast.literal_eval` 'a " "bakınız." -#: library/functions.rst:671 -#, fuzzy -msgid "" -"Raises an auditing event exec with the code object as the argument. Code " -"compilation events may also be raised." -msgstr "" -"Argüman olarak kod nesnesi ile bir :ref:`denetleme olayı ` " -"``exec`` hatası ortaya çıkartır. Kodun derlendiği sırada çıkan hatalar da " -"yükseltilir." - -#: library/functions.rst:673 +#: library/functions.rst:635 library/functions.rst:685 msgid "" "Raises an :ref:`auditing event ` ``exec`` with the code object as " "the argument. Code compilation events may also be raised." @@ -1311,7 +1355,7 @@ msgstr "" "``exec`` hatası ortaya çıkartır. Kodun derlendiği sırada çıkan hatalar da " "yükseltilir." -#: library/functions.rst:635 +#: library/functions.rst:647 msgid "" "This function supports dynamic execution of Python code. *object* must be " "either a string or a code object. If it is a string, the string is parsed " @@ -1333,7 +1377,7 @@ msgstr "" "geçirilen kod kaynağında bile fonksiyonlar dışında kullanılamayacağını " "unutmayınız. Döndürülen değer ``None`` 'dır." -#: library/functions.rst:646 +#: library/functions.rst:658 #, fuzzy msgid "" "In all cases, if the optional parts are omitted, the code is executed in the " @@ -1353,14 +1397,14 @@ msgstr "" "sözlükte bulunduğunu unutmayın. Eğer exec *globals* ve *locals* olarak iki " "ayrı nesne alırsa, kod bir sınıf tanımına gömülmüş gibi çalıştırılacaktır." -#: library/functions.rst:656 +#: library/functions.rst:668 msgid "" "Most users should just pass a *globals* argument and never *locals*. If exec " "gets two separate objects as *globals* and *locals*, the code will be " "executed as if it were embedded in a class definition." msgstr "" -#: library/functions.rst:660 +#: library/functions.rst:672 msgid "" "If the *globals* dictionary does not contain a value for the key " "``__builtins__``, a reference to the dictionary of the built-in module :mod:" @@ -1374,7 +1418,7 @@ msgstr "" "`exec` 'e geçirmeden önce *globals* içine ekleyerek yürütülen kod için hangi " "yerleşiklerin mevcut olduğunu kontrol edebilirsiniz." -#: library/functions.rst:666 +#: library/functions.rst:678 msgid "" "The *closure* argument specifies a closure--a tuple of cellvars. It's only " "valid when the *object* is a code object containing free variables. The " @@ -1386,7 +1430,7 @@ msgstr "" "olduğunda geçerlidir. Demetin uzunluğu, kod nesnesi tarafından başvurulan " "serbest değişkenlerin sayısıyla tam olarak eşleşmelidir." -#: library/functions.rst:678 +#: library/functions.rst:690 msgid "" "The built-in functions :func:`globals` and :func:`locals` return the current " "global and local dictionary, respectively, which may be useful to pass " @@ -1396,7 +1440,7 @@ msgstr "" "yerel sözlüğü sırasıyla döndürür. Bu, :func:`exec` 'e ikinci ve üçüncü " "argüman olarak kullanılmak üzere geçirmek için yararlı olabilir." -#: library/functions.rst:684 +#: library/functions.rst:696 msgid "" "The default *locals* act as described for function :func:`locals` below: " "modifications to the default *locals* dictionary should not be attempted. " @@ -1409,11 +1453,11 @@ msgstr "" "*locals* üzerindeki etkilerini görmeniz gerekiyorsa, açık bir *local* " "sözlüğü geçirin." -#: library/functions.rst:689 +#: library/functions.rst:701 msgid "Added the *closure* parameter." msgstr "*closure* parametresi eklendi." -#: library/functions.rst:695 +#: library/functions.rst:707 msgid "" "Construct an iterator from those elements of *iterable* for which *function* " "is true. *iterable* may be either a sequence, a container which supports " @@ -1425,7 +1469,7 @@ msgstr "" "yineleyici olabilir. *fonksiyon* ``None`` ise, kimlik işlevi varsayılır, " "yani *iterable* öğesinin yanlış olan tüm öğeleri kaldırılır." -#: library/functions.rst:701 +#: library/functions.rst:713 msgid "" "Note that ``filter(function, iterable)`` is equivalent to the generator " "expression ``(item for item in iterable if function(item))`` if function is " @@ -1437,7 +1481,7 @@ msgstr "" "ifadesine ``(item for item in iterable if function(item))`` eşit olduğunu " "unutmayın." -#: library/functions.rst:706 +#: library/functions.rst:718 msgid "" "See :func:`itertools.filterfalse` for the complementary function that " "returns elements of *iterable* for which *function* is false." @@ -1445,12 +1489,26 @@ msgstr "" "*fonksiyon*'un yanlış olduğu *iterable* öğelerini döndüren tamamlayıcı " "fonksiyon için :func:`itertools.filterfalse` konusuna bakın." -#: library/functions.rst:717 +#: library/functions.rst:729 #, fuzzy msgid "Return a floating-point number constructed from a number or a string." msgstr "Bir numara veya string *x* 'ten oluşturulan bir reel sayı döndürür." -#: library/functions.rst:734 +#: library/functions.rst:733 +msgid "" +">>> float('+1.23')\n" +"1.23\n" +">>> float(' -12345\\n')\n" +"-12345.0\n" +">>> float('1e-003')\n" +"0.001\n" +">>> float('+1E6')\n" +"1000000.0\n" +">>> float('-Infinity')\n" +"-inf" +msgstr "" + +#: library/functions.rst:746 #, fuzzy msgid "" "If the argument is a string, it should contain a decimal number, optionally " @@ -1469,7 +1527,7 @@ msgstr "" "baştaki ve sondaki boşluk karakterleri kaldırıldıktan sonra veri girişi " "aşağıdaki dilbilgisindeki ``floatvalue`` üretim kuralına uygun olmalıdır:" -#: library/functions.rst:755 +#: library/functions.rst:767 #, fuzzy msgid "" "Case is not significant, so, for example, \"inf\", \"Inf\", \"INFINITY\", " @@ -1480,7 +1538,7 @@ msgstr "" "örneğin, \"inf\", \"Inf\", \"INFINITY\" ve \"iNfINity\" pozitif sonsuzluk " "için kabul edilebilir yazımlardır." -#: library/functions.rst:758 +#: library/functions.rst:770 #, fuzzy msgid "" "Otherwise, if the argument is an integer or a floating-point number, a " @@ -1492,7 +1550,7 @@ msgstr "" "sayı döndürülür. Eğer argüman Python reel sayı aralığının dışındaysa, :exc:" "`OverflowError` hatası ortaya çıkar." -#: library/functions.rst:763 +#: library/functions.rst:775 #, fuzzy msgid "" "For a general Python object ``x``, ``float(x)`` delegates to ``x." @@ -1503,15 +1561,15 @@ msgstr "" "fonksiyonuna delege eder. Eğer ``__float__()`` tanımlanmamışsa, :meth:" "`__index__` 'e geri döner." -#: library/functions.rst:767 +#: library/functions.rst:779 msgid "If no argument is given, ``0.0`` is returned." msgstr "Argüman verilmediyse, ``0.0`` döndürülür." -#: library/functions.rst:769 +#: library/functions.rst:781 msgid "The float type is described in :ref:`typesnumeric`." msgstr "Float tipi :ref:`typesnumeric` kısmında açıklandı." -#: library/functions.rst:777 +#: library/functions.rst:789 #, fuzzy msgid "" "Falls back to :meth:`~object.__index__` if :meth:`~object.__float__` is not " @@ -1519,7 +1577,7 @@ msgid "" msgstr "" ":meth:`__float__` tanımlanmadıysa, :meth:`__index__` konumuna geri döner." -#: library/functions.rst:787 +#: library/functions.rst:799 msgid "" "Convert a *value* to a \"formatted\" representation, as controlled by " "*format_spec*. The interpretation of *format_spec* will depend on the type " @@ -1532,7 +1590,7 @@ msgstr "" "tiplerde kullanılan :ref:`formatspec` adında bir standart biçimlendirme " "sözdizimi var." -#: library/functions.rst:792 +#: library/functions.rst:804 msgid "" "The default *format_spec* is an empty string which usually gives the same " "effect as calling :func:`str(value) `." @@ -1540,7 +1598,7 @@ msgstr "" "Varsayılan *format_spec*, :func:`str(value) ` fonksiyonunu çağırmakla " "aynı etkiyi gösteren boş bir dizedir." -#: library/functions.rst:795 +#: library/functions.rst:807 #, fuzzy msgid "" "A call to ``format(value, format_spec)`` is translated to ``type(value)." @@ -1556,7 +1614,7 @@ msgstr "" "*format_spec* boş değilse, veya *format_spec* veya döndürülen değer dize " "değilse, :exc:`TypeError` hatası ortaya çıkar." -#: library/functions.rst:802 +#: library/functions.rst:814 msgid "" "``object().__format__(format_spec)`` raises :exc:`TypeError` if " "*format_spec* is not an empty string." @@ -1564,7 +1622,7 @@ msgstr "" "*format_spec* boş bir dize değilse, ``object().__format__(format_spec)``, :" "exc:`TypeError` hatasını ortaya çıkartır." -#: library/functions.rst:811 +#: library/functions.rst:823 msgid "" "Return a new :class:`frozenset` object, optionally with elements taken from " "*iterable*. ``frozenset`` is a built-in class. See :class:`frozenset` and :" @@ -1575,7 +1633,7 @@ msgstr "" "hakkında dokümantasyona ulaşmak için :class:`frozenset` ve :ref:`types-set` " "'e bakınız." -#: library/functions.rst:815 +#: library/functions.rst:827 msgid "" "For other containers see the built-in :class:`set`, :class:`list`, :class:" "`tuple`, and :class:`dict` classes, as well as the :mod:`collections` module." @@ -1584,7 +1642,7 @@ msgstr "" "`tuple`, ve :class:`dict` sınıflarına, ayrıca :mod:`collections` modülüne " "bakabilirsiniz." -#: library/functions.rst:823 +#: library/functions.rst:835 msgid "" "Return the value of the named attribute of *object*. *name* must be a " "string. If the string is the name of one of the object's attributes, the " @@ -1601,7 +1659,7 @@ msgstr "" "ortaya çıkar. *name* bir Python tanımlayıcısı olmak zorunda değildir (:func:" "`setattr` bkz)." -#: library/functions.rst:832 +#: library/functions.rst:844 msgid "" "Since :ref:`private name mangling ` happens at " "compilation time, one must manually mangle a private attribute's (attributes " @@ -1612,7 +1670,7 @@ msgstr "" "gerçekleştiğinden dolayı, :func:`getattr` ile almak için özel bir niteliğin " "(baştaki iki alt çizgili nitelikler) adını manuel olarak değiştirmek gerekir." -#: library/functions.rst:840 +#: library/functions.rst:852 msgid "" "Return the dictionary implementing the current module namespace. For code " "within functions, this is set when the function is defined and remains the " @@ -1622,7 +1680,7 @@ msgstr "" "için, bu fonksiyon tanımlandığında ayarlanır ve fonksiyonun çağrıldığı " "yerden bağımsız olarak aynı kalır." -#: library/functions.rst:847 +#: library/functions.rst:859 msgid "" "The arguments are an object and a string. The result is ``True`` if the " "string is the name of one of the object's attributes, ``False`` if not. " @@ -1634,7 +1692,7 @@ msgstr "" "'i çağırarak uygulanır ve :exc:`AttributeError` hatası oluşup oluşmayacağı " "görülür.)" -#: library/functions.rst:855 +#: library/functions.rst:867 msgid "" "Return the hash value of the object (if it has one). Hash values are " "integers. They are used to quickly compare dictionary keys during a " @@ -1647,7 +1705,7 @@ msgstr "" "değerler aynı karma değere sahiptir (1 ve 1.0 durumunda olduğu gibi farklı " "veri tiplerinde olsalar bile)." -#: library/functions.rst:862 +#: library/functions.rst:874 #, fuzzy msgid "" "For objects with custom :meth:`~object.__hash__` methods, note that :func:" @@ -1657,7 +1715,7 @@ msgstr "" "makinenin bit genişliğine göre döndürdüğü değeri kestiğini unutmayın. " "Detaylar için :meth:`__hash__` 'e bakınız." -#: library/functions.rst:869 +#: library/functions.rst:881 msgid "" "Invoke the built-in help system. (This function is intended for interactive " "use.) If no argument is given, the interactive help system starts on the " @@ -1673,7 +1731,7 @@ msgstr "" "dizeye bakılır ve bir yardım sayfası konsola bastırılır. Eğer argüman başka " "tipte bir nesne ise, nesne üzerinde bir yardım sayfası oluşturulur." -#: library/functions.rst:876 +#: library/functions.rst:888 msgid "" "Note that if a slash(/) appears in the parameter list of a function when " "invoking :func:`help`, it means that the parameters prior to the slash are " @@ -1686,13 +1744,13 @@ msgstr "" "konumsalparametrelerle ilgili SSS girişi ` " "'ne bakınız." -#: library/functions.rst:881 +#: library/functions.rst:893 msgid "" "This function is added to the built-in namespace by the :mod:`site` module." msgstr "" "Bu fonksiyon :mod:`site` modülü tarafından yerleşik ad alanına eklenir." -#: library/functions.rst:883 +#: library/functions.rst:895 msgid "" "Changes to :mod:`pydoc` and :mod:`inspect` mean that the reported signatures " "for callables are now more comprehensive and consistent." @@ -1701,7 +1759,7 @@ msgstr "" "için rapor edilen damgaların artık daha kapsamlı ve tutarlı olduğunu ifade " "eder." -#: library/functions.rst:890 +#: library/functions.rst:902 #, fuzzy msgid "" "Convert an integer number to a lowercase hexadecimal string prefixed with " @@ -1712,7 +1770,7 @@ msgstr "" "dizeye dönüştürür. Eğer *x* Python :class:`int` nesnesi değilse, tam sayı " "döndüren bir :meth:`__index__` metoduna sahip olmalidir. Bazı örnekler:" -#: library/functions.rst:899 +#: library/functions.rst:911 msgid "" "If you want to convert an integer number to an uppercase or lower " "hexadecimal string with prefix or not, you can use either of the following " @@ -1721,7 +1779,7 @@ msgstr "" "Eğer bir tam sayıyı büyük harf-küçük harf, önekli-öneksiz bir onaltılık " "sayıya dönüştürmek istiyorsanız, aşağıdaki yolları kullanabilirsiniz:" -#: library/functions.rst:911 +#: library/functions.rst:923 msgid "" "See also :func:`int` for converting a hexadecimal string to an integer using " "a base of 16." @@ -1729,7 +1787,7 @@ msgstr "" "Ayrıca onaltılık bir dizgiyi 16 tabanını kullanarak bir tam sayıya " "dönüştürmek için :func:`int` 'e bakınız." -#: library/functions.rst:916 +#: library/functions.rst:928 msgid "" "To obtain a hexadecimal string representation for a float, use the :meth:" "`float.hex` method." @@ -1737,7 +1795,7 @@ msgstr "" "Bir gerçel sayıdan onaltılık bir dize gösterimi elde etmek için :meth:`float." "hex` metodunu kullanın." -#: library/functions.rst:922 +#: library/functions.rst:934 msgid "" "Return the \"identity\" of an object. This is an integer which is " "guaranteed to be unique and constant for this object during its lifetime. " @@ -1748,18 +1806,20 @@ msgstr "" "sabit olduğu garanti edilen bir tam sayıdır. Ömürleri örtüşmeyen iki nesne " "aynı :func:`id` değerine sahip olabilir." -#: library/functions.rst:927 +#: library/functions.rst:939 msgid "This is the address of the object in memory." msgstr "Bu, bellekteki nesnenin adresidir." -#: library/functions.rst:929 +#: library/functions.rst:941 #, fuzzy -msgid "Raises an auditing event builtins.id with argument id." +msgid "" +"Raises an :ref:`auditing event ` ``builtins.id`` with argument " +"``id``." msgstr "" -"``id`` argümanıyla beraber bir :ref:`denetleme olayı ` ``builtins." -"id`` ortaya çıkartır." +"``prompt`` argümanıyla birlikte bir :ref:`denetleme olayı ` " +"``builtins.input`` ortaya çıkartır." -#: library/functions.rst:935 +#: library/functions.rst:947 msgid "" "If the *prompt* argument is present, it is written to standard output " "without a trailing newline. The function then reads a line from input, " @@ -1771,7 +1831,15 @@ msgstr "" "bir dizeye çevirip (sondaki yeni satırı çıkartır) döndürür. EOF " "okunduğunda, :exc:`EOFError` istisnası ortaya çıkar. Örnek::" -#: library/functions.rst:945 +#: library/functions.rst:952 +msgid "" +">>> s = input('--> ') \n" +"--> Monty Python's Flying Circus\n" +">>> s \n" +"\"Monty Python's Flying Circus\"" +msgstr "" + +#: library/functions.rst:957 msgid "" "If the :mod:`readline` module was loaded, then :func:`input` will use it to " "provide elaborate line editing and history features." @@ -1779,16 +1847,7 @@ msgstr "" "Eğer :mod:`readline` modülü yüklendiyse, :func:`input` ayrıntılı satır " "düzenleme ve geçmiş özellikleri sağlamak için onu kullanacaktır." -#: library/functions.rst:948 -#, fuzzy -msgid "" -"Raises an auditing event builtins.input with argument prompt before reading " -"input" -msgstr "" -"Girişi okumadan önce, ``prompt`` argümanıyla birlikte bir :ref:`denetleme " -"olayı ` ``builtins.input`` ortaya çıkartır" - -#: library/functions.rst:950 +#: library/functions.rst:962 msgid "" "Raises an :ref:`auditing event ` ``builtins.input`` with argument " "``prompt`` before reading input" @@ -1796,16 +1855,7 @@ msgstr "" "Girişi okumadan önce, ``prompt`` argümanıyla birlikte bir :ref:`denetleme " "olayı ` ``builtins.input`` ortaya çıkartır" -#: library/functions.rst:953 -#, fuzzy -msgid "" -"Raises an auditing event builtins.input/result with the result after " -"successfully reading input." -msgstr "" -"Girişi başarıyla okuduktan sonra sonuçla birlikte bir :ref:`auditing event " -"` ``builtins.input/result`` denetleme olayı ortaya çıkarır." - -#: library/functions.rst:955 +#: library/functions.rst:967 msgid "" "Raises an :ref:`auditing event ` ``builtins.input/result`` with " "the result after successfully reading input." @@ -1813,14 +1863,30 @@ msgstr "" "Girişi başarıyla okuduktan sonra sonuçla birlikte bir :ref:`auditing event " "` ``builtins.input/result`` denetleme olayı ortaya çıkarır." -#: library/functions.rst:962 +#: library/functions.rst:974 #, fuzzy msgid "" "Return an integer object constructed from a number or a string, or return " "``0`` if no arguments are given." msgstr "Bir numara veya string *x* 'ten oluşturulan bir reel sayı döndürür." -#: library/functions.rst:982 +#: library/functions.rst:979 +msgid "" +">>> int(123.45)\n" +"123\n" +">>> int('123')\n" +"123\n" +">>> int(' -12_345\\n')\n" +"-12345\n" +">>> int('FACE', 16)\n" +"64206\n" +">>> int('0xface', 0)\n" +"64206\n" +">>> int('01110011', base=2)\n" +"115" +msgstr "" + +#: library/functions.rst:994 #, fuzzy msgid "" "If the argument defines :meth:`~object.__int__`, ``int(x)`` returns ``x." @@ -1835,7 +1901,7 @@ msgstr "" "__index__()`` 'i döndürür. *x* :meth:`__trunc__` 'ı içeriyorsa, ``x." "__trunc__()`` 'ı döndürür. Gerçel sayılar için, sayı tam sayıya çevrilir." -#: library/functions.rst:988 +#: library/functions.rst:1000 #, fuzzy msgid "" "If the argument is not a number or if *base* is given, then it must be a " @@ -1851,7 +1917,7 @@ msgstr "" "çevrelenebilir ve rakamlar arasına serpiştirilmiş tek alt çizgilere sahip " "olabilir." -#: library/functions.rst:994 +#: library/functions.rst:1006 msgid "" "A base-n integer string contains digits, each representing a value from 0 to " "n-1. The values 0--9 can be represented by any Unicode decimal digit. The " @@ -1876,11 +1942,11 @@ msgstr "" "baştaki sıfırlara da izin vermez: ``int('010', 0)`` yasal değilken, " "``int('010')`` ve ``int('010', 8)`` yasaldır." -#: library/functions.rst:1005 +#: library/functions.rst:1017 msgid "The integer type is described in :ref:`typesnumeric`." msgstr "Tam sayı tipi :ref:`typesnumeric` kısmında açıklandı." -#: library/functions.rst:1007 +#: library/functions.rst:1019 msgid "" "If *base* is not an instance of :class:`int` and the *base* object has a :" "meth:`base.__index__ ` method, that method is called to " @@ -1892,23 +1958,23 @@ msgstr "" "tamsayı elde etmek için çağrılır. Önceki sürümler :meth:`base.__index__ " "` yerine :meth:`base.__int__ ` 'i kullandı." -#: library/functions.rst:1017 +#: library/functions.rst:1029 msgid "The first parameter is now positional-only." msgstr "" -#: library/functions.rst:1020 +#: library/functions.rst:1032 #, fuzzy msgid "" "Falls back to :meth:`~object.__index__` if :meth:`~object.__int__` is not " "defined." msgstr ":meth:`__int__` tanımlı değilse :meth:`__index__` konumuna geri döner." -#: library/functions.rst:1023 +#: library/functions.rst:1035 #, fuzzy msgid "The delegation to :meth:`~object.__trunc__` is deprecated." msgstr ":meth:`__trunc__` yetkisi kullanımdan kaldırıldı." -#: library/functions.rst:1026 +#: library/functions.rst:1038 #, fuzzy msgid "" ":class:`int` string inputs and string representations can be limited to help " @@ -1925,7 +1991,7 @@ msgstr "" "ortaya çıkar. :ref:`tam sayı dönüştürme uzunluk sınırlaması " "` dokümanına bakın." -#: library/functions.rst:1036 +#: library/functions.rst:1048 msgid "" "Return ``True`` if the *object* argument is an instance of the *classinfo* " "argument, or of a (direct, indirect, or :term:`virtual `) of *classinfo*. A class is considered a " @@ -1969,7 +2035,7 @@ msgstr "" "birinin alt sınıfıysa ``True`` döndürülür. Diğer her durumda, :exc:" "`TypeError` hatası ortaya çıkar." -#: library/functions.rst:1068 +#: library/functions.rst:1080 #, fuzzy msgid "" "Return an :term:`iterator` object. The first argument is interpreted very " @@ -1997,11 +2063,11 @@ msgstr "" "döndürülen değer *sentinel* 'e eşitse, :exc:`StopIteration` hatası ortaya " "çıkar, aksi takdirde değer döndürülür." -#: library/functions.rst:1082 +#: library/functions.rst:1094 msgid "See also :ref:`typeiter`." msgstr "Ayrıca :ref:`typeiter` bkz." -#: library/functions.rst:1084 +#: library/functions.rst:1096 msgid "" "One useful application of the second form of :func:`iter` is to build a " "block-reader. For example, reading fixed-width blocks from a binary database " @@ -2011,7 +2077,15 @@ msgstr "" "okuyucu inşaa etmektir. Örnek olarak, dosyanın sonuna ulaşılana kadar ikili " "bir veritabanı dosyasından sabit genişlikte bloklar okunurken::" -#: library/functions.rst:1096 +#: library/functions.rst:1100 +msgid "" +"from functools import partial\n" +"with open('mydata.db', 'rb') as f:\n" +" for block in iter(partial(f.read, 64), b''):\n" +" process_block(block)" +msgstr "" + +#: library/functions.rst:1108 msgid "" "Return the length (the number of items) of an object. The argument may be a " "sequence (such as a string, bytes, tuple, list, or range) or a collection " @@ -2021,7 +2095,7 @@ msgstr "" "(örneğin dize, bytes, demet, liste veya aralık) veya bir koleksiyon (örneğin " "sözlük, küme veya dondurulmuş küme) olabilir." -#: library/functions.rst:1102 +#: library/functions.rst:1114 msgid "" "``len`` raises :exc:`OverflowError` on lengths larger than :data:`sys." "maxsize`, such as :class:`range(2 ** 100) `." @@ -2029,7 +2103,7 @@ msgstr "" "``len``, :class:`range(2 ** 100) ` gibi :data:`sys.maxsize` 'dan daha " "geniş uzunluklar için :exc:`OverflowError` hatası ortaya çıkartır." -#: library/functions.rst:1111 +#: library/functions.rst:1123 msgid "" "Rather than being a function, :class:`list` is actually a mutable sequence " "type, as documented in :ref:`typesseq-list` and :ref:`typesseq`." @@ -2037,7 +2111,7 @@ msgstr "" "Bir fonksiyon görevi görmektense, :ref:`typesseq-list` ve :ref:`typesseq` de " "anlatıldığı gibi :class:`list` bir değiştirebilir dizi çeşididir." -#: library/functions.rst:1117 +#: library/functions.rst:1129 msgid "" "Update and return a dictionary representing the current local symbol table. " "Free variables are returned by :func:`locals` when it is called in function " @@ -2050,7 +2124,7 @@ msgstr "" "Unutmayın ki modül seviyesinde, :func:`locals` ve :func:`globals` aynı " "sözlüklerdir." -#: library/functions.rst:1123 +#: library/functions.rst:1135 msgid "" "The contents of this dictionary should not be modified; changes may not " "affect the values of local and free variables used by the interpreter." @@ -2059,7 +2133,7 @@ msgstr "" "tarafından kullanılan yerel ve serbest değişkenlerin değerlerini " "etkilemeyebilir." -#: library/functions.rst:1128 +#: library/functions.rst:1140 msgid "" "Return an iterator that applies *function* to every item of *iterable*, " "yielding the results. If additional *iterables* arguments are passed, " @@ -2076,7 +2150,7 @@ msgstr "" "girdilerinin zaten demetler halinde verildiği durumlar için, :func:" "`itertools.starmap`\\ 'a bakın." -#: library/functions.rst:1140 +#: library/functions.rst:1152 msgid "" "Return the largest item in an iterable or the largest of two or more " "arguments." @@ -2084,7 +2158,7 @@ msgstr "" "Bir yineleyicinin veya birden fazla parametrenin en büyük elementini " "döndürür." -#: library/functions.rst:1143 +#: library/functions.rst:1155 msgid "" "If one positional argument is provided, it should be an :term:`iterable`. " "The largest item in the iterable is returned. If two or more positional " @@ -2095,7 +2169,7 @@ msgstr "" "pozisyonel parametre sağlandıysa, pozisyonel parametrelerin en büyüğü " "döndürülür." -#: library/functions.rst:1186 +#: library/functions.rst:1198 msgid "" "There are two optional keyword-only arguments. The *key* argument specifies " "a one-argument ordering function like that used for :meth:`list.sort`. The " @@ -2109,7 +2183,7 @@ msgstr "" "döndürülecek nesneyi belirtir. Eğer yineleyici boş ve *varsayılan* " "verilmemiş ise, :exc:`ValueError` hatası ortaya çıkar." -#: library/functions.rst:1154 +#: library/functions.rst:1166 msgid "" "If multiple items are maximal, the function returns the first one " "encountered. This is consistent with other sort-stability preserving tools " @@ -2121,16 +2195,16 @@ msgstr "" "iterable, key=keyfunc)`` gibi sıralama kararlılığı muhafaza eden araçlar ile " "uygundur." -#: library/functions.rst:1197 +#: library/functions.rst:1209 #, fuzzy msgid "Added the *default* keyword-only parameter." msgstr "*varsayılan* yalnızca anahtar kelime parametresi." -#: library/functions.rst:1200 +#: library/functions.rst:1212 msgid "The *key* can be ``None``." msgstr "*key* ``None`` olabilir." -#: library/functions.rst:1170 +#: library/functions.rst:1182 msgid "" "Return a \"memory view\" object created from the given argument. See :ref:" "`typememoryview` for more information." @@ -2138,7 +2212,7 @@ msgstr "" "Verilen argümandan oluşturulan bir \"memory view\" objesi döndürür. Daha " "fazla bilgi için :ref:`typememoryview` bkz." -#: library/functions.rst:1178 +#: library/functions.rst:1190 msgid "" "Return the smallest item in an iterable or the smallest of two or more " "arguments." @@ -2146,7 +2220,7 @@ msgstr "" "Bir yineleyicideki en küçük elementi veya birden fazla argümandan en " "küçüğünü döndürür." -#: library/functions.rst:1181 +#: library/functions.rst:1193 msgid "" "If one positional argument is provided, it should be an :term:`iterable`. " "The smallest item in the iterable is returned. If two or more positional " @@ -2156,7 +2230,7 @@ msgstr "" "Yineleyicinin en küçük elementi döndürülür. Eğer birden fazla argüman " "sağlandıysa, argümanların en küçüğü döndürülür." -#: library/functions.rst:1192 +#: library/functions.rst:1204 msgid "" "If multiple items are minimal, the function returns the first one " "encountered. This is consistent with other sort-stability preserving tools " @@ -2168,7 +2242,7 @@ msgstr "" "key=keyfunc)`` gibi diğer sıralama kararlılığını koruma araçlarıyla tutarlı " "çalışır." -#: library/functions.rst:1207 +#: library/functions.rst:1219 msgid "" "Retrieve the next item from the :term:`iterator` by calling its :meth:" "`~iterator.__next__` method. If *default* is given, it is returned if the " @@ -2178,25 +2252,28 @@ msgstr "" "elementi getirir. Eğer *default* verildiyse ve yineleyici tükenmiş ise " "*default* döndürülür, aksi takdirde :exc:`StopIteration` hatası ortaya çıkar." -#: library/functions.rst:1214 +#: library/functions.rst:1226 +#, fuzzy msgid "" -"Return a new featureless object. :class:`object` is a base for all classes. " -"It has methods that are common to all instances of Python classes. This " -"function does not accept any arguments." +"This is the ultimate base class of all other classes. It has methods that " +"are common to all instances of Python classes. When the constructor is " +"called, it returns a new featureless object. The constructor does not accept " +"any arguments." msgstr "" "Yeni bir niteliksiz nesne döndürür. :class:`object` tüm sınıflar için " "temeldir. Tüm Python sınıflarında bulunan genel metotları içerir. Bu " "fonksiyon hiçbir argüman kabul etmez." -#: library/functions.rst:1220 +#: library/functions.rst:1233 +#, fuzzy msgid "" -":class:`object` does *not* have a :attr:`~object.__dict__`, so you can't " -"assign arbitrary attributes to an instance of the :class:`object` class." +":class:`object` instances do *not* have :attr:`~object.__dict__` attributes, " +"so you can't assign arbitrary attributes to an instance of :class:`object`." msgstr "" ":class:`object`, :attr:`~object.__dict__` özelliğine sahip *değildir*, yani " "bir :class:`object` örneğine keyfi özellikler atayamazsınız." -#: library/functions.rst:1226 +#: library/functions.rst:1240 #, fuzzy msgid "" "Convert an integer number to an octal string prefixed with \"0o\". The " @@ -2208,7 +2285,7 @@ msgstr "" "Python ifadesidir. Eğer *x* bir Python :class:`int` nesnesi değilse, tamsayı " "döndüren bir :meth:`__index__` metoduna sahip olmalıdır. Örnek olarak:" -#: library/functions.rst:1236 +#: library/functions.rst:1250 msgid "" "If you want to convert an integer number to an octal string either with the " "prefix \"0o\" or not, you can use either of the following ways." @@ -2216,7 +2293,7 @@ msgstr "" "Eğer bir tamsayıyı \"0o\" ön ekiyle veya ön eksiz oktal bir dizeye " "dönüştürmek istiyorsanız, aşağıdaki yolları kullanabilirsiniz." -#: library/functions.rst:1253 +#: library/functions.rst:1267 msgid "" "Open *file* and return a corresponding :term:`file object`. If the file " "cannot be opened, an :exc:`OSError` is raised. See :ref:`tut-files` for more " @@ -2226,7 +2303,7 @@ msgstr "" "dosya açılamazsa, :exc:`OSError` hatası ortaya çıkar. Bu fonksiyonun nasıl " "kullanıldığına dair daha fazla örnek için :ref:`tut-files` bkz." -#: library/functions.rst:1257 +#: library/functions.rst:1271 msgid "" "*file* is a :term:`path-like object` giving the pathname (absolute or " "relative to the current working directory) of the file to be opened or an " @@ -2240,7 +2317,8 @@ msgstr "" "açıklayıcısı veirldiyse, *closefd*, ``False`` 'a ayarlanmadığı sürece I/O " "nesnesi kapatıldığında kapatılır." -#: library/functions.rst:1263 +#: library/functions.rst:1277 +#, fuzzy msgid "" "*mode* is an optional string that specifies the mode in which the file is " "opened. It defaults to ``'r'`` which means open for reading in text mode. " @@ -2249,7 +2327,7 @@ msgid "" "(which on *some* Unix systems, means that *all* writes append to the end of " "the file regardless of the current seek position). In text mode, if " "*encoding* is not specified the encoding used is platform-dependent: :func:" -"`locale.getencoding()` is called to get the current locale encoding. (For " +"`locale.getencoding` is called to get the current locale encoding. (For " "reading and writing raw bytes use binary mode and leave *encoding* " "unspecified.) The available modes are:" msgstr "" @@ -2264,71 +2342,71 @@ msgstr "" "(İşlenmemiş baytlar okumak veya yazmak için ikili modu kullanın ve " "*encoding* 'i boş bırakın. Geçerli modlar:" -#: library/functions.rst:1280 +#: library/functions.rst:1294 msgid "Character" msgstr "Karakter" -#: library/functions.rst:1280 +#: library/functions.rst:1294 msgid "Meaning" msgstr "Anlam" -#: library/functions.rst:1282 +#: library/functions.rst:1296 msgid "``'r'``" msgstr "``'r'``" -#: library/functions.rst:1282 +#: library/functions.rst:1296 msgid "open for reading (default)" msgstr "okumaya açık (varsayılan)" -#: library/functions.rst:1283 +#: library/functions.rst:1297 msgid "``'w'``" msgstr "``'w'``" -#: library/functions.rst:1283 +#: library/functions.rst:1297 msgid "open for writing, truncating the file first" msgstr "yazmaya açık, önce dosyayı keser" -#: library/functions.rst:1284 +#: library/functions.rst:1298 msgid "``'x'``" msgstr "``'x'``" -#: library/functions.rst:1284 +#: library/functions.rst:1298 msgid "open for exclusive creation, failing if the file already exists" msgstr "ayrıcalıklı oluşturma için açık, dosya varsa hata verir" -#: library/functions.rst:1285 +#: library/functions.rst:1299 msgid "``'a'``" msgstr "``'a'``" -#: library/functions.rst:1285 +#: library/functions.rst:1299 msgid "open for writing, appending to the end of file if it exists" msgstr "yazmaya açık, eğer dosya bulunuyorsa dosyaya ekleme yapar" -#: library/functions.rst:1286 +#: library/functions.rst:1300 msgid "``'b'``" msgstr "``'b'``" -#: library/functions.rst:1430 +#: library/functions.rst:1444 msgid "binary mode" msgstr "ikili mod" -#: library/functions.rst:1287 +#: library/functions.rst:1301 msgid "``'t'``" msgstr "``'t'``" -#: library/functions.rst:1287 +#: library/functions.rst:1301 msgid "text mode (default)" msgstr "metin modu (varsayılan)" -#: library/functions.rst:1288 +#: library/functions.rst:1302 msgid "``'+'``" msgstr "``'+'``" -#: library/functions.rst:1288 +#: library/functions.rst:1302 msgid "open for updating (reading and writing)" msgstr "güncellemeye açık (okuma ve yazma)" -#: library/functions.rst:1291 +#: library/functions.rst:1305 msgid "" "The default mode is ``'r'`` (open for reading text, a synonym of ``'rt'``). " "Modes ``'w+'`` and ``'w+b'`` open and truncate the file. Modes ``'r+'`` and " @@ -2338,7 +2416,7 @@ msgstr "" "``'w+'`` ve ``'w+b'`` modları dosyayı açar ve temizlerler. ``'r+'`` ve " "``'r+b'`` modları dosyayı temizlemeden açarlar." -#: library/functions.rst:1295 +#: library/functions.rst:1309 msgid "" "As mentioned in the :ref:`io-overview`, Python distinguishes between binary " "and text I/O. Files opened in binary mode (including ``'b'`` in the *mode* " @@ -2356,7 +2434,7 @@ msgstr "" "platforma bağlı bir kodlayıcı veya belirtilen *encoding* 'i kullanarak " "deşifre edilir." -#: library/functions.rst:1305 +#: library/functions.rst:1319 msgid "" "Python doesn't depend on the underlying operating system's notion of text " "files; all the processing is done by Python itself, and is therefore " @@ -2366,7 +2444,7 @@ msgstr "" "değildir. Tüm işlemler Python'un kendisi tarafından yapılır ve bu yüzden de " "platformdan bağımsızdır." -#: library/functions.rst:1309 +#: library/functions.rst:1323 msgid "" "*buffering* is an optional integer used to set the buffering policy. Pass 0 " "to switch buffering off (only allowed in binary mode), 1 to select line " @@ -2391,7 +2469,7 @@ msgstr "" "değişkeni verilmediğinde, varsayılan arabelleğe alma ilkesi şu şekilde " "çalışır:" -#: library/functions.rst:1319 +#: library/functions.rst:1333 #, fuzzy msgid "" "Binary files are buffered in fixed-size chunks; the size of the buffer is " @@ -2404,7 +2482,7 @@ msgstr "" "kullanılarak seçilir ve :attr:`io.DEFAULT_BUFFER_SIZE` değerine düşer. Çoğu " "sistemde, arabellek 4096 veya 8192 bayt uzunluğunda olacaktır." -#: library/functions.rst:1324 +#: library/functions.rst:1338 msgid "" "\"Interactive\" text files (files for which :meth:`~io.IOBase.isatty` " "returns ``True``) use line buffering. Other text files use the policy " @@ -2414,7 +2492,7 @@ msgstr "" "döndürdüğü dosyalar) satır arabelleğe almayı kullanır. Diğer metin dosyaları " "yukarıda ikili dosyalar için açıklanan poliçeyi kullanırlar." -#: library/functions.rst:1328 +#: library/functions.rst:1342 msgid "" "*encoding* is the name of the encoding used to decode or encode the file. " "This should only be used in text mode. The default encoding is platform " @@ -2429,7 +2507,7 @@ msgstr "" "kullanılabilir. Desteklenen kodlayıcıların listesi için :mod:`codecs` " "modülüne bkz." -#: library/functions.rst:1334 +#: library/functions.rst:1348 msgid "" "*errors* is an optional string that specifies how encoding and decoding " "errors are to be handled—this cannot be used in binary mode. A variety of " @@ -2443,7 +2521,7 @@ msgstr "" "`codecs.register_error` ile kaydedilen herhangi bir hata işleyici ismi de " "geçerlidir. Standart isimler bunları içerir:" -#: library/functions.rst:1342 +#: library/functions.rst:1356 msgid "" "``'strict'`` to raise a :exc:`ValueError` exception if there is an encoding " "error. The default value of ``None`` has the same effect." @@ -2452,7 +2530,7 @@ msgstr "" "yükseltmek için kullanılır. Varsayılan değer ``None`` ile aynı etkiyi " "gösterir." -#: library/functions.rst:1346 +#: library/functions.rst:1360 msgid "" "``'ignore'`` ignores errors. Note that ignoring encoding errors can lead to " "data loss." @@ -2460,7 +2538,7 @@ msgstr "" "``'ignore'`` hataları görmezden gelir. Kodlayıcı hatalarını görmezden " "gelmenin veri kaybı ile sonuçlanabileceğini unutmayın." -#: library/functions.rst:1349 +#: library/functions.rst:1363 msgid "" "``'replace'`` causes a replacement marker (such as ``'?'``) to be inserted " "where there is malformed data." @@ -2469,7 +2547,7 @@ msgstr "" "(``'?'`` gibi) 'nin hatalı biçimlendirilmiş verinin yerine geçmesine neden " "olur." -#: library/functions.rst:1352 +#: library/functions.rst:1366 msgid "" "``'surrogateescape'`` will represent any incorrect bytes as low surrogate " "code units ranging from U+DC80 to U+DCFF. These surrogate code units will " @@ -2483,7 +2561,7 @@ msgstr "" "baytlara geri döndürülecektir. Bu dosyaları bilinmeyen bir kodlayıcıyla " "işlerken kullanışlıdır." -#: library/functions.rst:1359 +#: library/functions.rst:1373 #, fuzzy msgid "" "``'xmlcharrefreplace'`` is only supported when writing to a file. Characters " @@ -2494,7 +2572,7 @@ msgstr "" "Kodlayıcı tarafından desteklenmeyen karakterler uygun XML karakter örneği " "ile değiştirilir." -#: library/functions.rst:1363 +#: library/functions.rst:1377 msgid "" "``'backslashreplace'`` replaces malformed data by Python's backslashed " "escape sequences." @@ -2502,7 +2580,7 @@ msgstr "" "``'backslashreplace'`` Python'un ters slash kaçış karakterleri yüzünden " "oluşan hatalı veriyi değiştirir." -#: library/functions.rst:1366 +#: library/functions.rst:1380 msgid "" "``'namereplace'`` (also only supported when writing) replaces unsupported " "characters with ``\\N{...}`` escape sequences." @@ -2510,7 +2588,7 @@ msgstr "" "``'namereplace'`` (sadece yazarken desteklenir) desteklenmeyen karakterleri " "``\\N{...}`` kaçış karakterleriyle değiştirir." -#: library/functions.rst:1374 +#: library/functions.rst:1388 msgid "" "*newline* determines how to parse newline characters from the stream. It can " "be ``None``, ``''``, ``'\\n'``, ``'\\r'``, and ``'\\r\\n'``. It works as " @@ -2520,7 +2598,7 @@ msgstr "" "belirler. ``None``, ``''``, ``'\\n'``, ``'\\r'`` ve ``'\\r\\n'`` olabilir. " "Aşağıdaki gibi çalışır:" -#: library/functions.rst:1378 +#: library/functions.rst:1392 msgid "" "When reading input from the stream, if *newline* is ``None``, universal " "newlines mode is enabled. Lines in the input can end in ``'\\n'``, " @@ -2538,7 +2616,7 @@ msgstr "" "değer verildiyse, girdi satırları sadece verilen dize ile sonlanır ve satır " "sonu çağrıcıya çevrilmeden döndürülür." -#: library/functions.rst:1386 +#: library/functions.rst:1400 msgid "" "When writing output to the stream, if *newline* is ``None``, any ``'\\n'`` " "characters written are translated to the system default line separator, :" @@ -2552,7 +2630,7 @@ msgstr "" "yapılmaz. Eğer *newline* diğer uygun değerlerden biri ise, tüm ``'\\n'`` " "karakterleri verilen dizeye dönüştürülür." -#: library/functions.rst:1392 +#: library/functions.rst:1406 msgid "" "If *closefd* is ``False`` and a file descriptor rather than a filename was " "given, the underlying file descriptor will be kept open when the file is " @@ -2564,7 +2642,7 @@ msgstr "" "Eğer bir dosya adı verildiyse, *closefd* ``True`` olmalıdır (varsayılan); " "aksi takdirde, bir hata ortaya çıkar." -#: library/functions.rst:1397 +#: library/functions.rst:1411 msgid "" "A custom opener can be used by passing a callable as *opener*. The " "underlying file descriptor for the file object is then obtained by calling " @@ -2578,11 +2656,11 @@ msgstr "" "dosya tanımlayıcısı döndürmelidir (*opener* yerine :mod:`os.open` göndermek " "fonksiyonel olarak ``None`` göndermek ile benzer sonuçlanır)." -#: library/functions.rst:1403 +#: library/functions.rst:1417 msgid "The newly created file is :ref:`non-inheritable `." msgstr "Yeni oluşturulan dosya :ref:`non-inheritable ` 'dir." -#: library/functions.rst:1405 +#: library/functions.rst:1419 msgid "" "The following example uses the :ref:`dir_fd ` parameter of the :func:" "`os.open` function to open a file relative to a given directory::" @@ -2590,7 +2668,20 @@ msgstr "" "Aşağıdaki örnek verilen bir dizine ait bir dosyayı açmak için :func:`os." "open` fonksiyonunun :ref:`dir_fd ` parametresini kullanır:" -#: library/functions.rst:1418 +#: library/functions.rst:1422 +msgid "" +">>> import os\n" +">>> dir_fd = os.open('somedir', os.O_RDONLY)\n" +">>> def opener(path, flags):\n" +"... return os.open(path, flags, dir_fd=dir_fd)\n" +"...\n" +">>> with open('spamspam.txt', 'w', opener=opener) as f:\n" +"... print('This will be written to somedir/spamspam.txt', file=f)\n" +"...\n" +">>> os.close(dir_fd) # don't leak a file descriptor" +msgstr "" + +#: library/functions.rst:1432 msgid "" "The type of :term:`file object` returned by the :func:`open` function " "depends on the mode. When :func:`open` is used to open a file in a text " @@ -2616,7 +2707,7 @@ msgstr "" "olduğunda, ham akış, :class:`io.RawIOBase` 'in alt sınıfı, :class:`io." "FileIO` döndürülür." -#: library/functions.rst:1439 +#: library/functions.rst:1453 msgid "" "See also the file handling modules, such as :mod:`fileinput`, :mod:`io` " "(where :func:`open` is declared), :mod:`os`, :mod:`os.path`, :mod:" @@ -2626,14 +2717,16 @@ msgstr "" "`os`, :mod:`os.path`, :mod:`tempfile`, ve :mod:`shutil` gibi dosya işleme " "modüllerine de bkz." -#: library/functions.rst:1443 +#: library/functions.rst:1457 #, fuzzy -msgid "Raises an auditing event open with arguments path, mode, flags." +msgid "" +"Raises an :ref:`auditing event ` ``open`` with arguments ``path``, " +"``mode``, ``flags``." msgstr "" -"``file``, ``mode``, ``flags`` parametreleriyle bir :ref:`audition event " -"` ``open`` ortaya çıkartır." +"``source`` ve ``filename`` argümanlarıyla :ref:`denetleme olayı ` " +"``compile`` ortaya çıkartır." -#: library/functions.rst:1445 +#: library/functions.rst:1459 msgid "" "The ``mode`` and ``flags`` arguments may have been modified or inferred from " "the original call." @@ -2641,21 +2734,21 @@ msgstr "" "``mode`` ve ``flags`` parametreleri orijinal çağrı tarafından modifiye " "edilmiş veya çıkartılmış olabilir." -#: library/functions.rst:1450 +#: library/functions.rst:1464 msgid "The *opener* parameter was added." msgstr "*opener* parametresi eklendi." -#: library/functions.rst:1451 +#: library/functions.rst:1465 msgid "The ``'x'`` mode was added." msgstr "``'x'`` modu eklendi." -#: library/functions.rst:1452 +#: library/functions.rst:1466 msgid ":exc:`IOError` used to be raised, it is now an alias of :exc:`OSError`." msgstr "" "Eskiden :exc:`IOError` hatası ortaya çıkardı, şimdi :exc:`OSError` 'un takma " "adıdır." -#: library/functions.rst:1453 +#: library/functions.rst:1467 msgid "" ":exc:`FileExistsError` is now raised if the file opened in exclusive " "creation mode (``'x'``) already exists." @@ -2663,11 +2756,11 @@ msgstr "" "Artık eğer özel oluşturma modunda (``'x'``) açılmış dosyalar zaten " "bulunuyorsa :exc:`FileExistsError` hatası ortaya çıkar." -#: library/functions.rst:1458 +#: library/functions.rst:1472 msgid "The file is now non-inheritable." msgstr "Dosya artık miras alınamaz." -#: library/functions.rst:1462 +#: library/functions.rst:1476 msgid "" "If the system call is interrupted and the signal handler does not raise an " "exception, the function now retries the system call instead of raising an :" @@ -2677,15 +2770,15 @@ msgstr "" "çıkartmazsa, artık fonksiyon :exc:`InterruptedError` hatası ortaya çıkartmak " "yerine sistem çağrısını yeniden dener (açıklama için :pep:`475` bkz)." -#: library/functions.rst:1465 +#: library/functions.rst:1479 msgid "The ``'namereplace'`` error handler was added." msgstr "``'namereplace'`` hata işleyicisi eklendi." -#: library/functions.rst:1469 +#: library/functions.rst:1483 msgid "Support added to accept objects implementing :class:`os.PathLike`." msgstr ":class:`os.PathLike` uygulayan nesneleri kabul etme desteği eklendi." -#: library/functions.rst:1470 +#: library/functions.rst:1484 msgid "" "On Windows, opening a console buffer may return a subclass of :class:`io." "RawIOBase` other than :class:`io.FileIO`." @@ -2693,11 +2786,11 @@ msgstr "" "Windows'da, bir konsol arabelleğinin açılması :class:`io.FileIO` dışında " "bir :class:`io.RawIOBase` alt sınıfını döndürebilir." -#: library/functions.rst:1473 +#: library/functions.rst:1487 msgid "The ``'U'`` mode has been removed." msgstr "``'U'`` modu kaldırıldı." -#: library/functions.rst:1478 +#: library/functions.rst:1492 msgid "" "Given a string representing one Unicode character, return an integer " "representing the Unicode code point of that character. For example, " @@ -2709,7 +2802,7 @@ msgstr "" "tamsayısını döndürür ve ``ord('€')`` (Euro simgesi) ``8364`` tamsayısını " "döndürür. Bu :func:`chr` 'nin tersidir." -#: library/functions.rst:1486 +#: library/functions.rst:1500 msgid "" "Return *base* to the power *exp*; if *mod* is present, return *base* to the " "power *exp*, modulo *mod* (computed more efficiently than ``pow(base, exp) % " @@ -2721,7 +2814,7 @@ msgstr "" "parametreli formu ``pow(base, exp)``, üs operatörü ``base**exp`` kullanmaya " "eş değerdir." -#: library/functions.rst:1491 +#: library/functions.rst:1505 #, fuzzy msgid "" "The arguments must have numeric types. With mixed operand types, the " @@ -2746,7 +2839,7 @@ msgstr "" "`float` tipinin negatif tabanı için, karmaşık bir sayı çıktı verilir. " "Örneğin, ``pow(-9, 0.5)``, ``3j`` 'ye yakın bir değer döndürür." -#: library/functions.rst:1503 +#: library/functions.rst:1517 msgid "" "For :class:`int` operands *base* and *exp*, if *mod* is present, *mod* must " "also be of integer type and *mod* must be nonzero. If *mod* is present and " @@ -2760,11 +2853,19 @@ msgstr "" "``pow(inv_base,-exp,mod)`` döndürülüri *inv_base, *base* mod *mod* 'un " "tersidir." -#: library/functions.rst:1509 +#: library/functions.rst:1523 msgid "Here's an example of computing an inverse for ``38`` modulo ``97``::" msgstr "Burada ``38`` mod ``97`` 'nin tersini işlemek için bir örnek var::" -#: library/functions.rst:1516 +#: library/functions.rst:1525 +msgid "" +">>> pow(38, -1, mod=97)\n" +"23\n" +">>> 23 * 38 % 97 == 1\n" +"True" +msgstr "" + +#: library/functions.rst:1530 msgid "" "For :class:`int` operands, the three-argument form of ``pow`` now allows the " "second argument to be negative, permitting computation of modular inverses." @@ -2772,14 +2873,14 @@ msgstr "" ":class:`int` işlenenleri için, ``pow`` 'un üç parametreli formu artık ikinci " "parametrenin negatif olmasına, modüler terslerin hesaplanmasına izin verir." -#: library/functions.rst:1521 +#: library/functions.rst:1535 msgid "" "Allow keyword arguments. Formerly, only positional arguments were supported." msgstr "" "Anahtar kelime parametrelerine izin ver, önceden sadece pozisyonel " "parametreler desteklenirdi." -#: library/functions.rst:1528 +#: library/functions.rst:1542 msgid "" "Print *objects* to the text stream *file*, separated by *sep* and followed " "by *end*. *sep*, *end*, *file*, and *flush*, if present, must be given as " @@ -2789,7 +2890,7 @@ msgstr "" "şekilde *objects* 'i yazdırır. *sep*, *end, *file*, ve *flush* sunulursa " "anahtar kelime parametreleri olarak verilmelidir." -#: library/functions.rst:1532 +#: library/functions.rst:1546 msgid "" "All non-keyword arguments are converted to strings like :func:`str` does and " "written to the stream, separated by *sep* and followed by *end*. Both *sep* " @@ -2803,7 +2904,7 @@ msgstr "" "varsayılan değerler kullanılır. Eğer *objects* verilmediyse, :func:`print` " "sadece *end* 'i yazdırır." -#: library/functions.rst:1538 +#: library/functions.rst:1552 msgid "" "The *file* argument must be an object with a ``write(string)`` method; if it " "is not present or ``None``, :data:`sys.stdout` will be used. Since printed " @@ -2815,7 +2916,7 @@ msgstr "" "argümanlar metin dizelerine çevrildiğinden, :func:`print` ikili dosya " "nesneleri ile kullanılamaz. Bunlar için, ``file.write(...)`` 'ı kullanın." -#: library/functions.rst:1543 +#: library/functions.rst:1557 #, fuzzy msgid "" "Output buffering is usually determined by *file*. However, if *flush* is " @@ -2824,15 +2925,15 @@ msgstr "" "Çıktının arabelleğe alınıp alınmadığı genellikle *file* tarafından " "belirlenir, ama *flush* argümanı doğru ise, akış zorla boşaltılır." -#: library/functions.rst:1547 +#: library/functions.rst:1561 msgid "Added the *flush* keyword argument." msgstr "*flush* anahtar kelimesi argümanı eklendi." -#: library/functions.rst:1553 +#: library/functions.rst:1567 msgid "Return a property attribute." msgstr "Bir özellik özelliği döndürür." -#: library/functions.rst:1555 +#: library/functions.rst:1569 msgid "" "*fget* is a function for getting an attribute value. *fset* is a function " "for setting an attribute value. *fdel* is a function for deleting an " @@ -2843,11 +2944,29 @@ msgstr "" "bir özelliğin değerini silmek için kullanılan bir fonksiyondur, ve *doc* " "özellik için bir belge dizisi oluşturur." -#: library/functions.rst:1559 +#: library/functions.rst:1573 msgid "A typical use is to define a managed attribute ``x``::" msgstr "Yönetilen bir ``x`` özelliği tanımlamak için tipik bir yöntem::" -#: library/functions.rst:1576 +#: library/functions.rst:1575 +msgid "" +"class C:\n" +" def __init__(self):\n" +" self._x = None\n" +"\n" +" def getx(self):\n" +" return self._x\n" +"\n" +" def setx(self, value):\n" +" self._x = value\n" +"\n" +" def delx(self):\n" +" del self._x\n" +"\n" +" x = property(getx, setx, delx, \"I'm the 'x' property.\")" +msgstr "" + +#: library/functions.rst:1590 msgid "" "If *c* is an instance of *C*, ``c.x`` will invoke the getter, ``c.x = " "value`` will invoke the setter, and ``del c.x`` the deleter." @@ -2855,7 +2974,7 @@ msgstr "" "Eğer *c*, *C* 'nin bir örneğiyse, ``c.x``, alıcı fonksiyonu çağıracaktır. " "``c.x = value`` ayarlayıcı fonksiyonu, ``del c.x`` ise siliciyi çağıracaktır." -#: library/functions.rst:1579 +#: library/functions.rst:1593 msgid "" "If given, *doc* will be the docstring of the property attribute. Otherwise, " "the property will copy *fget*'s docstring (if it exists). This makes it " @@ -2867,7 +2986,19 @@ msgstr "" "kopyalayacaktır. Bu :func:`property` 'i :term:`decorator` olarak kullanarak " "kolayca salt-okunur özellikler oluşturmayı mümkün kılar::" -#: library/functions.rst:1592 +#: library/functions.rst:1597 +msgid "" +"class Parrot:\n" +" def __init__(self):\n" +" self._voltage = 100000\n" +"\n" +" @property\n" +" def voltage(self):\n" +" \"\"\"Get the current voltage.\"\"\"\n" +" return self._voltage" +msgstr "" + +#: library/functions.rst:1606 #, fuzzy msgid "" "The ``@property`` decorator turns the :meth:`!voltage` method into a " @@ -2878,7 +3009,7 @@ msgstr "" "bir özellik için \"getter\" metoduna dönüştürür ve *voltage* için doküman " "dizisini \"Get the current voltage.\" olarak ayarlar." -#: library/functions.rst:1600 +#: library/functions.rst:1614 #, fuzzy msgid "" "A property object has ``getter``, ``setter``, and ``deleter`` methods usable " @@ -2892,7 +3023,27 @@ msgstr "" "`~property.deleter` metotlarını içerir. Bu en iyi şekilde bir örnekle " "açıklanabilir::" -#: library/functions.rst:1624 +#: library/functions.rst:1619 +msgid "" +"class C:\n" +" def __init__(self):\n" +" self._x = None\n" +"\n" +" @property\n" +" def x(self):\n" +" \"\"\"I'm the 'x' property.\"\"\"\n" +" return self._x\n" +"\n" +" @x.setter\n" +" def x(self, value):\n" +" self._x = value\n" +"\n" +" @x.deleter\n" +" def x(self):\n" +" del self._x" +msgstr "" + +#: library/functions.rst:1638 msgid "" "This code is exactly equivalent to the first example. Be sure to give the " "additional functions the same name as the original property (``x`` in this " @@ -2901,7 +3052,7 @@ msgstr "" "Bu kod birinci örneğin tamamen eş değeridir. Orijinal özellikte olduğu gibi " "ekstra fonksiyonlara aynı ismi verdiğinizden emin olun (bu durumda ``x``)." -#: library/functions.rst:1628 +#: library/functions.rst:1642 msgid "" "The returned property object also has the attributes ``fget``, ``fset``, and " "``fdel`` corresponding to the constructor arguments." @@ -2909,11 +3060,11 @@ msgstr "" "Döndürülen property nesnesi yapıcı metotta verilen ``fget``, ``fset``, ve " "``fdel`` özelliklerine sahiptir." -#: library/functions.rst:1631 +#: library/functions.rst:1645 msgid "The docstrings of property objects are now writeable." msgstr "Property nesnelerinin doküman dizeleri artık yazılabilir." -#: library/functions.rst:1640 +#: library/functions.rst:1654 msgid "" "Rather than being a function, :class:`range` is actually an immutable " "sequence type, as documented in :ref:`typesseq-range` and :ref:`typesseq`." @@ -2922,7 +3073,7 @@ msgstr "" "tipidir. Daha fazla bilgi için :ref:`typesseq-range` ve :ref:`typesseq` 'e " "bakınız." -#: library/functions.rst:1646 +#: library/functions.rst:1660 #, fuzzy msgid "" "Return a string containing a printable representation of an object. For " @@ -2944,11 +3095,22 @@ msgstr "" "ne döndürdüğünü kontrol edebilir. :func:`sys.displayhook` erişilebilir " "değilse, bu fonksiyon :exc:`RuntimeError` değerini yükseltir." -#: library/functions.rst:1657 +#: library/functions.rst:1671 msgid "This class has a custom representation that can be evaluated::" msgstr "" -#: library/functions.rst:1670 +#: library/functions.rst:1673 +msgid "" +"class Person:\n" +" def __init__(self, name, age):\n" +" self.name = name\n" +" self.age = age\n" +"\n" +" def __repr__(self):\n" +" return f\"Person('{self.name}', {self.age})\"" +msgstr "" + +#: library/functions.rst:1684 #, fuzzy msgid "" "Return a reverse :term:`iterator`. *seq* must be an object which has a :" @@ -2961,7 +3123,7 @@ msgstr "" "tam sayı argümanları alan bir :meth:`__getitem__` metodu) destekleyen bir " "nesne olmalıdır." -#: library/functions.rst:1678 +#: library/functions.rst:1692 msgid "" "Return *number* rounded to *ndigits* precision after the decimal point. If " "*ndigits* is omitted or is ``None``, it returns the nearest integer to its " @@ -2971,7 +3133,7 @@ msgstr "" "*ndigits* verilmediyse veya ``None`` ise, *number* 'a en yakın tam sayı " "döndürülür." -#: library/functions.rst:1682 +#: library/functions.rst:1696 msgid "" "For the built-in types supporting :func:`round`, values are rounded to the " "closest multiple of 10 to the power minus *ndigits*; if two multiples are " @@ -2989,7 +3151,7 @@ msgstr "" "*ndigits* verilmediyse veya ``None`` ise döndürülen değer bir tam sayıdır. " "Aksi takdirde, döndürülen değerin tipi *number* 'ınkiyle aynıdır." -#: library/functions.rst:1691 +#: library/functions.rst:1705 msgid "" "For a general Python object ``number``, ``round`` delegates to ``number." "__round__``." @@ -2997,7 +3159,7 @@ msgstr "" "Genel bir Python nesnesi için ``number``, ``round`` ``number.__round__`` 'u " "temsil eder." -#: library/functions.rst:1696 +#: library/functions.rst:1710 msgid "" "The behavior of :func:`round` for floats can be surprising: for example, " "``round(2.675, 2)`` gives ``2.67`` instead of the expected ``2.68``. This is " @@ -3011,7 +3173,7 @@ msgstr "" "gösterilemeyeceğinden bu sonucu alıyoruz. Daha fazla bilgi için :ref:`tut-fp-" "issues` 'e bkz." -#: library/functions.rst:1708 +#: library/functions.rst:1722 msgid "" "Return a new :class:`set` object, optionally with elements taken from " "*iterable*. ``set`` is a built-in class. See :class:`set` and :ref:`types-" @@ -3021,7 +3183,7 @@ msgstr "" "nesnesi döndürür. ``set`` yerleşik bir sınıftır. Bu sınıf hakkında " "dokümantasyon için :class:`set` ve :ref:`types-set` 'e bakınız." -#: library/functions.rst:1712 +#: library/functions.rst:1726 msgid "" "For other containers see the built-in :class:`frozenset`, :class:`list`, :" "class:`tuple`, and :class:`dict` classes, as well as the :mod:`collections` " @@ -3031,7 +3193,7 @@ msgstr "" "`tuple` ve :class:`dict` sınıflarını; aynı zamanda :mod:`collections` " "modülüne bakınız." -#: library/functions.rst:1719 +#: library/functions.rst:1733 msgid "" "This is the counterpart of :func:`getattr`. The arguments are an object, a " "string, and an arbitrary value. The string may name an existing attribute " @@ -3044,7 +3206,7 @@ msgstr "" "Fonksiyon, nesnenin izin vermesi koşuluyla, değeri özelliğe atar. Örneğin " "``setattr(x, 'foobar', 123)`` ve ``x.foobar = 123`` eş değerdir." -#: library/functions.rst:1725 +#: library/functions.rst:1739 msgid "" "*name* need not be a Python identifier as defined in :ref:`identifiers` " "unless the object chooses to enforce that, for example in a custom :meth:" @@ -3058,7 +3220,7 @@ msgstr "" "zorunda değildir. Adı tanımlayıcı olmayan bir özelliğe nokta kullanılarak " "erişilemez, ancak :func:`getattr` vb. aracılığıyla erişilebilir." -#: library/functions.rst:1733 +#: library/functions.rst:1747 msgid "" "Since :ref:`private name mangling ` happens at " "compilation time, one must manually mangle a private attribute's (attributes " @@ -3068,14 +3230,14 @@ msgstr "" "olacağından, :func:`setattr` ile ayarlamak için özel bir niteliğin (iki alt " "çizgi ile başlayan nitelikler) adını manuel olarak değiştirmek gerekir." -#: library/functions.rst:1742 +#: library/functions.rst:1756 msgid "" "Return a :term:`slice` object representing the set of indices specified by " "``range(start, stop, step)``. The *start* and *step* arguments default to " "``None``." msgstr "" -#: library/functions.rst:1750 +#: library/functions.rst:1764 msgid "" "Slice objects have read-only data attributes :attr:`!start`, :attr:`!stop`, " "and :attr:`!step` which merely return the argument values (or their " @@ -3083,30 +3245,30 @@ msgid "" "by NumPy and other third-party packages." msgstr "" -#: library/functions.rst:1755 +#: library/functions.rst:1769 msgid "" "Slice objects are also generated when extended indexing syntax is used. For " "example: ``a[start:stop:step]`` or ``a[start:stop, i]``. See :func:" "`itertools.islice` for an alternate version that returns an :term:`iterator`." msgstr "" -#: library/functions.rst:1760 +#: library/functions.rst:1774 msgid "" "Slice objects are now :term:`hashable` (provided :attr:`~slice.start`, :attr:" "`~slice.stop`, and :attr:`~slice.step` are hashable)." msgstr "" -#: library/functions.rst:1766 +#: library/functions.rst:1780 msgid "Return a new sorted list from the items in *iterable*." msgstr "" "*iterable* 'ın içindeki elementlerden oluşan sıralı bir liste döndürür." -#: library/functions.rst:1768 +#: library/functions.rst:1782 msgid "" "Has two optional arguments which must be specified as keyword arguments." msgstr "İsimle belirtilmesi gereken 2 opsiyonel parametresi vardır." -#: library/functions.rst:1770 +#: library/functions.rst:1784 msgid "" "*key* specifies a function of one argument that is used to extract a " "comparison key from each element in *iterable* (for example, ``key=str." @@ -3116,7 +3278,7 @@ msgstr "" "için kullanılan bir argümanın fonksiyonunu belirtir (örneğin, ``key=str." "lower``). Varsayılan değer ``None`` 'dır (elementleri direkt karşılaştırır)." -#: library/functions.rst:1774 +#: library/functions.rst:1788 msgid "" "*reverse* is a boolean value. If set to ``True``, then the list elements " "are sorted as if each comparison were reversed." @@ -3124,7 +3286,7 @@ msgstr "" "*reverse* bir boolean değerdir. Eğer ``True`` ise, liste elementleri tüm " "karşılaştırmalar tersine çevrilmiş şekilde sıralanır." -#: library/functions.rst:1777 +#: library/functions.rst:1791 msgid "" "Use :func:`functools.cmp_to_key` to convert an old-style *cmp* function to a " "*key* function." @@ -3132,7 +3294,7 @@ msgstr "" "Eski stil *cmp* fonksiyonunu bir *key* fonksiyonuna dönüştürmek için :func:" "`functools.cmp_to_key` 'yi kullanın." -#: library/functions.rst:1780 +#: library/functions.rst:1794 msgid "" "The built-in :func:`sorted` function is guaranteed to be stable. A sort is " "stable if it guarantees not to change the relative order of elements that " @@ -3144,7 +3306,7 @@ msgstr "" "garantiliyorsa stabildir --- bu çoklu geçişlerle sıralama (örneğin önce " "departman, ardından maaş sıralama) için yardımcıdır." -#: library/functions.rst:1785 +#: library/functions.rst:1799 msgid "" "The sort algorithm uses only ``<`` comparisons between items. While " "defining an :meth:`~object.__lt__` method will suffice for sorting, :PEP:`8` " @@ -3164,18 +3326,18 @@ msgstr "" "uygulamak ayrıca yansıtılan :meth:`~object.__gt__` metodunu çağırabilen " "karmaşık tür karşılaştırmaları için karışıklığı da önler." -#: library/functions.rst:1794 +#: library/functions.rst:1808 msgid "" "For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`." msgstr "" "Sıralama örnekleri ve kısa sıralama öğreticisi için :ref:`sortinghowto` 'ya " "bakınız." -#: library/functions.rst:1798 +#: library/functions.rst:1812 msgid "Transform a method into a static method." msgstr "Bir metodu statik metoda dönüştürür." -#: library/functions.rst:1800 +#: library/functions.rst:1814 msgid "" "A static method does not receive an implicit first argument. To declare a " "static method, use this idiom::" @@ -3183,7 +3345,14 @@ msgstr "" "Statik bir metot üstü kapalı şekilde bir ilk argüman almaz. Statik metot " "tanımlamak için bu ifadeyi kullanabilirsiniz::" -#: library/functions.rst:1807 +#: library/functions.rst:1817 +msgid "" +"class C:\n" +" @staticmethod\n" +" def f(arg1, arg2, argN): ..." +msgstr "" + +#: library/functions.rst:1821 msgid "" "The ``@staticmethod`` form is a function :term:`decorator` -- see :ref:" "`function` for details." @@ -3191,7 +3360,7 @@ msgstr "" "``@staticmethod`` ifadesi bir :term:`decorator` fonksiyonudur. -- detaylar " "için :ref:`function` bkz." -#: library/functions.rst:1810 +#: library/functions.rst:1824 #, fuzzy msgid "" "A static method can be called either on the class (such as ``C.f()``) or on " @@ -3203,7 +3372,7 @@ msgstr "" "(``C().f()`` gibi) çağırılabilir. Hatta normal fonksiyonlar gibi (``f()``) " "de çağırılabilirler." -#: library/functions.rst:1815 +#: library/functions.rst:1829 msgid "" "Static methods in Python are similar to those found in Java or C++. Also, " "see :func:`classmethod` for a variant that is useful for creating alternate " @@ -3213,7 +3382,7 @@ msgstr "" "için alternatif bir yapıcı metot oluşturmak isterseniz :func:`classmethod` " "bkz." -#: library/functions.rst:1819 +#: library/functions.rst:1833 msgid "" "Like all decorators, it is also possible to call ``staticmethod`` as a " "regular function and do something with its result. This is needed in some " @@ -3227,29 +3396,40 @@ msgstr "" "dönüşümü engellemek istediğinizde işinize yarayabilir. Böyle durumlar için, " "bu ifadeyi kullanabilirsiniz::" -#: library/functions.rst:1831 +#: library/functions.rst:1839 +msgid "" +"def regular_function():\n" +" ...\n" +"\n" +"class C:\n" +" method = staticmethod(regular_function)" +msgstr "" + +#: library/functions.rst:1845 msgid "For more information on static methods, see :ref:`types`." msgstr "Statik metotlar hakkında daha fazla bilgi için, :ref:`types` bkz." -#: library/functions.rst:1833 +#: library/functions.rst:1847 +#, fuzzy msgid "" -"Static methods now inherit the method attributes (``__module__``, " -"``__name__``, ``__qualname__``, ``__doc__`` and ``__annotations__``), have a " -"new ``__wrapped__`` attribute, and are now callable as regular functions." +"Static methods now inherit the method attributes (:attr:`~function." +"__module__`, :attr:`~function.__name__`, :attr:`~function.__qualname__`, :" +"attr:`~function.__doc__` and :attr:`~function.__annotations__`), have a new " +"``__wrapped__`` attribute, and are now callable as regular functions." msgstr "" "Statik metotlar artık metot özelliklerini (``__module__``, ``__name__``, " "``__qualname__``, ``__doc__`` and ``__annotations__``) miras alır, yeni bir " "``__wrapped__`` özellikleri var ve artık normal fonksiyonlar gibi " "çağırılabilirler." -#: library/functions.rst:1848 +#: library/functions.rst:1863 msgid "" "Return a :class:`str` version of *object*. See :func:`str` for details." msgstr "" "*object* 'in :class:`str` versiyonunu döndürür. Detaylar için :func:`str` " "bkz." -#: library/functions.rst:1850 +#: library/functions.rst:1865 msgid "" "``str`` is the built-in string :term:`class`. For general information about " "strings, see :ref:`textseq`." @@ -3257,7 +3437,7 @@ msgstr "" "``str`` yerleşik dize :term:`class` 'ıdır. Dizeler hakkında genel bilgi " "için, :ref:`textseq` bkz." -#: library/functions.rst:1856 +#: library/functions.rst:1871 msgid "" "Sums *start* and the items of an *iterable* from left to right and returns " "the total. The *iterable*'s items are normally numbers, and the start value " @@ -3267,7 +3447,7 @@ msgstr "" "döndürür. *iterable* 'ın elemanları normal olarak numaralardır ve başlangıç " "değeri bir dize olamaz." -#: library/functions.rst:1860 +#: library/functions.rst:1875 #, fuzzy msgid "" "For some use cases, there are good alternatives to :func:`sum`. The " @@ -3283,17 +3463,17 @@ msgstr "" "nesnelerden oluşan bir diziyi birleştirmek istiyorsanız, :func:`itertools." "chain` fonksiyonunu kullanmayı göz önünde bulundurun." -#: library/functions.rst:1866 +#: library/functions.rst:1881 msgid "The *start* parameter can be specified as a keyword argument." msgstr "*start* parametresi bir anahtar kelime argümanı olarak belirtilebilir." -#: library/functions.rst:1869 +#: library/functions.rst:1884 msgid "" "Summation of floats switched to an algorithm that gives higher accuracy on " "most builds." msgstr "" -#: library/functions.rst:1876 +#: library/functions.rst:1891 msgid "" "Return a proxy object that delegates method calls to a parent or sibling " "class of *type*. This is useful for accessing inherited methods that have " @@ -3303,7 +3483,7 @@ msgstr "" "eden bir proxy objesi döndürür. Bu bir sınıfta üzerine yazılmış kalıtılan " "metotlara erişmek için kullanışlıdır." -#: library/functions.rst:1880 +#: library/functions.rst:1895 msgid "" "The *object_or_type* determines the :term:`method resolution order` to be " "searched. The search starts from the class right after the *type*." @@ -3311,9 +3491,10 @@ msgstr "" "*object_or_type* aranacak :term:`method resolution order` 'nı belirler. " "Arama *type* 'dan sonraki ilk sınıftan başlar." -#: library/functions.rst:1884 +#: library/functions.rst:1899 +#, fuzzy msgid "" -"For example, if :attr:`~class.__mro__` of *object_or_type* is ``D -> B -> C -" +"For example, if :attr:`~type.__mro__` of *object_or_type* is ``D -> B -> C -" "> A -> object`` and the value of *type* is ``B``, then :func:`super` " "searches ``C -> A -> object``." msgstr "" @@ -3321,19 +3502,20 @@ msgstr "" "> B -> C -> A -> object`` ise ve *type* değeri ``B`` ise, :func:`super` ``C -" "> A -> object`` 'i arar." -#: library/functions.rst:1888 +#: library/functions.rst:1903 +#, fuzzy msgid "" -"The :attr:`~class.__mro__` attribute of the *object_or_type* lists the " -"method resolution search order used by both :func:`getattr` and :func:" -"`super`. The attribute is dynamic and can change whenever the inheritance " -"hierarchy is updated." +"The :attr:`~type.__mro__` attribute of the class corresponding to " +"*object_or_type* lists the method resolution search order used by both :func:" +"`getattr` and :func:`super`. The attribute is dynamic and can change " +"whenever the inheritance hierarchy is updated." msgstr "" "*object_or_type* 'ın :attr:`~class.__mro__` özelliği, hem :func:`getattr` " "hem de :func:`super` tarafından kullanılan yöntem çözümleme arama sırasını " "listeler. Özellik dinamiktir ve kalıtım hiyerarşisi her güncellendiğinde " "değişebilir." -#: library/functions.rst:1893 +#: library/functions.rst:1908 msgid "" "If the second argument is omitted, the super object returned is unbound. If " "the second argument is an object, ``isinstance(obj, type)`` must be true. " @@ -3345,7 +3527,7 @@ msgstr "" "zorundadır. Eğer ikinci parametre bir tür ise, ``issubclass(type2, type)`` " "doğru olmak zorundadır (bu sınıf metotları için kullanışlıdır)." -#: library/functions.rst:1898 +#: library/functions.rst:1913 msgid "" "There are two typical use cases for *super*. In a class hierarchy with " "single inheritance, *super* can be used to refer to parent classes without " @@ -3356,7 +3538,7 @@ msgstr "" "hiyerarşisinde *super* üst sınıfları açıkça adlandırmadan onlara başvurmak " "için kullanılabilir. böylece kodu daha sürdürülebilir hale getirir." -#: library/functions.rst:1903 +#: library/functions.rst:1918 msgid "" "The second use case is to support cooperative multiple inheritance in a " "dynamic execution environment. This use case is unique to Python and is not " @@ -3377,12 +3559,20 @@ msgstr "" "sıra sınıf hiyerarşisindeki değişikliklere uyarlanır ve çalışma zamanından " "önce bilinmeyen kardeş sınıfları içerebilir) dikte eder." -#: library/functions.rst:1913 +#: library/functions.rst:1928 msgid "For both use cases, a typical superclass call looks like this::" msgstr "" "İki kullanım durumu için de, tipik bir üst sınıf çağrısı bu şekildedir::" -#: library/functions.rst:1920 +#: library/functions.rst:1930 +msgid "" +"class C(B):\n" +" def method(self, arg):\n" +" super().method(arg) # This does the same thing as:\n" +" # super(C, self).method(arg)" +msgstr "" + +#: library/functions.rst:1935 msgid "" "In addition to method lookups, :func:`super` also works for attribute " "lookups. One possible use case for this is calling :term:`descriptors " @@ -3392,7 +3582,7 @@ msgstr "" "çalışır. Bunun kullanım şekli ebeveyn veya kardeş bir sınıfta :term:" "`tanımlayıcılar ` 'i çağırmaktır." -#: library/functions.rst:1924 +#: library/functions.rst:1939 #, fuzzy msgid "" "Note that :func:`super` is implemented as part of the binding process for " @@ -3409,7 +3599,7 @@ msgstr "" "`super`, ifadeler veya ``super()[name]`` gibi operatörler kullanarak kesin " "aramalar için tanımsızdır." -#: library/functions.rst:1932 +#: library/functions.rst:1947 msgid "" "Also note that, aside from the zero argument form, :func:`super` is not " "limited to use inside methods. The two argument form specifies the " @@ -3424,7 +3614,7 @@ msgstr "" "tanımının içinde çalışır, derleyici tanımlanan sınıfı doğru şekilde almak ve " "sıradan yöntemlere geçerli örnekten erişmek için gerekli detayları doldurur." -#: library/functions.rst:1939 +#: library/functions.rst:1954 msgid "" "For practical suggestions on how to design cooperative classes using :func:" "`super`, see `guide to using super() `_ bkz." -#: library/functions.rst:1949 +#: library/functions.rst:1964 msgid "" "Rather than being a function, :class:`tuple` is actually an immutable " "sequence type, as documented in :ref:`typesseq-tuple` and :ref:`typesseq`." @@ -3442,17 +3632,18 @@ msgstr "" "Bir fonksiyon olmaktansa, :class:`tuple` :ref:`typesseq-tuple` ve :ref:" "`typesseq` 'de gösterildiği gibi düzenlenemez bir dizi türüdür." -#: library/functions.rst:1958 +#: library/functions.rst:1973 +#, fuzzy msgid "" "With one argument, return the type of an *object*. The return value is a " "type object and generally the same object as returned by :attr:`object." -"__class__ `." +"__class__`." msgstr "" "Bir parametre ile, *object* 'in türünü döndürür. Döndürülen değer bir obje " "türüdür ve genellikle :attr:`object.__class__ ` " "tarafından döndürülen obje ile aynıdır." -#: library/functions.rst:1962 +#: library/functions.rst:1977 msgid "" "The :func:`isinstance` built-in function is recommended for testing the type " "of an object, because it takes subclasses into account." @@ -3460,17 +3651,18 @@ msgstr "" ":func:`isinstance` yerleşik fonksiyonu bir objenin türünü test etmek için " "önerilir. Çünkü altsınıfları hesaba katar." -#: library/functions.rst:1966 +#: library/functions.rst:1980 +#, fuzzy msgid "" "With three arguments, return a new type object. This is essentially a " "dynamic form of the :keyword:`class` statement. The *name* string is the " -"class name and becomes the :attr:`~definition.__name__` attribute. The " -"*bases* tuple contains the base classes and becomes the :attr:`~class." -"__bases__` attribute; if empty, :class:`object`, the ultimate base of all " -"classes, is added. The *dict* dictionary contains attribute and method " -"definitions for the class body; it may be copied or wrapped before becoming " -"the :attr:`~object.__dict__` attribute. The following two statements create " -"identical :class:`type` objects:" +"class name and becomes the :attr:`~type.__name__` attribute. The *bases* " +"tuple contains the base classes and becomes the :attr:`~type.__bases__` " +"attribute; if empty, :class:`object`, the ultimate base of all classes, is " +"added. The *dict* dictionary contains attribute and method definitions for " +"the class body; it may be copied or wrapped before becoming the :attr:`~type." +"__dict__` attribute. The following two statements create identical :class:`!" +"type` objects:" msgstr "" "Üç parametre ile, yeni nesne türü döndürür. Bu esasen :keyword:`class` " "ifadesinin dinamik biçimidir. *name* dizesi sınıfın ismidir ve :attr:" @@ -3481,11 +3673,22 @@ msgstr "" "özelliği yerine geçmeden önce kopyalanabilir veya sarılabilir. Aşağıdaki iki " "ifade birebir aynı :class:`type` nesneleri oluşturur:" -#: library/functions.rst:1981 -msgid "See also :ref:`bltin-type-objects`." +#: library/functions.rst:1995 +msgid "See also:" +msgstr "" + +#: library/functions.rst:1997 +msgid "" +":ref:`Documentation on attributes and methods on classes `." +msgstr "" + +#: library/functions.rst:1998 +#, fuzzy +msgid ":ref:`bltin-type-objects`" msgstr ":ref:`bltin-type-objects` 'e de bkz." -#: library/functions.rst:1983 +#: library/functions.rst:2000 msgid "" "Keyword arguments provided to the three argument form are passed to the " "appropriate metaclass machinery (usually :meth:`~object.__init_subclass__`) " @@ -3497,32 +3700,35 @@ msgstr "" "tanımındaki anahtar sözcüklerin (*metaclass* dışında) yapacağı şekilde " "iletilir." -#: library/functions.rst:1988 +#: library/functions.rst:2005 msgid "See also :ref:`class-customization`." msgstr ":ref:`class-customization` 'a da bkz." -#: library/functions.rst:1990 +#: library/functions.rst:2007 +#, fuzzy msgid "" -"Subclasses of :class:`type` which don't override ``type.__new__`` may no " +"Subclasses of :class:`!type` which don't override ``type.__new__`` may no " "longer use the one-argument form to get the type of an object." msgstr "" "``type.__new__`` 'in üzerine yazmayan :class:`type` altsınıfları artık bir " "objenin türünü almak için tek argümanlı formu kullanamaz." -#: library/functions.rst:1997 +#: library/functions.rst:2014 +#, fuzzy msgid "" "Return the :attr:`~object.__dict__` attribute for a module, class, instance, " -"or any other object with a :attr:`~object.__dict__` attribute." +"or any other object with a :attr:`!__dict__` attribute." msgstr "" "Bir modül, sınıf, örnek veya :attr:`~object.__dict__` özelliği bulunan " "herhangi bir obje için, :attr:`~object.__dict__` özelliğini döndürür." -#: library/functions.rst:2000 +#: library/functions.rst:2017 +#, fuzzy msgid "" "Objects such as modules and instances have an updateable :attr:`~object." "__dict__` attribute; however, other objects may have write restrictions on " -"their :attr:`~object.__dict__` attributes (for example, classes use a :class:" -"`types.MappingProxyType` to prevent direct dictionary updates)." +"their :attr:`!__dict__` attributes (for example, classes use a :class:`types." +"MappingProxyType` to prevent direct dictionary updates)." msgstr "" "Modüller ve örnekler gibi nesneler güncellenebilir bir :attr:`~object." "__dict__` özelliğine sahiptir; ama diğer nesnelerin kendilerinin :attr:" @@ -3530,7 +3736,7 @@ msgstr "" "sınıflar doğrudan sözlük güncellemelerini önlemek için :class:`types." "MappingProxyType` sınıfını kullanırlar)." -#: library/functions.rst:2005 +#: library/functions.rst:2022 msgid "" "Without an argument, :func:`vars` acts like :func:`locals`. Note, the " "locals dictionary is only useful for reads since updates to the locals " @@ -3540,7 +3746,7 @@ msgstr "" "ona yapılan güncellemeler görmezden gelindiğinden ötürü, sadece okuma işlemi " "için kullanışlıdır." -#: library/functions.rst:2009 +#: library/functions.rst:2026 msgid "" "A :exc:`TypeError` exception is raised if an object is specified but it " "doesn't have a :attr:`~object.__dict__` attribute (for example, if its class " @@ -3550,7 +3756,7 @@ msgstr "" "(örneğin, :attr:`~object.__slots__` özelliğini tanımlayan bir sınıf ise), :" "exc:`TypeError` hatası ortaya çıkar." -#: library/functions.rst:2015 +#: library/functions.rst:2032 msgid "" "Iterate over several iterables in parallel, producing tuples with an item " "from each one." @@ -3558,11 +3764,21 @@ msgstr "" "Paralel olarak birkaç yinelenebilir nesneyi yineler ve hepsinden bir element " "alarak bir demet üretir." -#: library/functions.rst:2018 +#: library/functions.rst:2035 msgid "Example::" msgstr "Örnek::" -#: library/functions.rst:2027 +#: library/functions.rst:2037 +msgid "" +">>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):\n" +"... print(item)\n" +"...\n" +"(1, 'sugar')\n" +"(2, 'spice')\n" +"(3, 'everything nice')" +msgstr "" + +#: library/functions.rst:2044 msgid "" "More formally: :func:`zip` returns an iterator of tuples, where the *i*-th " "tuple contains the *i*-th element from each of the argument iterables." @@ -3571,7 +3787,7 @@ msgstr "" "parametre yineleyicisinden *i* 'inci elementi içerdiği bir yineleyici " "döndürür." -#: library/functions.rst:2030 +#: library/functions.rst:2047 msgid "" "Another way to think of :func:`zip` is that it turns rows into columns, and " "columns into rows. This is similar to `transposing a matrix `_ 'a benzer." -#: library/functions.rst:2034 +#: library/functions.rst:2051 msgid "" ":func:`zip` is lazy: The elements won't be processed until the iterable is " "iterated on, e.g. by a :keyword:`!for` loop or by wrapping in a :class:" @@ -3591,7 +3807,7 @@ msgstr "" "döngüsü veya :class:`list` tarafından sarılarak yinelenmediği sürece " "elementler işlenmez." -#: library/functions.rst:2038 +#: library/functions.rst:2055 msgid "" "One thing to consider is that the iterables passed to :func:`zip` could have " "different lengths; sometimes by design, and sometimes because of a bug in " @@ -3603,7 +3819,7 @@ msgstr "" "kodda oluşan bir hatadan dolayı farklı uzunluklarda olabilirler. Python " "bununla başa çıkmak için üç farklı yaklaşım sunar:" -#: library/functions.rst:2043 +#: library/functions.rst:2060 msgid "" "By default, :func:`zip` stops when the shortest iterable is exhausted. It " "will ignore the remaining items in the longer iterables, cutting off the " @@ -3613,7 +3829,13 @@ msgstr "" "durur. Daha uzun yinelebilirlerde kalan elementleri görmezden gelecektir ve " "sonucu en kısa yineleyicinin uzunluğuna eşitleyecektir::" -#: library/functions.rst:2050 +#: library/functions.rst:2064 +msgid "" +">>> list(zip(range(3), ['fee', 'fi', 'fo', 'fum']))\n" +"[(0, 'fee'), (1, 'fi'), (2, 'fo')]" +msgstr "" + +#: library/functions.rst:2067 msgid "" ":func:`zip` is often used in cases where the iterables are assumed to be of " "equal length. In such cases, it's recommended to use the ``strict=True`` " @@ -3623,7 +3845,13 @@ msgstr "" "kullanılır. Bu gibi durumlarda, ``strict=True`` opsiyonunu kullanmak " "önerilir. Çıktısı sıradan :func:`zip` ile aynıdır::" -#: library/functions.rst:2057 +#: library/functions.rst:2071 +msgid "" +">>> list(zip(('a', 'b', 'c'), (1, 2, 3), strict=True))\n" +"[('a', 1), ('b', 2), ('c', 3)]" +msgstr "" + +#: library/functions.rst:2074 msgid "" "Unlike the default behavior, it raises a :exc:`ValueError` if one iterable " "is exhausted before the others:" @@ -3631,7 +3859,7 @@ msgstr "" "Varsayılan davranışın aksine, bir yinelenebilir diğerlerinden önce tükenirse " "bir :exc:`ValueError` ortaya çıkar:" -#: library/functions.rst:2075 +#: library/functions.rst:2092 msgid "" "Without the ``strict=True`` argument, any bug that results in iterables of " "different lengths will be silenced, possibly manifesting as a hard-to-find " @@ -3641,7 +3869,7 @@ msgstr "" "sonuçlanan hatalar susturulacaktır. Mümkün olduğunca programın başka bir " "bölümünde bulunması zor bir hata olarak tezahür ediyor." -#: library/functions.rst:2079 +#: library/functions.rst:2096 msgid "" "Shorter iterables can be padded with a constant value to make all the " "iterables have the same length. This is done by :func:`itertools." @@ -3651,7 +3879,7 @@ msgstr "" "uzunlukta olması için sabit bir değerle doldurulabilirler. Bu :func:" "`itertools.zip_longest` tarafından yapılır." -#: library/functions.rst:2083 +#: library/functions.rst:2100 msgid "" "Edge cases: With a single iterable argument, :func:`zip` returns an iterator " "of 1-tuples. With no arguments, it returns an empty iterator." @@ -3660,11 +3888,11 @@ msgstr "" "bir demetin yineleyicisini döndürür. Argüman verilmezse, boş bir yineleyici " "döndürür." -#: library/functions.rst:2086 +#: library/functions.rst:2103 msgid "Tips and tricks:" msgstr "İpucu ve hileler:" -#: library/functions.rst:2088 +#: library/functions.rst:2105 msgid "" "The left-to-right evaluation order of the iterables is guaranteed. This " "makes possible an idiom for clustering a data series into n-length groups " @@ -3679,7 +3907,7 @@ msgstr "" "sayıda çağrı yapmış olur. Bu, girdiyi n-uzunluklu parçalara bölme etkisine " "sahiptir." -#: library/functions.rst:2094 +#: library/functions.rst:2111 msgid "" ":func:`zip` in conjunction with the ``*`` operator can be used to unzip a " "list::" @@ -3687,11 +3915,22 @@ msgstr "" ":func:`zip`, bir listeyi açmak için ``*`` operatörüyle birlikte " "kullanılabilir::" -#: library/functions.rst:2105 +#: library/functions.rst:2114 +msgid "" +">>> x = [1, 2, 3]\n" +">>> y = [4, 5, 6]\n" +">>> list(zip(x, y))\n" +"[(1, 4), (2, 5), (3, 6)]\n" +">>> x2, y2 = zip(*zip(x, y))\n" +">>> x == list(x2) and y == list(y2)\n" +"True" +msgstr "" + +#: library/functions.rst:2122 msgid "Added the ``strict`` argument." msgstr "``strict`` argümanı eklendi." -#: library/functions.rst:2117 +#: library/functions.rst:2134 msgid "" "This is an advanced function that is not needed in everyday Python " "programming, unlike :func:`importlib.import_module`." @@ -3699,7 +3938,7 @@ msgstr "" "Bu :func:`importlib.import_module` 'un aksine günlük Python programlamasında " "genel olarak kullanılmayan gelişmiş bir fonksiyondur." -#: library/functions.rst:2120 +#: library/functions.rst:2137 msgid "" "This function is invoked by the :keyword:`import` statement. It can be " "replaced (by importing the :mod:`builtins` module and assigning to " @@ -3718,7 +3957,7 @@ msgstr "" "neden olmayacağından tavsiye **edilmez**. :func:`__import__` 'un doğrudan " "kullanımı da :func:`importlib.import_module` 'ın lehine tavsiye edilmez." -#: library/functions.rst:2129 +#: library/functions.rst:2146 msgid "" "The function imports the module *name*, potentially using the given " "*globals* and *locals* to determine how to interpret the name in a package " @@ -3734,7 +3973,7 @@ msgstr "" "*locals* argümanını kullanmaya teşebbüs etmez ve *globals* 'i :keyword:" "`import` ifadesinin paket bağlamını belirlemek için kullanır." -#: library/functions.rst:2136 +#: library/functions.rst:2153 msgid "" "*level* specifies whether to use absolute or relative imports. ``0`` (the " "default) means only perform absolute imports. Positive values for *level* " @@ -3748,7 +3987,7 @@ msgstr "" "dizinine göre aranacak üst dizinlerin sayısını gösterir (detaylar için :pep:" "`328` 'e bakınız)." -#: library/functions.rst:2142 +#: library/functions.rst:2159 msgid "" "When the *name* variable is of the form ``package.module``, normally, the " "top-level package (the name up till the first dot) is returned, *not* the " @@ -3759,7 +3998,7 @@ msgstr "" "((ilk noktaya kadar olan isim) döndürülür, *name* isimli modül *değil*. Boş " "olmayan bir *fromlist* argümanı verildiğinde, *name* isimli modül döndürülür." -#: library/functions.rst:2147 +#: library/functions.rst:2164 msgid "" "For example, the statement ``import spam`` results in bytecode resembling " "the following code::" @@ -3767,11 +4006,19 @@ msgstr "" "Örnek olarak, ``import spam`` ifadesi aşağıdaki koda benzeyen bayt koduyla " "sonuçlanır::" -#: library/functions.rst:2152 +#: library/functions.rst:2167 +msgid "spam = __import__('spam', globals(), locals(), [], 0)" +msgstr "" + +#: library/functions.rst:2169 msgid "The statement ``import spam.ham`` results in this call::" msgstr "``import spam.ham`` ifadesi şu çağrıyla sonuçlanır::" -#: library/functions.rst:2156 +#: library/functions.rst:2171 +msgid "spam = __import__('spam.ham', globals(), locals(), [], 0)" +msgstr "" + +#: library/functions.rst:2173 msgid "" "Note how :func:`__import__` returns the toplevel module here because this is " "the object that is bound to a name by the :keyword:`import` statement." @@ -3780,7 +4027,7 @@ msgstr "" "dikkat edin, çünkü bu, :keyword:`import` ifadesiyle bir ada bağlanan " "nesnedir." -#: library/functions.rst:2159 +#: library/functions.rst:2176 msgid "" "On the other hand, the statement ``from spam.ham import eggs, sausage as " "saus`` results in ::" @@ -3788,7 +4035,14 @@ msgstr "" "Diğer yandan, ``from spam.ham import eggs, sausage as saus`` ifadesi şöyle " "sonuçlanır::" -#: library/functions.rst:2166 +#: library/functions.rst:2179 +msgid "" +"_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)\n" +"eggs = _temp.eggs\n" +"saus = _temp.sausage" +msgstr "" + +#: library/functions.rst:2183 msgid "" "Here, the ``spam.ham`` module is returned from :func:`__import__`. From " "this object, the names to import are retrieved and assigned to their " @@ -3797,7 +4051,7 @@ msgstr "" "Burada, ``spam.ham`` modülü :func:`__import__` 'dan döndürülür. Bu objeden, " "içeri aktarılacak isimler alınır ve sırasıyla adlarına atanır." -#: library/functions.rst:2170 +#: library/functions.rst:2187 msgid "" "If you simply want to import a module (potentially within a package) by " "name, use :func:`importlib.import_module`." @@ -3805,7 +4059,7 @@ msgstr "" "Eğer ismiyle bir modülü (potansiyel olarak bir paket içinde) içe aktarmak " "istiyorsanız, :func:`importlib.import_module` 'i kullanın." -#: library/functions.rst:2173 +#: library/functions.rst:2190 msgid "" "Negative values for *level* are no longer supported (which also changes the " "default value to 0)." @@ -3813,7 +4067,7 @@ msgstr "" "*level* için negatif değerler artık desteklenmiyor (bu, varsayılan değeri 0 " "olarak da değiştirir)." -#: library/functions.rst:2177 +#: library/functions.rst:2194 msgid "" "When the command line options :option:`-E` or :option:`-I` are being used, " "the environment variable :envvar:`PYTHONCASEOK` is now ignored." @@ -3821,11 +4075,11 @@ msgstr "" "Komut satırı opsiyonlarından :option:`-E` veya :option:`-I` kullanıldığında, " "ortam değişkeni :envvar:`PYTHONCASEOK` görmezden gelinir." -#: library/functions.rst:2182 +#: library/functions.rst:2199 msgid "Footnotes" msgstr "Dipnotlar" -#: library/functions.rst:2183 +#: library/functions.rst:2200 msgid "" "Note that the parser only accepts the Unix-style end of line convention. If " "you are reading the code from a file, make sure to use newline conversion " @@ -3840,122 +4094,169 @@ msgstr "" msgid "Boolean" msgstr "" -#: library/functions.rst:1956 +#: library/functions.rst:1971 msgid "type" msgstr "" -#: library/functions.rst:631 +#: library/functions.rst:638 #, fuzzy msgid "built-in function" msgstr "Gömülü Fonksiyonlar" -#: library/functions.rst:631 +#: library/functions.rst:638 msgid "exec" msgstr "" -#: library/functions.rst:713 +#: library/functions.rst:725 msgid "NaN" msgstr "" -#: library/functions.rst:713 +#: library/functions.rst:725 msgid "Infinity" msgstr "" -#: library/functions.rst:781 +#: library/functions.rst:793 msgid "__format__" msgstr "" -#: library/functions.rst:1840 +#: library/functions.rst:1855 msgid "string" msgstr "" -#: library/functions.rst:781 +#: library/functions.rst:793 #, fuzzy msgid "format() (built-in function)" msgstr "Gömülü Fonksiyonlar" -#: library/functions.rst:1248 +#: library/functions.rst:1262 msgid "file object" msgstr "" -#: library/functions.rst:1369 +#: library/functions.rst:1383 #, fuzzy msgid "open() built-in function" msgstr "Gömülü Fonksiyonlar" -#: library/functions.rst:1276 +#: library/functions.rst:1290 msgid "file" msgstr "" -#: library/functions.rst:1276 +#: library/functions.rst:1290 msgid "modes" msgstr "" -#: library/functions.rst:1369 +#: library/functions.rst:1383 msgid "universal newlines" msgstr "" -#: library/functions.rst:1430 +#: library/functions.rst:1444 msgid "line-buffered I/O" msgstr "" -#: library/functions.rst:1430 +#: library/functions.rst:1444 msgid "unbuffered I/O" msgstr "" -#: library/functions.rst:1430 +#: library/functions.rst:1444 msgid "buffer size, I/O" msgstr "" -#: library/functions.rst:1430 +#: library/functions.rst:1444 msgid "I/O control" msgstr "" -#: library/functions.rst:1430 +#: library/functions.rst:1444 msgid "buffering" msgstr "" -#: library/functions.rst:1430 +#: library/functions.rst:1444 #, fuzzy msgid "text mode" msgstr "metin modu (varsayılan)" -#: library/functions.rst:2111 +#: library/functions.rst:2128 msgid "module" msgstr "" -#: library/functions.rst:1430 +#: library/functions.rst:1444 msgid "sys" msgstr "" -#: library/functions.rst:1840 +#: library/functions.rst:1855 #, fuzzy msgid "str() (built-in function)" msgstr "Gömülü Fonksiyonlar" -#: library/functions.rst:1956 +#: library/functions.rst:1971 #, fuzzy msgid "object" msgstr ":func:`object`" -#: library/functions.rst:2111 +#: library/functions.rst:2128 msgid "statement" msgstr "" -#: library/functions.rst:2111 +#: library/functions.rst:2128 msgid "import" msgstr "" -#: library/functions.rst:2111 +#: library/functions.rst:2128 msgid "builtins" msgstr "" +#, fuzzy #~ msgid "" -#~ "Raises an :ref:`auditing event ` ``compile`` with arguments " -#~ "``source``, ``filename``." +#~ "Raises an auditing event builtins.breakpoint with argument breakpointhook." +#~ msgstr "" +#~ "``breakpointhook`` parametresi ile :ref:`denetleme olayı ` " +#~ "``builtins.breakpoint`` ortaya çıkartır." + +#, fuzzy +#~ msgid "" +#~ "Raises an auditing event compile with arguments source and filename. This " +#~ "event may also be raised by implicit compilation." #~ msgstr "" #~ "``source`` ve ``filename`` argümanlarıyla :ref:`denetleme olayı " -#~ "` ``compile`` ortaya çıkartır." +#~ "` ``compile`` ortaya çıkartır. Bu durum, örtük derleme ile de " +#~ "ortaya çıkarılabilir." + +#, fuzzy +#~ msgid "" +#~ "Raises an auditing event exec with the code object as the argument. Code " +#~ "compilation events may also be raised." +#~ msgstr "" +#~ "Argüman olarak kod nesnesi ile bir :ref:`denetleme olayı ` " +#~ "``exec`` hatası ortaya çıkartır. Kodun derlendiği sırada çıkan hatalar da " +#~ "yükseltilir." + +#, fuzzy +#~ msgid "Raises an auditing event builtins.id with argument id." +#~ msgstr "" +#~ "``id`` argümanıyla beraber bir :ref:`denetleme olayı ` " +#~ "``builtins.id`` ortaya çıkartır." + +#, fuzzy +#~ msgid "" +#~ "Raises an auditing event builtins.input with argument prompt before " +#~ "reading input" +#~ msgstr "" +#~ "Girişi okumadan önce, ``prompt`` argümanıyla birlikte bir :ref:`denetleme " +#~ "olayı ` ``builtins.input`` ortaya çıkartır" + +#, fuzzy +#~ msgid "" +#~ "Raises an auditing event builtins.input/result with the result after " +#~ "successfully reading input." +#~ msgstr "" +#~ "Girişi başarıyla okuduktan sonra sonuçla birlikte bir :ref:`auditing " +#~ "event ` ``builtins.input/result`` denetleme olayı ortaya " +#~ "çıkarır." + +#, fuzzy +#~ msgid "Raises an auditing event open with arguments path, mode, flags." +#~ msgstr "" +#~ "``file``, ``mode``, ``flags`` parametreleriyle bir :ref:`audition event " +#~ "` ``open`` ortaya çıkartır." #~ msgid "" #~ "Raises an :ref:`auditing event ` ``exec`` with argument " @@ -3964,13 +4265,6 @@ msgstr "" #~ "``code_object`` argümanıyla bir :ref:`denetleme olayı ` " #~ "``exec`` hatası ortaya çıkarır." -#~ msgid "" -#~ "Raises an :ref:`auditing event ` ``builtins.input`` with " -#~ "argument ``prompt``." -#~ msgstr "" -#~ "``prompt`` argümanıyla birlikte bir :ref:`denetleme olayı ` " -#~ "``builtins.input`` ortaya çıkartır." - #~ msgid "" #~ "Raises an :ref:`auditing event ` ``builtins.input/result`` with " #~ "argument ``result``." diff --git a/library/functools.po b/library/functools.po index 8c0151502..5e3c4c623 100644 --- a/library/functools.po +++ b/library/functools.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -47,14 +47,30 @@ msgstr "" msgid "" "Returns the same as ``lru_cache(maxsize=None)``, creating a thin wrapper " "around a dictionary lookup for the function arguments. Because it never " -"needs to evict old values, this is smaller and faster than :func:" -"`lru_cache()` with a size limit." +"needs to evict old values, this is smaller and faster than :func:`lru_cache` " +"with a size limit." msgstr "" #: library/functools.rst:291 msgid "For example::" msgstr "" +#: library/functools.rst:41 +msgid "" +"@cache\n" +"def factorial(n):\n" +" return n * factorial(n-1) if n else 1\n" +"\n" +">>> factorial(10) # no previously cached result, makes 11 recursive " +"calls\n" +"3628800\n" +">>> factorial(5) # just looks up cached value result\n" +"120\n" +">>> factorial(12) # makes two new recursive calls, the other 10 are " +"cached\n" +"479001600" +msgstr "" + #: library/functools.rst:158 msgid "" "The cache is threadsafe so that the wrapped function can be used in multiple " @@ -81,6 +97,18 @@ msgstr "" msgid "Example::" msgstr "" +#: library/functools.rst:72 +msgid "" +"class DataSet:\n" +"\n" +" def __init__(self, sequence_of_numbers):\n" +" self._data = tuple(sequence_of_numbers)\n" +"\n" +" @cached_property\n" +" def stdev(self):\n" +" return statistics.stdev(self._data)" +msgstr "" + #: library/functools.rst:81 msgid "" "The mechanics of :func:`cached_property` are somewhat different from :func:" @@ -167,6 +195,11 @@ msgid "" "one argument and returns another value to be used as the sort key." msgstr "" +#: library/functools.rst:144 +msgid "" +"sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order" +msgstr "" + #: library/functools.rst:146 msgid "" "For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`." @@ -200,6 +233,13 @@ msgid "" "*maxsize* at its default value of 128::" msgstr "" +#: library/functools.rst:178 +msgid "" +"@lru_cache\n" +"def count_vowels(sentence):\n" +" return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')" +msgstr "" + #: library/functools.rst:182 msgid "" "If *maxsize* is set to ``None``, the LRU feature is disabled and the cache " @@ -267,7 +307,7 @@ msgstr "" #: library/functools.rst:220 msgid "" "An `LRU (least recently used) cache `_ works best when the " +"Cache_replacement_policies#Least_Recently_Used_(LRU)>`_ works best when the " "most recent calls are the best predictors of upcoming calls (for example, " "the most popular articles on a news server tend to change each day). The " "cache's size limit assures that the cache does not grow without bound on " @@ -287,6 +327,26 @@ msgstr "" msgid "Example of an LRU cache for static web content::" msgstr "" +#: library/functools.rst:235 +msgid "" +"@lru_cache(maxsize=32)\n" +"def get_pep(num):\n" +" 'Retrieve text of a Python Enhancement Proposal'\n" +" resource = f'https://peps.python.org/pep-{num:04d}'\n" +" try:\n" +" with urllib.request.urlopen(resource) as s:\n" +" return s.read()\n" +" except urllib.error.HTTPError:\n" +" return 'Not Found'\n" +"\n" +">>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:\n" +"... pep = get_pep(n)\n" +"... print(n, len(pep))\n" +"\n" +">>> get_pep.cache_info()\n" +"CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)" +msgstr "" + #: library/functools.rst:252 msgid "" "Example of efficiently computing `Fibonacci numbers `_ technique::" msgstr "" +#: library/functools.rst:258 +msgid "" +"@lru_cache(maxsize=None)\n" +"def fib(n):\n" +" if n < 2:\n" +" return n\n" +" return fib(n-1) + fib(n-2)\n" +"\n" +">>> [fib(n) for n in range(16)]\n" +"[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]\n" +"\n" +">>> fib.cache_info()\n" +"CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)" +msgstr "" + #: library/functools.rst:272 msgid "Added the *typed* option." msgstr "" @@ -320,6 +395,25 @@ msgid "" "method." msgstr "" +#: library/functools.rst:293 +msgid "" +"@total_ordering\n" +"class Student:\n" +" def _is_valid_operand(self, other):\n" +" return (hasattr(other, \"lastname\") and\n" +" hasattr(other, \"firstname\"))\n" +" def __eq__(self, other):\n" +" if not self._is_valid_operand(other):\n" +" return NotImplemented\n" +" return ((self.lastname.lower(), self.firstname.lower()) ==\n" +" (other.lastname.lower(), other.firstname.lower()))\n" +" def __lt__(self, other):\n" +" if not self._is_valid_operand(other):\n" +" return NotImplemented\n" +" return ((self.lastname.lower(), self.firstname.lower()) <\n" +" (other.lastname.lower(), other.firstname.lower()))" +msgstr "" + #: library/functools.rst:311 msgid "" "While this decorator makes it easy to create well behaved totally ordered " @@ -352,6 +446,18 @@ msgid "" "extend and override *keywords*. Roughly equivalent to::" msgstr "" +#: library/functools.rst:340 +msgid "" +"def partial(func, /, *args, **keywords):\n" +" def newfunc(*fargs, **fkeywords):\n" +" newkeywords = {**keywords, **fkeywords}\n" +" return func(*args, *fargs, **newkeywords)\n" +" newfunc.func = func\n" +" newfunc.args = args\n" +" newfunc.keywords = keywords\n" +" return newfunc" +msgstr "" + #: library/functools.rst:349 msgid "" "The :func:`partial` is used for partial function application which " @@ -392,6 +498,27 @@ msgid "" "`partialmethod` constructor." msgstr "" +#: library/functools.rst:385 +msgid "" +">>> class Cell:\n" +"... def __init__(self):\n" +"... self._alive = False\n" +"... @property\n" +"... def alive(self):\n" +"... return self._alive\n" +"... def set_state(self, state):\n" +"... self._alive = bool(state)\n" +"... set_alive = partialmethod(set_state, True)\n" +"... set_dead = partialmethod(set_state, False)\n" +"...\n" +">>> c = Cell()\n" +">>> c.alive\n" +"False\n" +">>> c.set_alive()\n" +">>> c.alive\n" +"True" +msgstr "" + #: library/functools.rst:408 msgid "" "Apply *function* of two arguments cumulatively to the items of *iterable*, " @@ -409,6 +536,19 @@ msgstr "" msgid "Roughly equivalent to::" msgstr "" +#: library/functools.rst:419 +msgid "" +"def reduce(function, iterable, initializer=None):\n" +" it = iter(iterable)\n" +" if initializer is None:\n" +" value = next(it)\n" +" else:\n" +" value = initializer\n" +" for element in it:\n" +" value = function(value, element)\n" +" return value" +msgstr "" + #: library/functools.rst:429 msgid "" "See :func:`itertools.accumulate` for an iterator that yields all " @@ -428,6 +568,16 @@ msgid "" "dispatch happens on the type of the first argument::" msgstr "" +#: library/functools.rst:441 +msgid "" +">>> from functools import singledispatch\n" +">>> @singledispatch\n" +"... def fun(arg, verbose=False):\n" +"... if verbose:\n" +"... print(\"Let me just say,\", end=\" \")\n" +"... print(arg)" +msgstr "" + #: library/functools.rst:448 msgid "" "To add overloaded implementations to the function, use the :func:`register` " @@ -436,36 +586,147 @@ msgid "" "first argument automatically::" msgstr "" +#: library/functools.rst:453 +msgid "" +">>> @fun.register\n" +"... def _(arg: int, verbose=False):\n" +"... if verbose:\n" +"... print(\"Strength in numbers, eh?\", end=\" \")\n" +"... print(arg)\n" +"...\n" +">>> @fun.register\n" +"... def _(arg: list, verbose=False):\n" +"... if verbose:\n" +"... print(\"Enumerate this:\")\n" +"... for i, elem in enumerate(arg):\n" +"... print(i, elem)" +msgstr "" + #: library/functools.rst:466 msgid ":data:`types.UnionType` and :data:`typing.Union` can also be used::" msgstr "" +#: library/functools.rst:468 +msgid "" +">>> @fun.register\n" +"... def _(arg: int | float, verbose=False):\n" +"... if verbose:\n" +"... print(\"Strength in numbers, eh?\", end=\" \")\n" +"... print(arg)\n" +"...\n" +">>> from typing import Union\n" +">>> @fun.register\n" +"... def _(arg: Union[list, set], verbose=False):\n" +"... if verbose:\n" +"... print(\"Enumerate this:\")\n" +"... for i, elem in enumerate(arg):\n" +"... print(i, elem)\n" +"..." +msgstr "" + #: library/functools.rst:483 msgid "" "For code which doesn't use type annotations, the appropriate type argument " "can be passed explicitly to the decorator itself::" msgstr "" -#: library/functools.rst:494 +#: library/functools.rst:486 +msgid "" +">>> @fun.register(complex)\n" +"... def _(arg, verbose=False):\n" +"... if verbose:\n" +"... print(\"Better than complicated.\", end=\" \")\n" +"... print(arg.real, arg.imag)\n" +"..." +msgstr "" + +#: library/functools.rst:493 +msgid "" +"For code that dispatches on a collections type (e.g., ``list``), but wants " +"to typehint the items of the collection (e.g., ``list[int]``), the dispatch " +"type should be passed explicitly to the decorator itself with the typehint " +"going into the function definition::" +msgstr "" + +#: library/functools.rst:498 +msgid "" +">>> @fun.register(list)\n" +"... def _(arg: list[int], verbose=False):\n" +"... if verbose:\n" +"... print(\"Enumerate this:\")\n" +"... for i, elem in enumerate(arg):\n" +"... print(i, elem)" +msgstr "" + +#: library/functools.rst:507 +msgid "" +"At runtime the function will dispatch on an instance of a list regardless of " +"the type contained within the list i.e. ``[1,2,3]`` will be dispatched the " +"same as ``[\"foo\", \"bar\", \"baz\"]``. The annotation provided in this " +"example is for static type checkers only and has no runtime impact." +msgstr "" + +#: library/functools.rst:513 msgid "" "To enable registering :term:`lambdas` and pre-existing functions, " "the :func:`register` attribute can also be used in a functional form::" msgstr "" -#: library/functools.rst:502 +#: library/functools.rst:516 +msgid "" +">>> def nothing(arg, verbose=False):\n" +"... print(\"Nothing.\")\n" +"...\n" +">>> fun.register(type(None), nothing)" +msgstr "" + +#: library/functools.rst:521 msgid "" "The :func:`register` attribute returns the undecorated function. This " "enables decorator stacking, :mod:`pickling`, and the creation of " "unit tests for each variant independently::" msgstr "" -#: library/functools.rst:516 +#: library/functools.rst:525 +msgid "" +">>> @fun.register(float)\n" +"... @fun.register(Decimal)\n" +"... def fun_num(arg, verbose=False):\n" +"... if verbose:\n" +"... print(\"Half of your number:\", end=\" \")\n" +"... print(arg / 2)\n" +"...\n" +">>> fun_num is fun\n" +"False" +msgstr "" + +#: library/functools.rst:535 msgid "" "When called, the generic function dispatches on the type of the first " "argument::" msgstr "" -#: library/functools.rst:536 +#: library/functools.rst:538 +msgid "" +">>> fun(\"Hello, world.\")\n" +"Hello, world.\n" +">>> fun(\"test.\", verbose=True)\n" +"Let me just say, test.\n" +">>> fun(42, verbose=True)\n" +"Strength in numbers, eh? 42\n" +">>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True)\n" +"Enumerate this:\n" +"0 spam\n" +"1 spam\n" +"2 eggs\n" +"3 spam\n" +">>> fun(None)\n" +"Nothing.\n" +">>> fun(1.23)\n" +"0.615" +msgstr "" + +#: library/functools.rst:555 msgid "" "Where there is no registered implementation for a specific type, its method " "resolution order is used to find a more generic implementation. The original " @@ -474,42 +735,76 @@ msgid "" "found." msgstr "" -#: library/functools.rst:542 +#: library/functools.rst:561 msgid "" "If an implementation is registered to an :term:`abstract base class`, " "virtual subclasses of the base class will be dispatched to that " "implementation::" msgstr "" -#: library/functools.rst:557 +#: library/functools.rst:565 +msgid "" +">>> from collections.abc import Mapping\n" +">>> @fun.register\n" +"... def _(arg: Mapping, verbose=False):\n" +"... if verbose:\n" +"... print(\"Keys & Values\")\n" +"... for key, value in arg.items():\n" +"... print(key, \"=>\", value)\n" +"...\n" +">>> fun({\"a\": \"b\"})\n" +"a => b" +msgstr "" + +#: library/functools.rst:576 msgid "" "To check which implementation the generic function will choose for a given " "type, use the ``dispatch()`` attribute::" msgstr "" -#: library/functools.rst:565 +#: library/functools.rst:579 +msgid "" +">>> fun.dispatch(float)\n" +"\n" +">>> fun.dispatch(dict) # note: default implementation\n" +"" +msgstr "" + +#: library/functools.rst:584 msgid "" "To access all registered implementations, use the read-only ``registry`` " "attribute::" msgstr "" -#: library/functools.rst:579 +#: library/functools.rst:587 +msgid "" +">>> fun.registry.keys()\n" +"dict_keys([, , ,\n" +" , ,\n" +" ])\n" +">>> fun.registry[float]\n" +"\n" +">>> fun.registry[object]\n" +"" +msgstr "" + +#: library/functools.rst:598 msgid "The :func:`register` attribute now supports using type annotations." msgstr "" -#: library/functools.rst:582 +#: library/functools.rst:601 msgid "" "The :func:`register` attribute now supports :data:`types.UnionType` and :" "data:`typing.Union` as type annotations." msgstr "" -#: library/functools.rst:589 +#: library/functools.rst:608 msgid "" "Transform a method into a :term:`single-dispatch ` :term:" "`generic function`." msgstr "" -#: library/functools.rst:592 +#: library/functools.rst:611 msgid "" "To define a generic method, decorate it with the ``@singledispatchmethod`` " "decorator. When defining a function using ``@singledispatchmethod``, note " @@ -517,7 +812,23 @@ msgid "" "argument::" msgstr "" -#: library/functools.rst:610 +#: library/functools.rst:616 +msgid "" +"class Negator:\n" +" @singledispatchmethod\n" +" def neg(self, arg):\n" +" raise NotImplementedError(\"Cannot negate a\")\n" +"\n" +" @neg.register\n" +" def _(self, arg: int):\n" +" return -arg\n" +"\n" +" @neg.register\n" +" def _(self, arg: bool):\n" +" return not arg" +msgstr "" + +#: library/functools.rst:629 msgid "" "``@singledispatchmethod`` supports nesting with other decorators such as :" "func:`@classmethod`. Note that to allow for ``dispatcher." @@ -526,14 +837,33 @@ msgid "" "rather than an instance of the class::" msgstr "" -#: library/functools.rst:632 +#: library/functools.rst:635 +msgid "" +"class Negator:\n" +" @singledispatchmethod\n" +" @classmethod\n" +" def neg(cls, arg):\n" +" raise NotImplementedError(\"Cannot negate a\")\n" +"\n" +" @neg.register\n" +" @classmethod\n" +" def _(cls, arg: int):\n" +" return -arg\n" +"\n" +" @neg.register\n" +" @classmethod\n" +" def _(cls, arg: bool):\n" +" return not arg" +msgstr "" + +#: library/functools.rst:651 msgid "" "The same pattern can be used for other similar decorators: :func:" "`@staticmethod`, :func:`@abstractmethod`, " "and others." msgstr "" -#: library/functools.rst:641 +#: library/functools.rst:660 msgid "" "Update a *wrapper* function to look like the *wrapped* function. The " "optional arguments are tuples to specify which attributes of the original " @@ -541,13 +871,15 @@ msgid "" "function and which attributes of the wrapper function are updated with the " "corresponding attributes from the original function. The default values for " "these arguments are the module level constants ``WRAPPER_ASSIGNMENTS`` " -"(which assigns to the wrapper function's ``__module__``, ``__name__``, " -"``__qualname__``, ``__annotations__``, ``__type_params__``, and ``__doc__``, " -"the documentation string) and ``WRAPPER_UPDATES`` (which updates the wrapper " -"function's ``__dict__``, i.e. the instance dictionary)." +"(which assigns to the wrapper function's :attr:`~function.__module__`, :attr:" +"`~function.__name__`, :attr:`~function.__qualname__`, :attr:`~function." +"__annotations__`, :attr:`~function.__type_params__`, and :attr:`~function." +"__doc__`, the documentation string) and ``WRAPPER_UPDATES`` (which updates " +"the wrapper function's :attr:`~function.__dict__`, i.e. the instance " +"dictionary)." msgstr "" -#: library/functools.rst:652 +#: library/functools.rst:672 msgid "" "To allow access to the original function for introspection and other " "purposes (e.g. bypassing a caching decorator such as :func:`lru_cache`), " @@ -555,7 +887,7 @@ msgid "" "that refers to the function being wrapped." msgstr "" -#: library/functools.rst:657 +#: library/functools.rst:677 msgid "" "The main intended use for this function is in :term:`decorator` functions " "which wrap the decorated function and return the wrapper. If the wrapper " @@ -564,7 +896,7 @@ msgid "" "is typically less than helpful." msgstr "" -#: library/functools.rst:663 +#: library/functools.rst:683 msgid "" ":func:`update_wrapper` may be used with callables other than functions. Any " "attributes named in *assigned* or *updated* that are missing from the object " @@ -573,25 +905,26 @@ msgid "" "wrapper function itself is missing any attributes named in *updated*." msgstr "" -#: library/functools.rst:669 +#: library/functools.rst:689 msgid "" -"The ``__wrapped__`` attribute is now automatically added. The " -"``__annotations__`` attribute is now copied by default. Missing attributes " -"no longer trigger an :exc:`AttributeError`." +"The ``__wrapped__`` attribute is now automatically added. The :attr:" +"`~function.__annotations__` attribute is now copied by default. Missing " +"attributes no longer trigger an :exc:`AttributeError`." msgstr "" -#: library/functools.rst:674 +#: library/functools.rst:694 msgid "" "The ``__wrapped__`` attribute now always refers to the wrapped function, " "even if that function defined a ``__wrapped__`` attribute. (see :issue:" "`17482`)" msgstr "" -#: library/functools.rst:679 -msgid "The ``__type_params__`` attribute is now copied by default." +#: library/functools.rst:699 +msgid "" +"The :attr:`~function.__type_params__` attribute is now copied by default." msgstr "" -#: library/functools.rst:685 +#: library/functools.rst:705 msgid "" "This is a convenience function for invoking :func:`update_wrapper` as a " "function decorator when defining a wrapper function. It is equivalent to " @@ -599,47 +932,72 @@ msgid "" "updated=updated)``. For example::" msgstr "" -#: library/functools.rst:711 +#: library/functools.rst:710 +msgid "" +">>> from functools import wraps\n" +">>> def my_decorator(f):\n" +"... @wraps(f)\n" +"... def wrapper(*args, **kwds):\n" +"... print('Calling decorated function')\n" +"... return f(*args, **kwds)\n" +"... return wrapper\n" +"...\n" +">>> @my_decorator\n" +"... def example():\n" +"... \"\"\"Docstring\"\"\"\n" +"... print('Called example function')\n" +"...\n" +">>> example()\n" +"Calling decorated function\n" +"Called example function\n" +">>> example.__name__\n" +"'example'\n" +">>> example.__doc__\n" +"'Docstring'" +msgstr "" + +#: library/functools.rst:731 msgid "" "Without the use of this decorator factory, the name of the example function " "would have been ``'wrapper'``, and the docstring of the original :func:" "`example` would have been lost." msgstr "" -#: library/functools.rst:719 +#: library/functools.rst:739 msgid ":class:`partial` Objects" msgstr "" -#: library/functools.rst:721 +#: library/functools.rst:741 msgid "" ":class:`partial` objects are callable objects created by :func:`partial`. " "They have three read-only attributes:" msgstr "" -#: library/functools.rst:727 +#: library/functools.rst:747 msgid "" "A callable object or function. Calls to the :class:`partial` object will be " "forwarded to :attr:`func` with new arguments and keywords." msgstr "" -#: library/functools.rst:733 +#: library/functools.rst:753 msgid "" "The leftmost positional arguments that will be prepended to the positional " "arguments provided to a :class:`partial` object call." msgstr "" -#: library/functools.rst:739 +#: library/functools.rst:759 msgid "" "The keyword arguments that will be supplied when the :class:`partial` object " "is called." msgstr "" -#: library/functools.rst:742 +#: library/functools.rst:762 msgid "" -":class:`partial` objects are like :class:`function` objects in that they are " -"callable, weak referenceable, and can have attributes. There are some " -"important differences. For instance, the :attr:`~definition.__name__` and :" -"attr:`__doc__` attributes are not created automatically. Also, :class:" -"`partial` objects defined in classes behave like static methods and do not " -"transform into bound methods during instance attribute look-up." +":class:`partial` objects are like :ref:`function objects ` in that they are callable, weak referenceable, and can have " +"attributes. There are some important differences. For instance, the :attr:" +"`~function.__name__` and :attr:`function.__doc__` attributes are not created " +"automatically. Also, :class:`partial` objects defined in classes behave " +"like static methods and do not transform into bound methods during instance " +"attribute look-up." msgstr "" diff --git a/library/gc.po b/library/gc.po index 642853ec8..b73e3d359 100644 --- a/library/gc.po +++ b/library/gc.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -95,7 +95,9 @@ msgid "New *generation* parameter." msgstr "" #: library/gc.rst:78 -msgid "Raises an auditing event gc.get_objects with argument generation." +msgid "" +"Raises an :ref:`auditing event ` ``gc.get_objects`` with argument " +"``generation``." msgstr "" #: library/gc.rst:82 @@ -184,7 +186,9 @@ msgid "" msgstr "" #: library/gc.rst:149 -msgid "Raises an auditing event gc.get_referrers with argument objs." +msgid "" +"Raises an :ref:`auditing event ` ``gc.get_referrers`` with " +"argument ``objs``." msgstr "" #: library/gc.rst:154 @@ -200,7 +204,9 @@ msgid "" msgstr "" #: library/gc.rst:162 -msgid "Raises an auditing event gc.get_referents with argument objs." +msgid "" +"Raises an :ref:`auditing event ` ``gc.get_referents`` with " +"argument ``objs``." msgstr "" #: library/gc.rst:166 @@ -213,12 +219,44 @@ msgid "" "instances (e.g. dicts containing only atomic keys and values)::" msgstr "" +#: library/gc.rst:173 +msgid "" +">>> gc.is_tracked(0)\n" +"False\n" +">>> gc.is_tracked(\"a\")\n" +"False\n" +">>> gc.is_tracked([])\n" +"True\n" +">>> gc.is_tracked({})\n" +"False\n" +">>> gc.is_tracked({\"a\": 1})\n" +"False\n" +">>> gc.is_tracked({\"a\": []})\n" +"True" +msgstr "" + #: library/gc.rst:191 msgid "" "Returns ``True`` if the given object has been finalized by the garbage " "collector, ``False`` otherwise. ::" msgstr "" +#: library/gc.rst:194 +msgid "" +">>> x = None\n" +">>> class Lazarus:\n" +"... def __del__(self):\n" +"... global x\n" +"... x = self\n" +"...\n" +">>> lazarus = Lazarus()\n" +">>> gc.is_finalized(lazarus)\n" +"False\n" +">>> del lazarus\n" +">>> gc.is_finalized(x)\n" +"True" +msgstr "" + #: library/gc.rst:212 msgid "" "Freeze all the objects tracked by the garbage collector; move them to a " diff --git a/library/getopt.po b/library/getopt.po index 5d18a173c..a32ea796a 100644 --- a/library/getopt.po +++ b/library/getopt.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -132,6 +132,38 @@ msgstr "" msgid "In a script, typical usage is something like this::" msgstr "" +#: library/getopt.rst:120 +msgid "" +"import getopt, sys\n" +"\n" +"def main():\n" +" try:\n" +" opts, args = getopt.getopt(sys.argv[1:], \"ho:v\", [\"help\", " +"\"output=\"])\n" +" except getopt.GetoptError as err:\n" +" # print help information and exit:\n" +" print(err) # will print something like \"option -a not " +"recognized\"\n" +" usage()\n" +" sys.exit(2)\n" +" output = None\n" +" verbose = False\n" +" for o, a in opts:\n" +" if o == \"-v\":\n" +" verbose = True\n" +" elif o in (\"-h\", \"--help\"):\n" +" usage()\n" +" sys.exit()\n" +" elif o in (\"-o\", \"--output\"):\n" +" output = a\n" +" else:\n" +" assert False, \"unhandled option\"\n" +" # ...\n" +"\n" +"if __name__ == \"__main__\":\n" +" main()" +msgstr "" + #: library/getopt.rst:147 msgid "" "Note that an equivalent command line interface could be produced with less " @@ -139,6 +171,19 @@ msgid "" "`argparse` module::" msgstr "" +#: library/getopt.rst:150 +msgid "" +"import argparse\n" +"\n" +"if __name__ == '__main__':\n" +" parser = argparse.ArgumentParser()\n" +" parser.add_argument('-o', '--output')\n" +" parser.add_argument('-v', dest='verbose', action='store_true')\n" +" args = parser.parse_args()\n" +" # ... do something with args.output ...\n" +" # ... do something with args.verbose .." +msgstr "" + #: library/getopt.rst:162 msgid "Module :mod:`argparse`" msgstr "" diff --git a/library/getpass.po b/library/getpass.po index 5609a43dd..d0a08bfa5 100644 --- a/library/getpass.po +++ b/library/getpass.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -25,7 +25,7 @@ msgid "**Source code:** :source:`Lib/getpass.py`" msgstr "" #: includes/wasm-notavail.rst:3 -msgid ":ref:`Availability `: not Emscripten, not WASI." +msgid "Availability" msgstr "" #: includes/wasm-notavail.rst:5 @@ -80,6 +80,5 @@ msgid "" msgstr "" #: library/getpass.rst:52 -msgid "" -"In general, this function should be preferred over :func:`os.getlogin()`." +msgid "In general, this function should be preferred over :func:`os.getlogin`." msgstr "" diff --git a/library/gettext.po b/library/gettext.po index 3109e35b1..8634770ef 100644 --- a/library/gettext.po +++ b/library/gettext.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -130,6 +130,16 @@ msgstr "" msgid "Here's an example of typical usage for this API::" msgstr "" +#: library/gettext.rst:106 +msgid "" +"import gettext\n" +"gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')\n" +"gettext.textdomain('myapplication')\n" +"_ = gettext.gettext\n" +"# ...\n" +"print(_('This is a translatable string.'))" +msgstr "" + #: library/gettext.rst:115 msgid "Class-based API" msgstr "" @@ -235,6 +245,10 @@ msgid "" "function, like this::" msgstr "" +#: library/gettext.rst:187 +msgid "print(_('This string will be translated.'))" +msgstr "" + #: library/gettext.rst:189 msgid "" "For convenience, you want the :func:`!_` function to be installed in " @@ -341,6 +355,13 @@ msgid "" "this code to make :func:`!_` available to their module::" msgstr "" +#: library/gettext.rst:285 +msgid "" +"import gettext\n" +"t = gettext.translation('mymodule', ...)\n" +"_ = t.gettext" +msgstr "" + #: library/gettext.rst:289 msgid "" "This puts :func:`!_` only in the module's global namespace and so only " @@ -428,6 +449,16 @@ msgstr "" msgid "Here is an example::" msgstr "" +#: library/gettext.rst:350 +msgid "" +"n = len(os.listdir('.'))\n" +"cat = GNUTranslations(somefile)\n" +"message = cat.ngettext(\n" +" 'There is %(num)d file in this directory',\n" +" 'There are %(num)d files in this directory',\n" +" n) % {'num': n}" +msgstr "" + #: library/gettext.rst:360 msgid "" "Look up the *context* and *message* id in the catalog and return the " @@ -473,6 +504,14 @@ msgid "" "this version has a slightly different API. Its documented usage was::" msgstr "" +#: library/gettext.rst:399 +msgid "" +"import gettext\n" +"cat = gettext.Catalog(domain, localedir)\n" +"_ = cat.gettext\n" +"print(_('hello world'))" +msgstr "" + #: library/gettext.rst:404 msgid "" "For compatibility with this older module, the function :func:`!Catalog` is " @@ -526,6 +565,14 @@ msgid "" "`. For example::" msgstr "" +#: library/gettext.rst:434 +msgid "" +"filename = 'mylog.txt'\n" +"message = _('writing a log message')\n" +"with open(filename, 'w') as fp:\n" +" fp.write(message)" +msgstr "" + #: library/gettext.rst:439 msgid "" "In this example, the string ``'writing a log message'`` is marked as a " @@ -604,6 +651,13 @@ msgid "" "your module::" msgstr "" +#: library/gettext.rst:496 +msgid "" +"import gettext\n" +"t = gettext.translation('spam', '/usr/share/locale')\n" +"_ = t.gettext" +msgstr "" + #: library/gettext.rst:502 msgid "Localizing your application" msgstr "" @@ -622,12 +676,24 @@ msgid "" "main driver file of your application::" msgstr "" +#: library/gettext.rst:512 +msgid "" +"import gettext\n" +"gettext.install('myapplication')" +msgstr "" + #: library/gettext.rst:515 msgid "" "If you need to set the locale directory, you can pass it into the :func:" "`install` function::" msgstr "" +#: library/gettext.rst:518 +msgid "" +"import gettext\n" +"gettext.install('myapplication', '/usr/share/locale')" +msgstr "" + #: library/gettext.rst:523 msgid "Changing languages on the fly" msgstr "" @@ -639,6 +705,24 @@ msgid "" "explicitly, like so::" msgstr "" +#: library/gettext.rst:529 +msgid "" +"import gettext\n" +"\n" +"lang1 = gettext.translation('myapplication', languages=['en'])\n" +"lang2 = gettext.translation('myapplication', languages=['fr'])\n" +"lang3 = gettext.translation('myapplication', languages=['de'])\n" +"\n" +"# start by using language1\n" +"lang1.install()\n" +"\n" +"# ... time goes by, user selects language 2\n" +"lang2.install()\n" +"\n" +"# ... more time goes by, user selects language 3\n" +"lang3.install()" +msgstr "" + #: library/gettext.rst:546 msgid "Deferred translations" msgstr "" @@ -650,6 +734,18 @@ msgid "" "actual translation until later. A classic example is::" msgstr "" +#: library/gettext.rst:552 +msgid "" +"animals = ['mollusk',\n" +" 'albatross',\n" +" 'rat',\n" +" 'penguin',\n" +" 'python', ]\n" +"# ...\n" +"for a in animals:\n" +" print(a)" +msgstr "" + #: library/gettext.rst:561 msgid "" "Here, you want to mark the strings in the ``animals`` list as being " @@ -661,6 +757,23 @@ msgstr "" msgid "Here is one way you can handle this situation::" msgstr "" +#: library/gettext.rst:567 +msgid "" +"def _(message): return message\n" +"\n" +"animals = [_('mollusk'),\n" +" _('albatross'),\n" +" _('rat'),\n" +" _('penguin'),\n" +" _('python'), ]\n" +"\n" +"del _\n" +"\n" +"# ...\n" +"for a in animals:\n" +" print(_(a))" +msgstr "" + #: library/gettext.rst:581 msgid "" "This works because the dummy definition of :func:`!_` simply returns the " @@ -681,6 +794,21 @@ msgstr "" msgid "Another way to handle this is with the following example::" msgstr "" +#: library/gettext.rst:593 +msgid "" +"def N_(message): return message\n" +"\n" +"animals = [N_('mollusk'),\n" +" N_('albatross'),\n" +" N_('rat'),\n" +" N_('penguin'),\n" +" N_('python'), ]\n" +"\n" +"# ...\n" +"for a in animals:\n" +" print(_(a))" +msgstr "" + #: library/gettext.rst:605 msgid "" "In this case, you are marking translatable strings with the function :func:`!" diff --git a/library/glob.po b/library/glob.po index ea39b32af..6db6455ec 100644 --- a/library/glob.po +++ b/library/glob.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -93,13 +93,15 @@ msgid "" msgstr "" #: library/glob.rst:100 -msgid "Raises an auditing event glob.glob with arguments pathname, recursive." +msgid "" +"Raises an :ref:`auditing event ` ``glob.glob`` with arguments " +"``pathname``, ``recursive``." msgstr "" #: library/glob.rst:101 msgid "" -"Raises an auditing event glob.glob/2 with arguments pathname, recursive, " -"root_dir, dir_fd." +"Raises an :ref:`auditing event ` ``glob.glob/2`` with arguments " +"``pathname``, ``recursive``, ``root_dir``, ``dir_fd``." msgstr "" #: library/glob.rst:77 @@ -150,6 +152,21 @@ msgid "" "preserved. ::" msgstr "" +#: library/glob.rst:134 +msgid "" +">>> import glob\n" +">>> glob.glob('./[0-9].*')\n" +"['./1.gif', './2.txt']\n" +">>> glob.glob('*.gif')\n" +"['1.gif', 'card.gif']\n" +">>> glob.glob('?.gif')\n" +"['1.gif']\n" +">>> glob.glob('**/*.txt', recursive=True)\n" +"['2.txt', 'sub/3.txt']\n" +">>> glob.glob('./**/', recursive=True)\n" +"['./', './sub/']" +msgstr "" + #: library/glob.rst:146 msgid "" "If the directory contains files starting with ``.`` they won't be matched by " @@ -157,6 +174,15 @@ msgid "" "file:`.card.gif`::" msgstr "" +#: library/glob.rst:150 +msgid "" +">>> import glob\n" +">>> glob.glob('*.gif')\n" +"['card.gif']\n" +">>> glob.glob('.c*')\n" +"['.card.gif']" +msgstr "" + #: library/glob.rst:158 msgid "Module :mod:`fnmatch`" msgstr "" diff --git a/library/graphlib.po b/library/graphlib.po index 5b4b7b96f..fb858c40a 100644 --- a/library/graphlib.po +++ b/library/graphlib.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -86,12 +86,45 @@ msgid "" "static_order` can be used directly:" msgstr "" +#: library/graphlib.rst:53 +msgid "" +">>> graph = {\"D\": {\"B\", \"C\"}, \"C\": {\"A\"}, \"B\": {\"A\"}}\n" +">>> ts = TopologicalSorter(graph)\n" +">>> tuple(ts.static_order())\n" +"('A', 'C', 'B', 'D')" +msgstr "" + #: library/graphlib.rst:60 msgid "" "The class is designed to easily support parallel processing of the nodes as " "they become ready. For instance::" msgstr "" +#: library/graphlib.rst:63 +msgid "" +"topological_sorter = TopologicalSorter()\n" +"\n" +"# Add nodes to 'topological_sorter'...\n" +"\n" +"topological_sorter.prepare()\n" +"while topological_sorter.is_active():\n" +" for node in topological_sorter.get_ready():\n" +" # Worker threads or processes take nodes to work on off the\n" +" # 'task_queue' queue.\n" +" task_queue.put(node)\n" +"\n" +" # When the work for a node is done, workers put the node in\n" +" # 'finalized_tasks_queue' so we can get more nodes to work on.\n" +" # The definition of 'is_active()' guarantees that, at this point, at\n" +" # least one node has been placed on 'task_queue' that hasn't yet\n" +" # been passed to 'done()', so this blocking 'get()' must (eventually)\n" +" # succeed. After calling 'done()', we loop back to call 'get_ready()'\n" +" # again, so put newly freed nodes on 'task_queue' as soon as\n" +" # logically possible.\n" +" node = finalized_tasks_queue.get()\n" +" topological_sorter.done(node)" +msgstr "" + #: library/graphlib.rst:87 msgid "" "Add a new node and its predecessors to the graph. Both the *node* and all " @@ -143,10 +176,22 @@ msgid "" "so instead of::" msgstr "" +#: library/graphlib.rst:121 +msgid "" +"if ts.is_active():\n" +" ..." +msgstr "" + #: library/graphlib.rst:124 msgid "it is possible to simply do::" msgstr "" +#: library/graphlib.rst:126 +msgid "" +"if ts:\n" +" ..." +msgstr "" + #: library/graphlib.rst:152 msgid "" "Raises :exc:`ValueError` if called without calling :meth:`~TopologicalSorter." @@ -186,12 +231,37 @@ msgid "" "to::" msgstr "" +#: library/graphlib.rst:162 +msgid "" +"def static_order(self):\n" +" self.prepare()\n" +" while self.is_active():\n" +" node_group = self.get_ready()\n" +" yield from node_group\n" +" self.done(*node_group)" +msgstr "" + #: library/graphlib.rst:169 msgid "" "The particular order that is returned may depend on the specific order in " "which the items were inserted in the graph. For example:" msgstr "" +#: library/graphlib.rst:172 +msgid "" +">>> ts = TopologicalSorter()\n" +">>> ts.add(3, 2, 1)\n" +">>> ts.add(1, 0)\n" +">>> print([*ts.static_order()])\n" +"[2, 0, 1, 3]\n" +"\n" +">>> ts2 = TopologicalSorter()\n" +">>> ts2.add(1, 0)\n" +">>> ts2.add(3, 2, 1)\n" +">>> print([*ts2.static_order()])\n" +"[0, 2, 1, 3]" +msgstr "" + #: library/graphlib.rst:186 msgid "" "This is due to the fact that \"0\" and \"2\" are in the same level in the " diff --git a/library/grp.po b/library/grp.po index 7c07a5d42..1cd949631 100644 --- a/library/grp.po +++ b/library/grp.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -27,7 +27,7 @@ msgid "" msgstr "" #: library/grp.rst:13 -msgid ":ref:`Availability `: Unix, not Emscripten, not WASI." +msgid "Availability" msgstr "" #: library/grp.rst:15 diff --git a/library/gzip.po b/library/gzip.po index 9cc276722..eeb0d4481 100644 --- a/library/gzip.po +++ b/library/gzip.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-08-01 00:19+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -311,18 +311,49 @@ msgstr "" msgid "Example of how to read a compressed file::" msgstr "" +#: library/gzip.rst:221 +msgid "" +"import gzip\n" +"with gzip.open('/home/joe/file.txt.gz', 'rb') as f:\n" +" file_content = f.read()" +msgstr "" + #: library/gzip.rst:225 msgid "Example of how to create a compressed GZIP file::" msgstr "" +#: library/gzip.rst:227 +msgid "" +"import gzip\n" +"content = b\"Lots of content here\"\n" +"with gzip.open('/home/joe/file.txt.gz', 'wb') as f:\n" +" f.write(content)" +msgstr "" + #: library/gzip.rst:232 msgid "Example of how to GZIP compress an existing file::" msgstr "" +#: library/gzip.rst:234 +msgid "" +"import gzip\n" +"import shutil\n" +"with open('/home/joe/file.txt', 'rb') as f_in:\n" +" with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out:\n" +" shutil.copyfileobj(f_in, f_out)" +msgstr "" + #: library/gzip.rst:240 msgid "Example of how to GZIP compress a binary string::" msgstr "" +#: library/gzip.rst:242 +msgid "" +"import gzip\n" +"s_in = b\"Lots of content here\"\n" +"s_out = gzip.compress(s_in)" +msgstr "" + #: library/gzip.rst:248 msgid "Module :mod:`zlib`" msgstr "" diff --git a/library/hashlib.po b/library/hashlib.po index c15927c1b..6affae605 100644 --- a/library/hashlib.po +++ b/library/hashlib.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -127,6 +127,20 @@ msgid "" "repetition\"``::" msgstr "" +#: library/hashlib.rst:105 +msgid "" +">>> import hashlib\n" +">>> m = hashlib.sha256()\n" +">>> m.update(b\"Nobody inspects\")\n" +">>> m.update(b\" the spammish repetition\")\n" +">>> m.digest()\n" +"b'\\x03\\x1e\\xdd}Ae\\x15\\x93\\xc5\\xfe\\\\" +"\\x00o\\xa5u+7\\xfd\\xdf\\xf7\\xbcN\\x84:" +"\\xa6\\xaf\\x0c\\x95\\x0fK\\x94\\x06'\n" +">>> m.hexdigest()\n" +"'031edd7d41651593c5fe5c006fa5752b37fddff7bc4e843aa6af0c950f4b9406'" +msgstr "" + #: library/hashlib.rst:114 msgid "More condensed:" msgstr "" @@ -663,18 +677,65 @@ msgid "" "for message ``b'message data'`` with key ``b'pseudorandom key'``::" msgstr "" +#: library/hashlib.rst:583 +msgid "" +">>> from hashlib import blake2b\n" +">>> h = blake2b(key=b'pseudorandom key', digest_size=16)\n" +">>> h.update(b'message data')\n" +">>> h.hexdigest()\n" +"'3d363ff7401e02026f4a4687d4863ced'" +msgstr "" + #: library/hashlib.rst:590 msgid "" "As a practical example, a web application can symmetrically sign cookies " "sent to users and later verify them to make sure they weren't tampered with::" msgstr "" +#: library/hashlib.rst:593 +msgid "" +">>> from hashlib import blake2b\n" +">>> from hmac import compare_digest\n" +">>>\n" +">>> SECRET_KEY = b'pseudorandomly generated server secret key'\n" +">>> AUTH_SIZE = 16\n" +">>>\n" +">>> def sign(cookie):\n" +"... h = blake2b(digest_size=AUTH_SIZE, key=SECRET_KEY)\n" +"... h.update(cookie)\n" +"... return h.hexdigest().encode('utf-8')\n" +">>>\n" +">>> def verify(cookie, sig):\n" +"... good_sig = sign(cookie)\n" +"... return compare_digest(good_sig, sig)\n" +">>>\n" +">>> cookie = b'user-alice'\n" +">>> sig = sign(cookie)\n" +">>> print(\"{0},{1}\".format(cookie.decode('utf-8'), sig))\n" +"user-alice,b'43b3c982cf697e0c5ab22172d1ca7421'\n" +">>> verify(cookie, sig)\n" +"True\n" +">>> verify(b'user-bob', sig)\n" +"False\n" +">>> verify(cookie, b'0102030405060708090a0b0c0d0e0f00')\n" +"False" +msgstr "" + #: library/hashlib.rst:619 msgid "" "Even though there's a native keyed hashing mode, BLAKE2 can, of course, be " "used in HMAC construction with :mod:`hmac` module::" msgstr "" +#: library/hashlib.rst:622 +msgid "" +">>> import hmac, hashlib\n" +">>> m = hmac.new(b'secret key', digestmod=hashlib.blake2s)\n" +">>> m.update(b'message')\n" +">>> m.hexdigest()\n" +"'e3c8102868d28b5ff85fc35dda07329970d1a01e273c37481326fe0c861c8142'" +msgstr "" + #: library/hashlib.rst:630 msgid "Randomized hashing" msgstr "" @@ -710,7 +771,7 @@ msgstr "" #: library/hashlib.rst:655 msgid "" "(`NIST SP-800-106 \"Randomized Hashing for Digital Signatures\" `_)" +"csrc.nist.gov/pubs/sp/800/106/final>`_)" msgstr "" #: library/hashlib.rst:658 @@ -758,6 +819,21 @@ msgstr "" msgid "BLAKE2 can be personalized by passing bytes to the *person* argument::" msgstr "" +#: library/hashlib.rst:705 +msgid "" +">>> from hashlib import blake2b\n" +">>> FILES_HASH_PERSON = b'MyApp Files Hash'\n" +">>> BLOCK_HASH_PERSON = b'MyApp Block Hash'\n" +">>> h = blake2b(digest_size=32, person=FILES_HASH_PERSON)\n" +">>> h.update(b'the same content')\n" +">>> h.hexdigest()\n" +"'20d9cd024d4fb086aae819a1432dd2466de12947831b75c5a30cf2676095d3b4'\n" +">>> h = blake2b(digest_size=32, person=BLOCK_HASH_PERSON)\n" +">>> h.update(b'the same content')\n" +">>> h.hexdigest()\n" +"'cf68fb5761b9c44e7878bfb2c4c9aea52264a80b75005e65619778de59f383a3'" +msgstr "" + #: library/hashlib.rst:717 msgid "" "Personalization together with the keyed mode can also be used to derive " @@ -772,12 +848,48 @@ msgstr "" msgid "Here's an example of hashing a minimal tree with two leaf nodes::" msgstr "" +#: library/hashlib.rst:735 +msgid "" +" 10\n" +" / \\\n" +"00 01" +msgstr "" + #: library/hashlib.rst:739 msgid "" "This example uses 64-byte internal digests, and returns the 32-byte final " "digest::" msgstr "" +#: library/hashlib.rst:742 +msgid "" +">>> from hashlib import blake2b\n" +">>>\n" +">>> FANOUT = 2\n" +">>> DEPTH = 2\n" +">>> LEAF_SIZE = 4096\n" +">>> INNER_SIZE = 64\n" +">>>\n" +">>> buf = bytearray(6000)\n" +">>>\n" +">>> # Left leaf\n" +"... h00 = blake2b(buf[0:LEAF_SIZE], fanout=FANOUT, depth=DEPTH,\n" +"... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,\n" +"... node_offset=0, node_depth=0, last_node=False)\n" +">>> # Right leaf\n" +"... h01 = blake2b(buf[LEAF_SIZE:], fanout=FANOUT, depth=DEPTH,\n" +"... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,\n" +"... node_offset=1, node_depth=0, last_node=True)\n" +">>> # Root node\n" +"... h10 = blake2b(digest_size=32, fanout=FANOUT, depth=DEPTH,\n" +"... leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,\n" +"... node_offset=0, node_depth=1, last_node=True)\n" +">>> h10.update(h00.digest())\n" +">>> h10.update(h01.digest())\n" +">>> h10.hexdigest()\n" +"'3ad2a9b37c6070e374c7a8c508fe20ca86b6ed54e286e93a0318e95e881db5aa'" +msgstr "" + #: library/hashlib.rst:769 msgid "Credits" msgstr "" @@ -863,7 +975,7 @@ msgid "The FIPS 180-4 publication on Secure Hash Algorithms." msgstr "" #: library/hashlib.rst:828 -msgid "https://csrc.nist.gov/publications/detail/fips/202/final" +msgid "https://csrc.nist.gov/pubs/fips/202/final" msgstr "" #: library/hashlib.rst:829 diff --git a/library/heapq.po b/library/heapq.po index 4ee5bf7de..2c9a53daa 100644 --- a/library/heapq.po +++ b/library/heapq.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -199,6 +199,18 @@ msgid "" "at a time::" msgstr "" +#: library/heapq.rst:144 +msgid "" +">>> def heapsort(iterable):\n" +"... h = []\n" +"... for value in iterable:\n" +"... heappush(h, value)\n" +"... return [heappop(h) for i in range(len(h))]\n" +"...\n" +">>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])\n" +"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" +msgstr "" + #: library/heapq.rst:153 msgid "" "This is similar to ``sorted(iterable)``, but unlike :func:`sorted`, this " @@ -211,6 +223,17 @@ msgid "" "(such as task priorities) alongside the main record being tracked::" msgstr "" +#: library/heapq.rst:159 +msgid "" +">>> h = []\n" +">>> heappush(h, (5, 'write code'))\n" +">>> heappush(h, (7, 'release product'))\n" +">>> heappush(h, (1, 'write spec'))\n" +">>> heappush(h, (3, 'create tests'))\n" +">>> heappop(h)\n" +"(1, 'write spec')" +msgstr "" + #: library/heapq.rst:169 msgid "Priority Queue Implementation Notes" msgstr "" @@ -261,6 +284,17 @@ msgid "" "field::" msgstr "" +#: library/heapq.rst:195 +msgid "" +"from dataclasses import dataclass, field\n" +"from typing import Any\n" +"\n" +"@dataclass(order=True)\n" +"class PrioritizedItem:\n" +" priority: int\n" +" item: Any=field(compare=False)" +msgstr "" + #: library/heapq.rst:203 msgid "" "The remaining challenges revolve around finding a pending task and making " @@ -275,6 +309,37 @@ msgid "" "mark the entry as removed and add a new entry with the revised priority::" msgstr "" +#: library/heapq.rst:211 +msgid "" +"pq = [] # list of entries arranged in a heap\n" +"entry_finder = {} # mapping of tasks to entries\n" +"REMOVED = '' # placeholder for a removed task\n" +"counter = itertools.count() # unique sequence count\n" +"\n" +"def add_task(task, priority=0):\n" +" 'Add a new task or update the priority of an existing task'\n" +" if task in entry_finder:\n" +" remove_task(task)\n" +" count = next(counter)\n" +" entry = [priority, count, task]\n" +" entry_finder[task] = entry\n" +" heappush(pq, entry)\n" +"\n" +"def remove_task(task):\n" +" 'Mark an existing task as REMOVED. Raise KeyError if not found.'\n" +" entry = entry_finder.pop(task)\n" +" entry[-1] = REMOVED\n" +"\n" +"def pop_task():\n" +" 'Remove and return the lowest priority task. Raise KeyError if empty.'\n" +" while pq:\n" +" priority, count, task = heappop(pq)\n" +" if task is not REMOVED:\n" +" del entry_finder[task]\n" +" return task\n" +" raise KeyError('pop from an empty priority queue')" +msgstr "" + #: library/heapq.rst:241 msgid "Theory" msgstr "" @@ -293,6 +358,19 @@ msgid "" "representation for a tournament. The numbers below are *k*, not ``a[k]``::" msgstr "" +#: library/heapq.rst:251 +msgid "" +" 0\n" +"\n" +" 1 2\n" +"\n" +" 3 4 5 6\n" +"\n" +" 7 8 9 10 11 12 13 14\n" +"\n" +"15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30" +msgstr "" + #: library/heapq.rst:261 msgid "" "In the tree above, each cell *k* is topping ``2*k+1`` and ``2*k+2``. In a " diff --git a/library/html.parser.po b/library/html.parser.po index f57a3de0b..dd75102f1 100644 --- a/library/html.parser.po +++ b/library/html.parser.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2024-06-01 00:16+0000\n" +"POT-Creation-Date: 2024-11-01 00:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: \n" "Language-Team: TURKISH \n" @@ -76,10 +76,45 @@ msgid "" "encountered::" msgstr "" +#: library/html.parser.rst:48 +msgid "" +"from html.parser import HTMLParser\n" +"\n" +"class MyHTMLParser(HTMLParser):\n" +" def handle_starttag(self, tag, attrs):\n" +" print(\"Encountered a start tag:\", tag)\n" +"\n" +" def handle_endtag(self, tag):\n" +" print(\"Encountered an end tag :\", tag)\n" +"\n" +" def handle_data(self, data):\n" +" print(\"Encountered some data :\", data)\n" +"\n" +"parser = MyHTMLParser()\n" +"parser.feed('Test'\n" +" '

Parse me!

')" +msgstr "" + #: library/html.parser.rst:64 msgid "The output will then be:" msgstr "" +#: library/html.parser.rst:66 +msgid "" +"Encountered a start tag: html\n" +"Encountered a start tag: head\n" +"Encountered a start tag: title\n" +"Encountered some data : Test\n" +"Encountered an end tag : title\n" +"Encountered an end tag : head\n" +"Encountered a start tag: body\n" +"Encountered a start tag: h1\n" +"Encountered some data : Parse me!\n" +"Encountered an end tag : h1\n" +"Encountered an end tag : body\n" +"Encountered an end tag : html" +msgstr "" + #: library/html.parser.rst:83 msgid ":class:`.HTMLParser` Methods" msgstr "" @@ -267,30 +302,121 @@ msgid "" "examples::" msgstr "" +#: library/html.parser.rst:235 +msgid "" +"from html.parser import HTMLParser\n" +"from html.entities import name2codepoint\n" +"\n" +"class MyHTMLParser(HTMLParser):\n" +" def handle_starttag(self, tag, attrs):\n" +" print(\"Start tag:\", tag)\n" +" for attr in attrs:\n" +" print(\" attr:\", attr)\n" +"\n" +" def handle_endtag(self, tag):\n" +" print(\"End tag :\", tag)\n" +"\n" +" def handle_data(self, data):\n" +" print(\"Data :\", data)\n" +"\n" +" def handle_comment(self, data):\n" +" print(\"Comment :\", data)\n" +"\n" +" def handle_entityref(self, name):\n" +" c = chr(name2codepoint[name])\n" +" print(\"Named ent:\", c)\n" +"\n" +" def handle_charref(self, name):\n" +" if name.startswith('x'):\n" +" c = chr(int(name[1:], 16))\n" +" else:\n" +" c = chr(int(name))\n" +" print(\"Num ent :\", c)\n" +"\n" +" def handle_decl(self, data):\n" +" print(\"Decl :\", data)\n" +"\n" +"parser = MyHTMLParser()" +msgstr "" + #: library/html.parser.rst:269 msgid "Parsing a doctype::" msgstr "" +#: library/html.parser.rst:271 +msgid "" +">>> parser.feed('')\n" +"Decl : DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3." +"org/TR/html4/strict.dtd\"" +msgstr "" + #: library/html.parser.rst:275 msgid "Parsing an element with a few attributes and a title::" msgstr "" +#: library/html.parser.rst:277 +msgid "" +">>> parser.feed('\"The')\n" +"Start tag: img\n" +" attr: ('src', 'python-logo.png')\n" +" attr: ('alt', 'The Python logo')\n" +">>>\n" +">>> parser.feed('

Python

')\n" +"Start tag: h1\n" +"Data : Python\n" +"End tag : h1" +msgstr "" + #: library/html.parser.rst:287 msgid "" "The content of ``script`` and ``style`` elements is returned as is, without " "further parsing::" msgstr "" +#: library/html.parser.rst:290 +msgid "" +">>> parser.feed('