mirror of
https://github.com/jart/cosmopolitan.git
synced 2025-05-30 01:02:29 +00:00
python-3.6.zip added from Github
README.cosmo contains the necessary links.
This commit is contained in:
parent
75fc601ff5
commit
0c4c56ff39
4219 changed files with 1968626 additions and 0 deletions
134
third_party/python/Doc/includes/capsulethunk.h
vendored
Normal file
134
third_party/python/Doc/includes/capsulethunk.h
vendored
Normal file
|
@ -0,0 +1,134 @@
|
|||
#ifndef __CAPSULETHUNK_H
|
||||
#define __CAPSULETHUNK_H
|
||||
|
||||
#if ( (PY_VERSION_HEX < 0x02070000) \
|
||||
|| ((PY_VERSION_HEX >= 0x03000000) \
|
||||
&& (PY_VERSION_HEX < 0x03010000)) )
|
||||
|
||||
#define __PyCapsule_GetField(capsule, field, default_value) \
|
||||
( PyCapsule_CheckExact(capsule) \
|
||||
? (((PyCObject *)capsule)->field) \
|
||||
: (default_value) \
|
||||
) \
|
||||
|
||||
#define __PyCapsule_SetField(capsule, field, value) \
|
||||
( PyCapsule_CheckExact(capsule) \
|
||||
? (((PyCObject *)capsule)->field = value), 1 \
|
||||
: 0 \
|
||||
) \
|
||||
|
||||
|
||||
#define PyCapsule_Type PyCObject_Type
|
||||
|
||||
#define PyCapsule_CheckExact(capsule) (PyCObject_Check(capsule))
|
||||
#define PyCapsule_IsValid(capsule, name) (PyCObject_Check(capsule))
|
||||
|
||||
|
||||
#define PyCapsule_New(pointer, name, destructor) \
|
||||
(PyCObject_FromVoidPtr(pointer, destructor))
|
||||
|
||||
|
||||
#define PyCapsule_GetPointer(capsule, name) \
|
||||
(PyCObject_AsVoidPtr(capsule))
|
||||
|
||||
/* Don't call PyCObject_SetPointer here, it fails if there's a destructor */
|
||||
#define PyCapsule_SetPointer(capsule, pointer) \
|
||||
__PyCapsule_SetField(capsule, cobject, pointer)
|
||||
|
||||
|
||||
#define PyCapsule_GetDestructor(capsule) \
|
||||
__PyCapsule_GetField(capsule, destructor)
|
||||
|
||||
#define PyCapsule_SetDestructor(capsule, dtor) \
|
||||
__PyCapsule_SetField(capsule, destructor, dtor)
|
||||
|
||||
|
||||
/*
|
||||
* Sorry, there's simply no place
|
||||
* to store a Capsule "name" in a CObject.
|
||||
*/
|
||||
#define PyCapsule_GetName(capsule) NULL
|
||||
|
||||
static int
|
||||
PyCapsule_SetName(PyObject *capsule, const char *unused)
|
||||
{
|
||||
unused = unused;
|
||||
PyErr_SetString(PyExc_NotImplementedError,
|
||||
"can't use PyCapsule_SetName with CObjects");
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
|
||||
#define PyCapsule_GetContext(capsule) \
|
||||
__PyCapsule_GetField(capsule, descr)
|
||||
|
||||
#define PyCapsule_SetContext(capsule, context) \
|
||||
__PyCapsule_SetField(capsule, descr, context)
|
||||
|
||||
|
||||
static void *
|
||||
PyCapsule_Import(const char *name, int no_block)
|
||||
{
|
||||
PyObject *object = NULL;
|
||||
void *return_value = NULL;
|
||||
char *trace;
|
||||
size_t name_length = (strlen(name) + 1) * sizeof(char);
|
||||
char *name_dup = (char *)PyMem_MALLOC(name_length);
|
||||
|
||||
if (!name_dup) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
memcpy(name_dup, name, name_length);
|
||||
|
||||
trace = name_dup;
|
||||
while (trace) {
|
||||
char *dot = strchr(trace, '.');
|
||||
if (dot) {
|
||||
*dot++ = '\0';
|
||||
}
|
||||
|
||||
if (object == NULL) {
|
||||
if (no_block) {
|
||||
object = PyImport_ImportModuleNoBlock(trace);
|
||||
} else {
|
||||
object = PyImport_ImportModule(trace);
|
||||
if (!object) {
|
||||
PyErr_Format(PyExc_ImportError,
|
||||
"PyCapsule_Import could not "
|
||||
"import module \"%s\"", trace);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
PyObject *object2 = PyObject_GetAttrString(object, trace);
|
||||
Py_DECREF(object);
|
||||
object = object2;
|
||||
}
|
||||
if (!object) {
|
||||
goto EXIT;
|
||||
}
|
||||
|
||||
trace = dot;
|
||||
}
|
||||
|
||||
if (PyCObject_Check(object)) {
|
||||
PyCObject *cobject = (PyCObject *)object;
|
||||
return_value = cobject->cobject;
|
||||
} else {
|
||||
PyErr_Format(PyExc_AttributeError,
|
||||
"PyCapsule_Import \"%s\" is not valid",
|
||||
name);
|
||||
}
|
||||
|
||||
EXIT:
|
||||
Py_XDECREF(object);
|
||||
if (name_dup) {
|
||||
PyMem_FREE(name_dup);
|
||||
}
|
||||
return return_value;
|
||||
}
|
||||
|
||||
#endif /* #if PY_VERSION_HEX < 0x02070000 */
|
||||
|
||||
#endif /* __CAPSULETHUNK_H */
|
39
third_party/python/Doc/includes/custom.c
vendored
Normal file
39
third_party/python/Doc/includes/custom.c
vendored
Normal file
|
@ -0,0 +1,39 @@
|
|||
#include <Python.h>
|
||||
|
||||
typedef struct {
|
||||
PyObject_HEAD
|
||||
/* Type-specific fields go here. */
|
||||
} CustomObject;
|
||||
|
||||
static PyTypeObject CustomType = {
|
||||
PyVarObject_HEAD_INIT(NULL, 0)
|
||||
.tp_name = "custom.Custom",
|
||||
.tp_doc = "Custom objects",
|
||||
.tp_basicsize = sizeof(CustomObject),
|
||||
.tp_itemsize = 0,
|
||||
.tp_flags = Py_TPFLAGS_DEFAULT,
|
||||
.tp_new = PyType_GenericNew,
|
||||
};
|
||||
|
||||
static PyModuleDef custommodule = {
|
||||
PyModuleDef_HEAD_INIT,
|
||||
.m_name = "custom",
|
||||
.m_doc = "Example module that creates an extension type.",
|
||||
.m_size = -1,
|
||||
};
|
||||
|
||||
PyMODINIT_FUNC
|
||||
PyInit_custom(void)
|
||||
{
|
||||
PyObject *m;
|
||||
if (PyType_Ready(&CustomType) < 0)
|
||||
return NULL;
|
||||
|
||||
m = PyModule_Create(&custommodule);
|
||||
if (m == NULL)
|
||||
return NULL;
|
||||
|
||||
Py_INCREF(&CustomType);
|
||||
PyModule_AddObject(m, "Custom", (PyObject *) &CustomType);
|
||||
return m;
|
||||
}
|
132
third_party/python/Doc/includes/custom2.c
vendored
Normal file
132
third_party/python/Doc/includes/custom2.c
vendored
Normal file
|
@ -0,0 +1,132 @@
|
|||
#include <Python.h>
|
||||
#include "structmember.h"
|
||||
|
||||
typedef struct {
|
||||
PyObject_HEAD
|
||||
PyObject *first; /* first name */
|
||||
PyObject *last; /* last name */
|
||||
int number;
|
||||
} CustomObject;
|
||||
|
||||
static void
|
||||
Custom_dealloc(CustomObject *self)
|
||||
{
|
||||
Py_XDECREF(self->first);
|
||||
Py_XDECREF(self->last);
|
||||
Py_TYPE(self)->tp_free((PyObject *) self);
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
|
||||
{
|
||||
CustomObject *self;
|
||||
self = (CustomObject *) type->tp_alloc(type, 0);
|
||||
if (self != NULL) {
|
||||
self->first = PyUnicode_FromString("");
|
||||
if (self->first == NULL) {
|
||||
Py_DECREF(self);
|
||||
return NULL;
|
||||
}
|
||||
self->last = PyUnicode_FromString("");
|
||||
if (self->last == NULL) {
|
||||
Py_DECREF(self);
|
||||
return NULL;
|
||||
}
|
||||
self->number = 0;
|
||||
}
|
||||
return (PyObject *) self;
|
||||
}
|
||||
|
||||
static int
|
||||
Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
|
||||
{
|
||||
static char *kwlist[] = {"first", "last", "number", NULL};
|
||||
PyObject *first = NULL, *last = NULL, *tmp;
|
||||
|
||||
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
|
||||
&first, &last,
|
||||
&self->number))
|
||||
return -1;
|
||||
|
||||
if (first) {
|
||||
tmp = self->first;
|
||||
Py_INCREF(first);
|
||||
self->first = first;
|
||||
Py_XDECREF(tmp);
|
||||
}
|
||||
if (last) {
|
||||
tmp = self->last;
|
||||
Py_INCREF(last);
|
||||
self->last = last;
|
||||
Py_XDECREF(tmp);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static PyMemberDef Custom_members[] = {
|
||||
{"first", T_OBJECT_EX, offsetof(CustomObject, first), 0,
|
||||
"first name"},
|
||||
{"last", T_OBJECT_EX, offsetof(CustomObject, last), 0,
|
||||
"last name"},
|
||||
{"number", T_INT, offsetof(CustomObject, number), 0,
|
||||
"custom number"},
|
||||
{NULL} /* Sentinel */
|
||||
};
|
||||
|
||||
static PyObject *
|
||||
Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))
|
||||
{
|
||||
if (self->first == NULL) {
|
||||
PyErr_SetString(PyExc_AttributeError, "first");
|
||||
return NULL;
|
||||
}
|
||||
if (self->last == NULL) {
|
||||
PyErr_SetString(PyExc_AttributeError, "last");
|
||||
return NULL;
|
||||
}
|
||||
return PyUnicode_FromFormat("%S %S", self->first, self->last);
|
||||
}
|
||||
|
||||
static PyMethodDef Custom_methods[] = {
|
||||
{"name", (PyCFunction) Custom_name, METH_NOARGS,
|
||||
"Return the name, combining the first and last name"
|
||||
},
|
||||
{NULL} /* Sentinel */
|
||||
};
|
||||
|
||||
static PyTypeObject CustomType = {
|
||||
PyVarObject_HEAD_INIT(NULL, 0)
|
||||
.tp_name = "custom2.Custom",
|
||||
.tp_doc = "Custom objects",
|
||||
.tp_basicsize = sizeof(CustomObject),
|
||||
.tp_itemsize = 0,
|
||||
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
|
||||
.tp_new = Custom_new,
|
||||
.tp_init = (initproc) Custom_init,
|
||||
.tp_dealloc = (destructor) Custom_dealloc,
|
||||
.tp_members = Custom_members,
|
||||
.tp_methods = Custom_methods,
|
||||
};
|
||||
|
||||
static PyModuleDef custommodule = {
|
||||
PyModuleDef_HEAD_INIT,
|
||||
.m_name = "custom2",
|
||||
.m_doc = "Example module that creates an extension type.",
|
||||
.m_size = -1,
|
||||
};
|
||||
|
||||
PyMODINIT_FUNC
|
||||
PyInit_custom2(void)
|
||||
{
|
||||
PyObject *m;
|
||||
if (PyType_Ready(&CustomType) < 0)
|
||||
return NULL;
|
||||
|
||||
m = PyModule_Create(&custommodule);
|
||||
if (m == NULL)
|
||||
return NULL;
|
||||
|
||||
Py_INCREF(&CustomType);
|
||||
PyModule_AddObject(m, "Custom", (PyObject *) &CustomType);
|
||||
return m;
|
||||
}
|
183
third_party/python/Doc/includes/custom3.c
vendored
Normal file
183
third_party/python/Doc/includes/custom3.c
vendored
Normal file
|
@ -0,0 +1,183 @@
|
|||
#include <Python.h>
|
||||
#include "structmember.h"
|
||||
|
||||
typedef struct {
|
||||
PyObject_HEAD
|
||||
PyObject *first; /* first name */
|
||||
PyObject *last; /* last name */
|
||||
int number;
|
||||
} CustomObject;
|
||||
|
||||
static void
|
||||
Custom_dealloc(CustomObject *self)
|
||||
{
|
||||
Py_XDECREF(self->first);
|
||||
Py_XDECREF(self->last);
|
||||
Py_TYPE(self)->tp_free((PyObject *) self);
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
|
||||
{
|
||||
CustomObject *self;
|
||||
self = (CustomObject *) type->tp_alloc(type, 0);
|
||||
if (self != NULL) {
|
||||
self->first = PyUnicode_FromString("");
|
||||
if (self->first == NULL) {
|
||||
Py_DECREF(self);
|
||||
return NULL;
|
||||
}
|
||||
self->last = PyUnicode_FromString("");
|
||||
if (self->last == NULL) {
|
||||
Py_DECREF(self);
|
||||
return NULL;
|
||||
}
|
||||
self->number = 0;
|
||||
}
|
||||
return (PyObject *) self;
|
||||
}
|
||||
|
||||
static int
|
||||
Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
|
||||
{
|
||||
static char *kwlist[] = {"first", "last", "number", NULL};
|
||||
PyObject *first = NULL, *last = NULL, *tmp;
|
||||
|
||||
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist,
|
||||
&first, &last,
|
||||
&self->number))
|
||||
return -1;
|
||||
|
||||
if (first) {
|
||||
tmp = self->first;
|
||||
Py_INCREF(first);
|
||||
self->first = first;
|
||||
Py_DECREF(tmp);
|
||||
}
|
||||
if (last) {
|
||||
tmp = self->last;
|
||||
Py_INCREF(last);
|
||||
self->last = last;
|
||||
Py_DECREF(tmp);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static PyMemberDef Custom_members[] = {
|
||||
{"number", T_INT, offsetof(CustomObject, number), 0,
|
||||
"custom number"},
|
||||
{NULL} /* Sentinel */
|
||||
};
|
||||
|
||||
static PyObject *
|
||||
Custom_getfirst(CustomObject *self, void *closure)
|
||||
{
|
||||
Py_INCREF(self->first);
|
||||
return self->first;
|
||||
}
|
||||
|
||||
static int
|
||||
Custom_setfirst(CustomObject *self, PyObject *value, void *closure)
|
||||
{
|
||||
PyObject *tmp;
|
||||
if (value == NULL) {
|
||||
PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
|
||||
return -1;
|
||||
}
|
||||
if (!PyUnicode_Check(value)) {
|
||||
PyErr_SetString(PyExc_TypeError,
|
||||
"The first attribute value must be a string");
|
||||
return -1;
|
||||
}
|
||||
tmp = self->first;
|
||||
Py_INCREF(value);
|
||||
self->first = value;
|
||||
Py_DECREF(tmp);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
Custom_getlast(CustomObject *self, void *closure)
|
||||
{
|
||||
Py_INCREF(self->last);
|
||||
return self->last;
|
||||
}
|
||||
|
||||
static int
|
||||
Custom_setlast(CustomObject *self, PyObject *value, void *closure)
|
||||
{
|
||||
PyObject *tmp;
|
||||
if (value == NULL) {
|
||||
PyErr_SetString(PyExc_TypeError, "Cannot delete the last attribute");
|
||||
return -1;
|
||||
}
|
||||
if (!PyUnicode_Check(value)) {
|
||||
PyErr_SetString(PyExc_TypeError,
|
||||
"The last attribute value must be a string");
|
||||
return -1;
|
||||
}
|
||||
tmp = self->last;
|
||||
Py_INCREF(value);
|
||||
self->last = value;
|
||||
Py_DECREF(tmp);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static PyGetSetDef Custom_getsetters[] = {
|
||||
{"first", (getter) Custom_getfirst, (setter) Custom_setfirst,
|
||||
"first name", NULL},
|
||||
{"last", (getter) Custom_getlast, (setter) Custom_setlast,
|
||||
"last name", NULL},
|
||||
{NULL} /* Sentinel */
|
||||
};
|
||||
|
||||
static PyObject *
|
||||
Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))
|
||||
{
|
||||
return PyUnicode_FromFormat("%S %S", self->first, self->last);
|
||||
}
|
||||
|
||||
static PyMethodDef Custom_methods[] = {
|
||||
{"name", (PyCFunction) Custom_name, METH_NOARGS,
|
||||
"Return the name, combining the first and last name"
|
||||
},
|
||||
{NULL} /* Sentinel */
|
||||
};
|
||||
|
||||
static PyTypeObject CustomType = {
|
||||
PyVarObject_HEAD_INIT(NULL, 0)
|
||||
.tp_name = "custom3.Custom",
|
||||
.tp_doc = "Custom objects",
|
||||
.tp_basicsize = sizeof(CustomObject),
|
||||
.tp_itemsize = 0,
|
||||
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
|
||||
.tp_new = Custom_new,
|
||||
.tp_init = (initproc) Custom_init,
|
||||
.tp_dealloc = (destructor) Custom_dealloc,
|
||||
.tp_members = Custom_members,
|
||||
.tp_methods = Custom_methods,
|
||||
.tp_getset = Custom_getsetters,
|
||||
};
|
||||
|
||||
static PyModuleDef custommodule = {
|
||||
PyModuleDef_HEAD_INIT,
|
||||
.m_name = "custom3",
|
||||
.m_doc = "Example module that creates an extension type.",
|
||||
.m_size = -1,
|
||||
};
|
||||
|
||||
PyMODINIT_FUNC
|
||||
PyInit_custom3(void)
|
||||
{
|
||||
PyObject *m;
|
||||
if (PyType_Ready(&CustomType) < 0)
|
||||
return NULL;
|
||||
|
||||
m = PyModule_Create(&custommodule);
|
||||
if (m == NULL)
|
||||
return NULL;
|
||||
|
||||
Py_INCREF(&CustomType);
|
||||
PyModule_AddObject(m, "Custom", (PyObject *) &CustomType);
|
||||
return m;
|
||||
}
|
197
third_party/python/Doc/includes/custom4.c
vendored
Normal file
197
third_party/python/Doc/includes/custom4.c
vendored
Normal file
|
@ -0,0 +1,197 @@
|
|||
#include <Python.h>
|
||||
#include "structmember.h"
|
||||
|
||||
typedef struct {
|
||||
PyObject_HEAD
|
||||
PyObject *first; /* first name */
|
||||
PyObject *last; /* last name */
|
||||
int number;
|
||||
} CustomObject;
|
||||
|
||||
static int
|
||||
Custom_traverse(CustomObject *self, visitproc visit, void *arg)
|
||||
{
|
||||
Py_VISIT(self->first);
|
||||
Py_VISIT(self->last);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
Custom_clear(CustomObject *self)
|
||||
{
|
||||
Py_CLEAR(self->first);
|
||||
Py_CLEAR(self->last);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void
|
||||
Custom_dealloc(CustomObject *self)
|
||||
{
|
||||
PyObject_GC_UnTrack(self);
|
||||
Custom_clear(self);
|
||||
Py_TYPE(self)->tp_free((PyObject *) self);
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
|
||||
{
|
||||
CustomObject *self;
|
||||
self = (CustomObject *) type->tp_alloc(type, 0);
|
||||
if (self != NULL) {
|
||||
self->first = PyUnicode_FromString("");
|
||||
if (self->first == NULL) {
|
||||
Py_DECREF(self);
|
||||
return NULL;
|
||||
}
|
||||
self->last = PyUnicode_FromString("");
|
||||
if (self->last == NULL) {
|
||||
Py_DECREF(self);
|
||||
return NULL;
|
||||
}
|
||||
self->number = 0;
|
||||
}
|
||||
return (PyObject *) self;
|
||||
}
|
||||
|
||||
static int
|
||||
Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
|
||||
{
|
||||
static char *kwlist[] = {"first", "last", "number", NULL};
|
||||
PyObject *first = NULL, *last = NULL, *tmp;
|
||||
|
||||
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist,
|
||||
&first, &last,
|
||||
&self->number))
|
||||
return -1;
|
||||
|
||||
if (first) {
|
||||
tmp = self->first;
|
||||
Py_INCREF(first);
|
||||
self->first = first;
|
||||
Py_DECREF(tmp);
|
||||
}
|
||||
if (last) {
|
||||
tmp = self->last;
|
||||
Py_INCREF(last);
|
||||
self->last = last;
|
||||
Py_DECREF(tmp);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static PyMemberDef Custom_members[] = {
|
||||
{"number", T_INT, offsetof(CustomObject, number), 0,
|
||||
"custom number"},
|
||||
{NULL} /* Sentinel */
|
||||
};
|
||||
|
||||
static PyObject *
|
||||
Custom_getfirst(CustomObject *self, void *closure)
|
||||
{
|
||||
Py_INCREF(self->first);
|
||||
return self->first;
|
||||
}
|
||||
|
||||
static int
|
||||
Custom_setfirst(CustomObject *self, PyObject *value, void *closure)
|
||||
{
|
||||
if (value == NULL) {
|
||||
PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
|
||||
return -1;
|
||||
}
|
||||
if (!PyUnicode_Check(value)) {
|
||||
PyErr_SetString(PyExc_TypeError,
|
||||
"The first attribute value must be a string");
|
||||
return -1;
|
||||
}
|
||||
Py_INCREF(value);
|
||||
Py_CLEAR(self->first);
|
||||
self->first = value;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
Custom_getlast(CustomObject *self, void *closure)
|
||||
{
|
||||
Py_INCREF(self->last);
|
||||
return self->last;
|
||||
}
|
||||
|
||||
static int
|
||||
Custom_setlast(CustomObject *self, PyObject *value, void *closure)
|
||||
{
|
||||
if (value == NULL) {
|
||||
PyErr_SetString(PyExc_TypeError, "Cannot delete the last attribute");
|
||||
return -1;
|
||||
}
|
||||
if (!PyUnicode_Check(value)) {
|
||||
PyErr_SetString(PyExc_TypeError,
|
||||
"The last attribute value must be a string");
|
||||
return -1;
|
||||
}
|
||||
Py_INCREF(value);
|
||||
Py_CLEAR(self->last);
|
||||
self->last = value;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static PyGetSetDef Custom_getsetters[] = {
|
||||
{"first", (getter) Custom_getfirst, (setter) Custom_setfirst,
|
||||
"first name", NULL},
|
||||
{"last", (getter) Custom_getlast, (setter) Custom_setlast,
|
||||
"last name", NULL},
|
||||
{NULL} /* Sentinel */
|
||||
};
|
||||
|
||||
static PyObject *
|
||||
Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))
|
||||
{
|
||||
return PyUnicode_FromFormat("%S %S", self->first, self->last);
|
||||
}
|
||||
|
||||
static PyMethodDef Custom_methods[] = {
|
||||
{"name", (PyCFunction) Custom_name, METH_NOARGS,
|
||||
"Return the name, combining the first and last name"
|
||||
},
|
||||
{NULL} /* Sentinel */
|
||||
};
|
||||
|
||||
static PyTypeObject CustomType = {
|
||||
PyVarObject_HEAD_INIT(NULL, 0)
|
||||
.tp_name = "custom4.Custom",
|
||||
.tp_doc = "Custom objects",
|
||||
.tp_basicsize = sizeof(CustomObject),
|
||||
.tp_itemsize = 0,
|
||||
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
|
||||
.tp_new = Custom_new,
|
||||
.tp_init = (initproc) Custom_init,
|
||||
.tp_dealloc = (destructor) Custom_dealloc,
|
||||
.tp_traverse = (traverseproc) Custom_traverse,
|
||||
.tp_clear = (inquiry) Custom_clear,
|
||||
.tp_members = Custom_members,
|
||||
.tp_methods = Custom_methods,
|
||||
.tp_getset = Custom_getsetters,
|
||||
};
|
||||
|
||||
static PyModuleDef custommodule = {
|
||||
PyModuleDef_HEAD_INIT,
|
||||
.m_name = "custom4",
|
||||
.m_doc = "Example module that creates an extension type.",
|
||||
.m_size = -1,
|
||||
};
|
||||
|
||||
PyMODINIT_FUNC
|
||||
PyInit_custom4(void)
|
||||
{
|
||||
PyObject *m;
|
||||
if (PyType_Ready(&CustomType) < 0)
|
||||
return NULL;
|
||||
|
||||
m = PyModule_Create(&custommodule);
|
||||
if (m == NULL)
|
||||
return NULL;
|
||||
|
||||
Py_INCREF(&CustomType);
|
||||
PyModule_AddObject(m, "Custom", (PyObject *) &CustomType);
|
||||
return m;
|
||||
}
|
87
third_party/python/Doc/includes/dbpickle.py
vendored
Normal file
87
third_party/python/Doc/includes/dbpickle.py
vendored
Normal file
|
@ -0,0 +1,87 @@
|
|||
# Simple example presenting how persistent ID can be used to pickle
|
||||
# external objects by reference.
|
||||
|
||||
import pickle
|
||||
import sqlite3
|
||||
from collections import namedtuple
|
||||
|
||||
# Simple class representing a record in our database.
|
||||
MemoRecord = namedtuple("MemoRecord", "key, task")
|
||||
|
||||
class DBPickler(pickle.Pickler):
|
||||
|
||||
def persistent_id(self, obj):
|
||||
# Instead of pickling MemoRecord as a regular class instance, we emit a
|
||||
# persistent ID.
|
||||
if isinstance(obj, MemoRecord):
|
||||
# Here, our persistent ID is simply a tuple, containing a tag and a
|
||||
# key, which refers to a specific record in the database.
|
||||
return ("MemoRecord", obj.key)
|
||||
else:
|
||||
# If obj does not have a persistent ID, return None. This means obj
|
||||
# needs to be pickled as usual.
|
||||
return None
|
||||
|
||||
|
||||
class DBUnpickler(pickle.Unpickler):
|
||||
|
||||
def __init__(self, file, connection):
|
||||
super().__init__(file)
|
||||
self.connection = connection
|
||||
|
||||
def persistent_load(self, pid):
|
||||
# This method is invoked whenever a persistent ID is encountered.
|
||||
# Here, pid is the tuple returned by DBPickler.
|
||||
cursor = self.connection.cursor()
|
||||
type_tag, key_id = pid
|
||||
if type_tag == "MemoRecord":
|
||||
# Fetch the referenced record from the database and return it.
|
||||
cursor.execute("SELECT * FROM memos WHERE key=?", (str(key_id),))
|
||||
key, task = cursor.fetchone()
|
||||
return MemoRecord(key, task)
|
||||
else:
|
||||
# Always raises an error if you cannot return the correct object.
|
||||
# Otherwise, the unpickler will think None is the object referenced
|
||||
# by the persistent ID.
|
||||
raise pickle.UnpicklingError("unsupported persistent object")
|
||||
|
||||
|
||||
def main():
|
||||
import io
|
||||
import pprint
|
||||
|
||||
# Initialize and populate our database.
|
||||
conn = sqlite3.connect(":memory:")
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("CREATE TABLE memos(key INTEGER PRIMARY KEY, task TEXT)")
|
||||
tasks = (
|
||||
'give food to fish',
|
||||
'prepare group meeting',
|
||||
'fight with a zebra',
|
||||
)
|
||||
for task in tasks:
|
||||
cursor.execute("INSERT INTO memos VALUES(NULL, ?)", (task,))
|
||||
|
||||
# Fetch the records to be pickled.
|
||||
cursor.execute("SELECT * FROM memos")
|
||||
memos = [MemoRecord(key, task) for key, task in cursor]
|
||||
# Save the records using our custom DBPickler.
|
||||
file = io.BytesIO()
|
||||
DBPickler(file).dump(memos)
|
||||
|
||||
print("Pickled records:")
|
||||
pprint.pprint(memos)
|
||||
|
||||
# Update a record, just for good measure.
|
||||
cursor.execute("UPDATE memos SET task='learn italian' WHERE key=1")
|
||||
|
||||
# Load the records from the pickle data stream.
|
||||
file.seek(0)
|
||||
memos = DBUnpickler(file, conn).load()
|
||||
|
||||
print("Unpickled records:")
|
||||
pprint.pprint(memos)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
56
third_party/python/Doc/includes/email-alternative.py
vendored
Normal file
56
third_party/python/Doc/includes/email-alternative.py
vendored
Normal file
|
@ -0,0 +1,56 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
import smtplib
|
||||
|
||||
from email.message import EmailMessage
|
||||
from email.headerregistry import Address
|
||||
from email.utils import make_msgid
|
||||
|
||||
# Create the base text message.
|
||||
msg = EmailMessage()
|
||||
msg['Subject'] = "Ayons asperges pour le déjeuner"
|
||||
msg['From'] = Address("Pepé Le Pew", "pepe", "example.com")
|
||||
msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"),
|
||||
Address("Fabrette Pussycat", "fabrette", "example.com"))
|
||||
msg.set_content("""\
|
||||
Salut!
|
||||
|
||||
Cela ressemble à un excellent recipie[1] déjeuner.
|
||||
|
||||
[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718
|
||||
|
||||
--Pepé
|
||||
""")
|
||||
|
||||
# Add the html version. This converts the message into a multipart/alternative
|
||||
# container, with the original text message as the first part and the new html
|
||||
# message as the second part.
|
||||
asparagus_cid = make_msgid()
|
||||
msg.add_alternative("""\
|
||||
<html>
|
||||
<head></head>
|
||||
<body>
|
||||
<p>Salut!</p>
|
||||
<p>Cela ressemble à un excellent
|
||||
<a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718">
|
||||
recipie
|
||||
</a> déjeuner.
|
||||
</p>
|
||||
<img src="cid:{asparagus_cid}" />
|
||||
</body>
|
||||
</html>
|
||||
""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
|
||||
# note that we needed to peel the <> off the msgid for use in the html.
|
||||
|
||||
# Now add the related image to the html part.
|
||||
with open("roasted-asparagus.jpg", 'rb') as img:
|
||||
msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
|
||||
cid=asparagus_cid)
|
||||
|
||||
# Make a local copy of what we are going to send.
|
||||
with open('outgoing.msg', 'wb') as f:
|
||||
f.write(bytes(msg))
|
||||
|
||||
# Send the message via local SMTP server.
|
||||
with smtplib.SMTP('localhost') as s:
|
||||
s.send_message(msg)
|
77
third_party/python/Doc/includes/email-dir.py
vendored
Normal file
77
third_party/python/Doc/includes/email-dir.py
vendored
Normal file
|
@ -0,0 +1,77 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
"""Send the contents of a directory as a MIME message."""
|
||||
|
||||
import os
|
||||
import smtplib
|
||||
# For guessing MIME type based on file name extension
|
||||
import mimetypes
|
||||
|
||||
from argparse import ArgumentParser
|
||||
|
||||
from email.message import EmailMessage
|
||||
from email.policy import SMTP
|
||||
|
||||
|
||||
def main():
|
||||
parser = ArgumentParser(description="""\
|
||||
Send the contents of a directory as a MIME message.
|
||||
Unless the -o option is given, the email is sent by forwarding to your local
|
||||
SMTP server, which then does the normal delivery process. Your local machine
|
||||
must be running an SMTP server.
|
||||
""")
|
||||
parser.add_argument('-d', '--directory',
|
||||
help="""Mail the contents of the specified directory,
|
||||
otherwise use the current directory. Only the regular
|
||||
files in the directory are sent, and we don't recurse to
|
||||
subdirectories.""")
|
||||
parser.add_argument('-o', '--output',
|
||||
metavar='FILE',
|
||||
help="""Print the composed message to FILE instead of
|
||||
sending the message to the SMTP server.""")
|
||||
parser.add_argument('-s', '--sender', required=True,
|
||||
help='The value of the From: header (required)')
|
||||
parser.add_argument('-r', '--recipient', required=True,
|
||||
action='append', metavar='RECIPIENT',
|
||||
default=[], dest='recipients',
|
||||
help='A To: header value (at least one required)')
|
||||
args = parser.parse_args()
|
||||
directory = args.directory
|
||||
if not directory:
|
||||
directory = '.'
|
||||
# Create the message
|
||||
msg = EmailMessage()
|
||||
msg['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
|
||||
msg['To'] = ', '.join(args.recipients)
|
||||
msg['From'] = args.sender
|
||||
msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'
|
||||
|
||||
for filename in os.listdir(directory):
|
||||
path = os.path.join(directory, filename)
|
||||
if not os.path.isfile(path):
|
||||
continue
|
||||
# Guess the content type based on the file's extension. Encoding
|
||||
# will be ignored, although we should check for simple things like
|
||||
# gzip'd or compressed files.
|
||||
ctype, encoding = mimetypes.guess_type(path)
|
||||
if ctype is None or encoding is not None:
|
||||
# No guess could be made, or the file is encoded (compressed), so
|
||||
# use a generic bag-of-bits type.
|
||||
ctype = 'application/octet-stream'
|
||||
maintype, subtype = ctype.split('/', 1)
|
||||
with open(path, 'rb') as fp:
|
||||
msg.add_attachment(fp.read(),
|
||||
maintype=maintype,
|
||||
subtype=subtype,
|
||||
filename=filename)
|
||||
# Now send or store the message
|
||||
if args.output:
|
||||
with open(args.output, 'wb') as fp:
|
||||
fp.write(msg.as_bytes(policy=SMTP))
|
||||
else:
|
||||
with smtplib.SMTP('localhost') as s:
|
||||
s.send_message(msg)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
24
third_party/python/Doc/includes/email-headers.py
vendored
Normal file
24
third_party/python/Doc/includes/email-headers.py
vendored
Normal file
|
@ -0,0 +1,24 @@
|
|||
# Import the email modules we'll need
|
||||
from email.parser import BytesParser, Parser
|
||||
from email.policy import default
|
||||
|
||||
# If the e-mail headers are in a file, uncomment these two lines:
|
||||
# with open(messagefile, 'rb') as fp:
|
||||
# headers = BytesParser(policy=default).parse(fp)
|
||||
|
||||
# Or for parsing headers in a string (this is an uncommon operation), use:
|
||||
headers = Parser(policy=default).parsestr(
|
||||
'From: Foo Bar <user@example.com>\n'
|
||||
'To: <someone_else@example.com>\n'
|
||||
'Subject: Test message\n'
|
||||
'\n'
|
||||
'Body would go here\n')
|
||||
|
||||
# Now the header items can be accessed as a dictionary:
|
||||
print('To: {}'.format(headers['to']))
|
||||
print('From: {}'.format(headers['from']))
|
||||
print('Subject: {}'.format(headers['subject']))
|
||||
|
||||
# You can also access the parts of the addresses:
|
||||
print('Recipient username: {}'.format(headers['to'].addresses[0].username))
|
||||
print('Sender name: {}'.format(headers['from'].addresses[0].display_name))
|
29
third_party/python/Doc/includes/email-mime.py
vendored
Normal file
29
third_party/python/Doc/includes/email-mime.py
vendored
Normal file
|
@ -0,0 +1,29 @@
|
|||
# Import smtplib for the actual sending function
|
||||
import smtplib
|
||||
|
||||
# And imghdr to find the types of our images
|
||||
import imghdr
|
||||
|
||||
# Here are the email package modules we'll need
|
||||
from email.message import EmailMessage
|
||||
|
||||
# Create the container email message.
|
||||
msg = EmailMessage()
|
||||
msg['Subject'] = 'Our family reunion'
|
||||
# me == the sender's email address
|
||||
# family = the list of all recipients' email addresses
|
||||
msg['From'] = me
|
||||
msg['To'] = ', '.join(family)
|
||||
msg.preamble = 'Our family reunion'
|
||||
|
||||
# Open the files in binary mode. Use imghdr to figure out the
|
||||
# MIME subtype for each specific image.
|
||||
for file in pngfiles:
|
||||
with open(file, 'rb') as fp:
|
||||
img_data = fp.read()
|
||||
msg.add_attachment(img_data, maintype='image',
|
||||
subtype=imghdr.what(None, img_data))
|
||||
|
||||
# Send the email via our own SMTP server.
|
||||
with smtplib.SMTP('localhost') as s:
|
||||
s.send_message(msg)
|
75
third_party/python/Doc/includes/email-read-alternative.py
vendored
Normal file
75
third_party/python/Doc/includes/email-read-alternative.py
vendored
Normal file
|
@ -0,0 +1,75 @@
|
|||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import mimetypes
|
||||
import webbrowser
|
||||
|
||||
# Import the email modules we'll need
|
||||
from email import policy
|
||||
from email.parser import BytesParser
|
||||
|
||||
# An imaginary module that would make this work and be safe.
|
||||
from imaginary import magic_html_parser
|
||||
|
||||
# In a real program you'd get the filename from the arguments.
|
||||
with open('outgoing.msg', 'rb') as fp:
|
||||
msg = BytesParser(policy=policy.default).parse(fp)
|
||||
|
||||
# Now the header items can be accessed as a dictionary, and any non-ASCII will
|
||||
# be converted to unicode:
|
||||
print('To:', msg['to'])
|
||||
print('From:', msg['from'])
|
||||
print('Subject:', msg['subject'])
|
||||
|
||||
# If we want to print a preview of the message content, we can extract whatever
|
||||
# the least formatted payload is and print the first three lines. Of course,
|
||||
# if the message has no plain text part printing the first three lines of html
|
||||
# is probably useless, but this is just a conceptual example.
|
||||
simplest = msg.get_body(preferencelist=('plain', 'html'))
|
||||
print()
|
||||
print(''.join(simplest.get_content().splitlines(keepends=True)[:3]))
|
||||
|
||||
ans = input("View full message?")
|
||||
if ans.lower()[0] == 'n':
|
||||
sys.exit()
|
||||
|
||||
# We can extract the richest alternative in order to display it:
|
||||
richest = msg.get_body()
|
||||
partfiles = {}
|
||||
if richest['content-type'].maintype == 'text':
|
||||
if richest['content-type'].subtype == 'plain':
|
||||
for line in richest.get_content().splitlines():
|
||||
print(line)
|
||||
sys.exit()
|
||||
elif richest['content-type'].subtype == 'html':
|
||||
body = richest
|
||||
else:
|
||||
print("Don't know how to display {}".format(richest.get_content_type()))
|
||||
sys.exit()
|
||||
elif richest['content-type'].content_type == 'multipart/related':
|
||||
body = richest.get_body(preferencelist=('html'))
|
||||
for part in richest.iter_attachments():
|
||||
fn = part.get_filename()
|
||||
if fn:
|
||||
extension = os.path.splitext(part.get_filename())[1]
|
||||
else:
|
||||
extension = mimetypes.guess_extension(part.get_content_type())
|
||||
with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as f:
|
||||
f.write(part.get_content())
|
||||
# again strip the <> to go from email form of cid to html form.
|
||||
partfiles[part['content-id'][1:-1]] = f.name
|
||||
else:
|
||||
print("Don't know how to display {}".format(richest.get_content_type()))
|
||||
sys.exit()
|
||||
with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
|
||||
# The magic_html_parser has to rewrite the href="cid:...." attributes to
|
||||
# point to the filenames in partfiles. It also has to do a safety-sanitize
|
||||
# of the html. It could be written using html.parser.
|
||||
f.write(magic_html_parser(body.get_content(), partfiles))
|
||||
webbrowser.open(f.name)
|
||||
os.remove(f.name)
|
||||
for fn in partfiles.values():
|
||||
os.remove(fn)
|
||||
|
||||
# Of course, there are lots of email messages that could break this simple
|
||||
# minded program, but it will handle the most common ones.
|
22
third_party/python/Doc/includes/email-simple.py
vendored
Normal file
22
third_party/python/Doc/includes/email-simple.py
vendored
Normal file
|
@ -0,0 +1,22 @@
|
|||
# Import smtplib for the actual sending function
|
||||
import smtplib
|
||||
|
||||
# Import the email modules we'll need
|
||||
from email.message import EmailMessage
|
||||
|
||||
# Open the plain text file whose name is in textfile for reading.
|
||||
with open(textfile) as fp:
|
||||
# Create a text/plain message
|
||||
msg = EmailMessage()
|
||||
msg.set_content(fp.read())
|
||||
|
||||
# me == the sender's email address
|
||||
# you == the recipient's email address
|
||||
msg['Subject'] = 'The contents of %s' % textfile
|
||||
msg['From'] = me
|
||||
msg['To'] = you
|
||||
|
||||
# Send the message via our own SMTP server.
|
||||
s = smtplib.SMTP('localhost')
|
||||
s.send_message(msg)
|
||||
s.quit()
|
53
third_party/python/Doc/includes/email-unpack.py
vendored
Normal file
53
third_party/python/Doc/includes/email-unpack.py
vendored
Normal file
|
@ -0,0 +1,53 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
"""Unpack a MIME message into a directory of files."""
|
||||
|
||||
import os
|
||||
import email
|
||||
import mimetypes
|
||||
|
||||
from email.policy import default
|
||||
|
||||
from argparse import ArgumentParser
|
||||
|
||||
|
||||
def main():
|
||||
parser = ArgumentParser(description="""\
|
||||
Unpack a MIME message into a directory of files.
|
||||
""")
|
||||
parser.add_argument('-d', '--directory', required=True,
|
||||
help="""Unpack the MIME message into the named
|
||||
directory, which will be created if it doesn't already
|
||||
exist.""")
|
||||
parser.add_argument('msgfile')
|
||||
args = parser.parse_args()
|
||||
|
||||
with open(args.msgfile, 'rb') as fp:
|
||||
msg = email.message_from_binary_file(fp, policy=default)
|
||||
|
||||
try:
|
||||
os.mkdir(args.directory)
|
||||
except FileExistsError:
|
||||
pass
|
||||
|
||||
counter = 1
|
||||
for part in msg.walk():
|
||||
# multipart/* are just containers
|
||||
if part.get_content_maintype() == 'multipart':
|
||||
continue
|
||||
# Applications should really sanitize the given filename so that an
|
||||
# email message can't be used to overwrite important files
|
||||
filename = part.get_filename()
|
||||
if not filename:
|
||||
ext = mimetypes.guess_extension(part.get_content_type())
|
||||
if not ext:
|
||||
# Use a generic bag-of-bits extension
|
||||
ext = '.bin'
|
||||
filename = 'part-%03d%s' % (counter, ext)
|
||||
counter += 1
|
||||
with open(os.path.join(args.directory, filename), 'wb') as fp:
|
||||
fp.write(part.get_payload(decode=True))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
64
third_party/python/Doc/includes/minidom-example.py
vendored
Normal file
64
third_party/python/Doc/includes/minidom-example.py
vendored
Normal file
|
@ -0,0 +1,64 @@
|
|||
import xml.dom.minidom
|
||||
|
||||
document = """\
|
||||
<slideshow>
|
||||
<title>Demo slideshow</title>
|
||||
<slide><title>Slide title</title>
|
||||
<point>This is a demo</point>
|
||||
<point>Of a program for processing slides</point>
|
||||
</slide>
|
||||
|
||||
<slide><title>Another demo slide</title>
|
||||
<point>It is important</point>
|
||||
<point>To have more than</point>
|
||||
<point>one slide</point>
|
||||
</slide>
|
||||
</slideshow>
|
||||
"""
|
||||
|
||||
dom = xml.dom.minidom.parseString(document)
|
||||
|
||||
def getText(nodelist):
|
||||
rc = []
|
||||
for node in nodelist:
|
||||
if node.nodeType == node.TEXT_NODE:
|
||||
rc.append(node.data)
|
||||
return ''.join(rc)
|
||||
|
||||
def handleSlideshow(slideshow):
|
||||
print("<html>")
|
||||
handleSlideshowTitle(slideshow.getElementsByTagName("title")[0])
|
||||
slides = slideshow.getElementsByTagName("slide")
|
||||
handleToc(slides)
|
||||
handleSlides(slides)
|
||||
print("</html>")
|
||||
|
||||
def handleSlides(slides):
|
||||
for slide in slides:
|
||||
handleSlide(slide)
|
||||
|
||||
def handleSlide(slide):
|
||||
handleSlideTitle(slide.getElementsByTagName("title")[0])
|
||||
handlePoints(slide.getElementsByTagName("point"))
|
||||
|
||||
def handleSlideshowTitle(title):
|
||||
print("<title>%s</title>" % getText(title.childNodes))
|
||||
|
||||
def handleSlideTitle(title):
|
||||
print("<h2>%s</h2>" % getText(title.childNodes))
|
||||
|
||||
def handlePoints(points):
|
||||
print("<ul>")
|
||||
for point in points:
|
||||
handlePoint(point)
|
||||
print("</ul>")
|
||||
|
||||
def handlePoint(point):
|
||||
print("<li>%s</li>" % getText(point.childNodes))
|
||||
|
||||
def handleToc(slides):
|
||||
for slide in slides:
|
||||
title = slide.getElementsByTagName("title")[0]
|
||||
print("<p>%s</p>" % getText(title.childNodes))
|
||||
|
||||
handleSlideshow(dom)
|
89
third_party/python/Doc/includes/mp_newtype.py
vendored
Normal file
89
third_party/python/Doc/includes/mp_newtype.py
vendored
Normal file
|
@ -0,0 +1,89 @@
|
|||
from multiprocessing import freeze_support
|
||||
from multiprocessing.managers import BaseManager, BaseProxy
|
||||
import operator
|
||||
|
||||
##
|
||||
|
||||
class Foo:
|
||||
def f(self):
|
||||
print('you called Foo.f()')
|
||||
def g(self):
|
||||
print('you called Foo.g()')
|
||||
def _h(self):
|
||||
print('you called Foo._h()')
|
||||
|
||||
# A simple generator function
|
||||
def baz():
|
||||
for i in range(10):
|
||||
yield i*i
|
||||
|
||||
# Proxy type for generator objects
|
||||
class GeneratorProxy(BaseProxy):
|
||||
_exposed_ = ['__next__']
|
||||
def __iter__(self):
|
||||
return self
|
||||
def __next__(self):
|
||||
return self._callmethod('__next__')
|
||||
|
||||
# Function to return the operator module
|
||||
def get_operator_module():
|
||||
return operator
|
||||
|
||||
##
|
||||
|
||||
class MyManager(BaseManager):
|
||||
pass
|
||||
|
||||
# register the Foo class; make `f()` and `g()` accessible via proxy
|
||||
MyManager.register('Foo1', Foo)
|
||||
|
||||
# register the Foo class; make `g()` and `_h()` accessible via proxy
|
||||
MyManager.register('Foo2', Foo, exposed=('g', '_h'))
|
||||
|
||||
# register the generator function baz; use `GeneratorProxy` to make proxies
|
||||
MyManager.register('baz', baz, proxytype=GeneratorProxy)
|
||||
|
||||
# register get_operator_module(); make public functions accessible via proxy
|
||||
MyManager.register('operator', get_operator_module)
|
||||
|
||||
##
|
||||
|
||||
def test():
|
||||
manager = MyManager()
|
||||
manager.start()
|
||||
|
||||
print('-' * 20)
|
||||
|
||||
f1 = manager.Foo1()
|
||||
f1.f()
|
||||
f1.g()
|
||||
assert not hasattr(f1, '_h')
|
||||
assert sorted(f1._exposed_) == sorted(['f', 'g'])
|
||||
|
||||
print('-' * 20)
|
||||
|
||||
f2 = manager.Foo2()
|
||||
f2.g()
|
||||
f2._h()
|
||||
assert not hasattr(f2, 'f')
|
||||
assert sorted(f2._exposed_) == sorted(['g', '_h'])
|
||||
|
||||
print('-' * 20)
|
||||
|
||||
it = manager.baz()
|
||||
for i in it:
|
||||
print('<%d>' % i, end=' ')
|
||||
print()
|
||||
|
||||
print('-' * 20)
|
||||
|
||||
op = manager.operator()
|
||||
print('op.add(23, 45) =', op.add(23, 45))
|
||||
print('op.pow(2, 94) =', op.pow(2, 94))
|
||||
print('op._exposed_ =', op._exposed_)
|
||||
|
||||
##
|
||||
|
||||
if __name__ == '__main__':
|
||||
freeze_support()
|
||||
test()
|
153
third_party/python/Doc/includes/mp_pool.py
vendored
Normal file
153
third_party/python/Doc/includes/mp_pool.py
vendored
Normal file
|
@ -0,0 +1,153 @@
|
|||
import multiprocessing
|
||||
import time
|
||||
import random
|
||||
import sys
|
||||
|
||||
#
|
||||
# Functions used by test code
|
||||
#
|
||||
|
||||
def calculate(func, args):
|
||||
result = func(*args)
|
||||
return '%s says that %s%s = %s' % (
|
||||
multiprocessing.current_process().name,
|
||||
func.__name__, args, result
|
||||
)
|
||||
|
||||
def calculatestar(args):
|
||||
return calculate(*args)
|
||||
|
||||
def mul(a, b):
|
||||
time.sleep(0.5 * random.random())
|
||||
return a * b
|
||||
|
||||
def plus(a, b):
|
||||
time.sleep(0.5 * random.random())
|
||||
return a + b
|
||||
|
||||
def f(x):
|
||||
return 1.0 / (x - 5.0)
|
||||
|
||||
def pow3(x):
|
||||
return x ** 3
|
||||
|
||||
def noop(x):
|
||||
pass
|
||||
|
||||
#
|
||||
# Test code
|
||||
#
|
||||
|
||||
def test():
|
||||
PROCESSES = 4
|
||||
print('Creating pool with %d processes\n' % PROCESSES)
|
||||
|
||||
with multiprocessing.Pool(PROCESSES) as pool:
|
||||
#
|
||||
# Tests
|
||||
#
|
||||
|
||||
TASKS = [(mul, (i, 7)) for i in range(10)] + \
|
||||
[(plus, (i, 8)) for i in range(10)]
|
||||
|
||||
results = [pool.apply_async(calculate, t) for t in TASKS]
|
||||
imap_it = pool.imap(calculatestar, TASKS)
|
||||
imap_unordered_it = pool.imap_unordered(calculatestar, TASKS)
|
||||
|
||||
print('Ordered results using pool.apply_async():')
|
||||
for r in results:
|
||||
print('\t', r.get())
|
||||
print()
|
||||
|
||||
print('Ordered results using pool.imap():')
|
||||
for x in imap_it:
|
||||
print('\t', x)
|
||||
print()
|
||||
|
||||
print('Unordered results using pool.imap_unordered():')
|
||||
for x in imap_unordered_it:
|
||||
print('\t', x)
|
||||
print()
|
||||
|
||||
print('Ordered results using pool.map() --- will block till complete:')
|
||||
for x in pool.map(calculatestar, TASKS):
|
||||
print('\t', x)
|
||||
print()
|
||||
|
||||
#
|
||||
# Test error handling
|
||||
#
|
||||
|
||||
print('Testing error handling:')
|
||||
|
||||
try:
|
||||
print(pool.apply(f, (5,)))
|
||||
except ZeroDivisionError:
|
||||
print('\tGot ZeroDivisionError as expected from pool.apply()')
|
||||
else:
|
||||
raise AssertionError('expected ZeroDivisionError')
|
||||
|
||||
try:
|
||||
print(pool.map(f, list(range(10))))
|
||||
except ZeroDivisionError:
|
||||
print('\tGot ZeroDivisionError as expected from pool.map()')
|
||||
else:
|
||||
raise AssertionError('expected ZeroDivisionError')
|
||||
|
||||
try:
|
||||
print(list(pool.imap(f, list(range(10)))))
|
||||
except ZeroDivisionError:
|
||||
print('\tGot ZeroDivisionError as expected from list(pool.imap())')
|
||||
else:
|
||||
raise AssertionError('expected ZeroDivisionError')
|
||||
|
||||
it = pool.imap(f, list(range(10)))
|
||||
for i in range(10):
|
||||
try:
|
||||
x = next(it)
|
||||
except ZeroDivisionError:
|
||||
if i == 5:
|
||||
pass
|
||||
except StopIteration:
|
||||
break
|
||||
else:
|
||||
if i == 5:
|
||||
raise AssertionError('expected ZeroDivisionError')
|
||||
|
||||
assert i == 9
|
||||
print('\tGot ZeroDivisionError as expected from IMapIterator.next()')
|
||||
print()
|
||||
|
||||
#
|
||||
# Testing timeouts
|
||||
#
|
||||
|
||||
print('Testing ApplyResult.get() with timeout:', end=' ')
|
||||
res = pool.apply_async(calculate, TASKS[0])
|
||||
while 1:
|
||||
sys.stdout.flush()
|
||||
try:
|
||||
sys.stdout.write('\n\t%s' % res.get(0.02))
|
||||
break
|
||||
except multiprocessing.TimeoutError:
|
||||
sys.stdout.write('.')
|
||||
print()
|
||||
print()
|
||||
|
||||
print('Testing IMapIterator.next() with timeout:', end=' ')
|
||||
it = pool.imap(calculatestar, TASKS)
|
||||
while 1:
|
||||
sys.stdout.flush()
|
||||
try:
|
||||
sys.stdout.write('\n\t%s' % it.next(0.02))
|
||||
except StopIteration:
|
||||
break
|
||||
except multiprocessing.TimeoutError:
|
||||
sys.stdout.write('.')
|
||||
print()
|
||||
print()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
multiprocessing.freeze_support()
|
||||
test()
|
77
third_party/python/Doc/includes/mp_workers.py
vendored
Normal file
77
third_party/python/Doc/includes/mp_workers.py
vendored
Normal file
|
@ -0,0 +1,77 @@
|
|||
import time
|
||||
import random
|
||||
|
||||
from multiprocessing import Process, Queue, current_process, freeze_support
|
||||
|
||||
#
|
||||
# Function run by worker processes
|
||||
#
|
||||
|
||||
def worker(input, output):
|
||||
for func, args in iter(input.get, 'STOP'):
|
||||
result = calculate(func, args)
|
||||
output.put(result)
|
||||
|
||||
#
|
||||
# Function used to calculate result
|
||||
#
|
||||
|
||||
def calculate(func, args):
|
||||
result = func(*args)
|
||||
return '%s says that %s%s = %s' % \
|
||||
(current_process().name, func.__name__, args, result)
|
||||
|
||||
#
|
||||
# Functions referenced by tasks
|
||||
#
|
||||
|
||||
def mul(a, b):
|
||||
time.sleep(0.5*random.random())
|
||||
return a * b
|
||||
|
||||
def plus(a, b):
|
||||
time.sleep(0.5*random.random())
|
||||
return a + b
|
||||
|
||||
#
|
||||
#
|
||||
#
|
||||
|
||||
def test():
|
||||
NUMBER_OF_PROCESSES = 4
|
||||
TASKS1 = [(mul, (i, 7)) for i in range(20)]
|
||||
TASKS2 = [(plus, (i, 8)) for i in range(10)]
|
||||
|
||||
# Create queues
|
||||
task_queue = Queue()
|
||||
done_queue = Queue()
|
||||
|
||||
# Submit tasks
|
||||
for task in TASKS1:
|
||||
task_queue.put(task)
|
||||
|
||||
# Start worker processes
|
||||
for i in range(NUMBER_OF_PROCESSES):
|
||||
Process(target=worker, args=(task_queue, done_queue)).start()
|
||||
|
||||
# Get and print results
|
||||
print('Unordered results:')
|
||||
for i in range(len(TASKS1)):
|
||||
print('\t', done_queue.get())
|
||||
|
||||
# Add more tasks using `put()`
|
||||
for task in TASKS2:
|
||||
task_queue.put(task)
|
||||
|
||||
# Get and print some more results
|
||||
for i in range(len(TASKS2)):
|
||||
print('\t', done_queue.get())
|
||||
|
||||
# Tell child processes to stop
|
||||
for i in range(NUMBER_OF_PROCESSES):
|
||||
task_queue.put('STOP')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
freeze_support()
|
||||
test()
|
70
third_party/python/Doc/includes/run-func.c
vendored
Normal file
70
third_party/python/Doc/includes/run-func.c
vendored
Normal file
|
@ -0,0 +1,70 @@
|
|||
#include <Python.h>
|
||||
|
||||
int
|
||||
main(int argc, char *argv[])
|
||||
{
|
||||
PyObject *pName, *pModule, *pFunc;
|
||||
PyObject *pArgs, *pValue;
|
||||
int i;
|
||||
|
||||
if (argc < 3) {
|
||||
fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
Py_Initialize();
|
||||
pName = PyUnicode_DecodeFSDefault(argv[1]);
|
||||
/* Error checking of pName left out */
|
||||
|
||||
pModule = PyImport_Import(pName);
|
||||
Py_DECREF(pName);
|
||||
|
||||
if (pModule != NULL) {
|
||||
pFunc = PyObject_GetAttrString(pModule, argv[2]);
|
||||
/* pFunc is a new reference */
|
||||
|
||||
if (pFunc && PyCallable_Check(pFunc)) {
|
||||
pArgs = PyTuple_New(argc - 3);
|
||||
for (i = 0; i < argc - 3; ++i) {
|
||||
pValue = PyLong_FromLong(atoi(argv[i + 3]));
|
||||
if (!pValue) {
|
||||
Py_DECREF(pArgs);
|
||||
Py_DECREF(pModule);
|
||||
fprintf(stderr, "Cannot convert argument\n");
|
||||
return 1;
|
||||
}
|
||||
/* pValue reference stolen here: */
|
||||
PyTuple_SetItem(pArgs, i, pValue);
|
||||
}
|
||||
pValue = PyObject_CallObject(pFunc, pArgs);
|
||||
Py_DECREF(pArgs);
|
||||
if (pValue != NULL) {
|
||||
printf("Result of call: %ld\n", PyLong_AsLong(pValue));
|
||||
Py_DECREF(pValue);
|
||||
}
|
||||
else {
|
||||
Py_DECREF(pFunc);
|
||||
Py_DECREF(pModule);
|
||||
PyErr_Print();
|
||||
fprintf(stderr,"Call failed\n");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (PyErr_Occurred())
|
||||
PyErr_Print();
|
||||
fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
|
||||
}
|
||||
Py_XDECREF(pFunc);
|
||||
Py_DECREF(pModule);
|
||||
}
|
||||
else {
|
||||
PyErr_Print();
|
||||
fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
|
||||
return 1;
|
||||
}
|
||||
if (Py_FinalizeEx() < 0) {
|
||||
return 120;
|
||||
}
|
||||
return 0;
|
||||
}
|
9
third_party/python/Doc/includes/setup.py
vendored
Normal file
9
third_party/python/Doc/includes/setup.py
vendored
Normal file
|
@ -0,0 +1,9 @@
|
|||
from distutils.core import setup, Extension
|
||||
setup(name="noddy", version="1.0",
|
||||
ext_modules=[
|
||||
Extension("noddy", ["noddy.c"]),
|
||||
Extension("noddy2", ["noddy2.c"]),
|
||||
Extension("noddy3", ["noddy3.c"]),
|
||||
Extension("noddy4", ["noddy4.c"]),
|
||||
Extension("shoddy", ["shoddy.c"]),
|
||||
])
|
15
third_party/python/Doc/includes/sqlite3/adapter_datetime.py
vendored
Normal file
15
third_party/python/Doc/includes/sqlite3/adapter_datetime.py
vendored
Normal file
|
@ -0,0 +1,15 @@
|
|||
import sqlite3
|
||||
import datetime
|
||||
import time
|
||||
|
||||
def adapt_datetime(ts):
|
||||
return time.mktime(ts.timetuple())
|
||||
|
||||
sqlite3.register_adapter(datetime.datetime, adapt_datetime)
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
cur = con.cursor()
|
||||
|
||||
now = datetime.datetime.now()
|
||||
cur.execute("select ?", (now,))
|
||||
print(cur.fetchone()[0])
|
16
third_party/python/Doc/includes/sqlite3/adapter_point_1.py
vendored
Normal file
16
third_party/python/Doc/includes/sqlite3/adapter_point_1.py
vendored
Normal file
|
@ -0,0 +1,16 @@
|
|||
import sqlite3
|
||||
|
||||
class Point:
|
||||
def __init__(self, x, y):
|
||||
self.x, self.y = x, y
|
||||
|
||||
def __conform__(self, protocol):
|
||||
if protocol is sqlite3.PrepareProtocol:
|
||||
return "%f;%f" % (self.x, self.y)
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
cur = con.cursor()
|
||||
|
||||
p = Point(4.0, -3.2)
|
||||
cur.execute("select ?", (p,))
|
||||
print(cur.fetchone()[0])
|
17
third_party/python/Doc/includes/sqlite3/adapter_point_2.py
vendored
Normal file
17
third_party/python/Doc/includes/sqlite3/adapter_point_2.py
vendored
Normal file
|
@ -0,0 +1,17 @@
|
|||
import sqlite3
|
||||
|
||||
class Point:
|
||||
def __init__(self, x, y):
|
||||
self.x, self.y = x, y
|
||||
|
||||
def adapt_point(point):
|
||||
return "%f;%f" % (point.x, point.y)
|
||||
|
||||
sqlite3.register_adapter(Point, adapt_point)
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
cur = con.cursor()
|
||||
|
||||
p = Point(4.0, -3.2)
|
||||
cur.execute("select ?", (p,))
|
||||
print(cur.fetchone()[0])
|
20
third_party/python/Doc/includes/sqlite3/collation_reverse.py
vendored
Normal file
20
third_party/python/Doc/includes/sqlite3/collation_reverse.py
vendored
Normal file
|
@ -0,0 +1,20 @@
|
|||
import sqlite3
|
||||
|
||||
def collate_reverse(string1, string2):
|
||||
if string1 == string2:
|
||||
return 0
|
||||
elif string1 < string2:
|
||||
return 1
|
||||
else:
|
||||
return -1
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
con.create_collation("reverse", collate_reverse)
|
||||
|
||||
cur = con.cursor()
|
||||
cur.execute("create table test(x)")
|
||||
cur.executemany("insert into test(x) values (?)", [("a",), ("b",)])
|
||||
cur.execute("select x from test order by x collate reverse")
|
||||
for row in cur:
|
||||
print(row)
|
||||
con.close()
|
30
third_party/python/Doc/includes/sqlite3/complete_statement.py
vendored
Normal file
30
third_party/python/Doc/includes/sqlite3/complete_statement.py
vendored
Normal file
|
@ -0,0 +1,30 @@
|
|||
# A minimal SQLite shell for experiments
|
||||
|
||||
import sqlite3
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
con.isolation_level = None
|
||||
cur = con.cursor()
|
||||
|
||||
buffer = ""
|
||||
|
||||
print("Enter your SQL commands to execute in sqlite3.")
|
||||
print("Enter a blank line to exit.")
|
||||
|
||||
while True:
|
||||
line = input()
|
||||
if line == "":
|
||||
break
|
||||
buffer += line
|
||||
if sqlite3.complete_statement(buffer):
|
||||
try:
|
||||
buffer = buffer.strip()
|
||||
cur.execute(buffer)
|
||||
|
||||
if buffer.lstrip().upper().startswith("SELECT"):
|
||||
print(cur.fetchall())
|
||||
except sqlite3.Error as e:
|
||||
print("An error occurred:", e.args[0])
|
||||
buffer = ""
|
||||
|
||||
con.close()
|
3
third_party/python/Doc/includes/sqlite3/connect_db_1.py
vendored
Normal file
3
third_party/python/Doc/includes/sqlite3/connect_db_1.py
vendored
Normal file
|
@ -0,0 +1,3 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect("mydb")
|
3
third_party/python/Doc/includes/sqlite3/connect_db_2.py
vendored
Normal file
3
third_party/python/Doc/includes/sqlite3/connect_db_2.py
vendored
Normal file
|
@ -0,0 +1,3 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
47
third_party/python/Doc/includes/sqlite3/converter_point.py
vendored
Normal file
47
third_party/python/Doc/includes/sqlite3/converter_point.py
vendored
Normal file
|
@ -0,0 +1,47 @@
|
|||
import sqlite3
|
||||
|
||||
class Point:
|
||||
def __init__(self, x, y):
|
||||
self.x, self.y = x, y
|
||||
|
||||
def __repr__(self):
|
||||
return "(%f;%f)" % (self.x, self.y)
|
||||
|
||||
def adapt_point(point):
|
||||
return ("%f;%f" % (point.x, point.y)).encode('ascii')
|
||||
|
||||
def convert_point(s):
|
||||
x, y = list(map(float, s.split(b";")))
|
||||
return Point(x, y)
|
||||
|
||||
# Register the adapter
|
||||
sqlite3.register_adapter(Point, adapt_point)
|
||||
|
||||
# Register the converter
|
||||
sqlite3.register_converter("point", convert_point)
|
||||
|
||||
p = Point(4.0, -3.2)
|
||||
|
||||
#########################
|
||||
# 1) Using declared types
|
||||
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
|
||||
cur = con.cursor()
|
||||
cur.execute("create table test(p point)")
|
||||
|
||||
cur.execute("insert into test(p) values (?)", (p,))
|
||||
cur.execute("select p from test")
|
||||
print("with declared types:", cur.fetchone()[0])
|
||||
cur.close()
|
||||
con.close()
|
||||
|
||||
#######################
|
||||
# 1) Using column names
|
||||
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
|
||||
cur = con.cursor()
|
||||
cur.execute("create table test(p)")
|
||||
|
||||
cur.execute("insert into test(p) values (?)", (p,))
|
||||
cur.execute('select p as "p [point]" from test')
|
||||
print("with column names:", cur.fetchone()[0])
|
||||
cur.close()
|
||||
con.close()
|
15
third_party/python/Doc/includes/sqlite3/countcursors.py
vendored
Normal file
15
third_party/python/Doc/includes/sqlite3/countcursors.py
vendored
Normal file
|
@ -0,0 +1,15 @@
|
|||
import sqlite3
|
||||
|
||||
class CountCursorsConnection(sqlite3.Connection):
|
||||
def __init__(self, *args, **kwargs):
|
||||
sqlite3.Connection.__init__(self, *args, **kwargs)
|
||||
self.numcursors = 0
|
||||
|
||||
def cursor(self, *args, **kwargs):
|
||||
self.numcursors += 1
|
||||
return sqlite3.Connection.cursor(self, *args, **kwargs)
|
||||
|
||||
con = sqlite3.connect(":memory:", factory=CountCursorsConnection)
|
||||
cur1 = con.cursor()
|
||||
cur2 = con.cursor()
|
||||
print(con.numcursors)
|
28
third_party/python/Doc/includes/sqlite3/createdb.py
vendored
Normal file
28
third_party/python/Doc/includes/sqlite3/createdb.py
vendored
Normal file
|
@ -0,0 +1,28 @@
|
|||
# Not referenced from the documentation, but builds the database file the other
|
||||
# code snippets expect.
|
||||
|
||||
import sqlite3
|
||||
import os
|
||||
|
||||
DB_FILE = "mydb"
|
||||
|
||||
if os.path.exists(DB_FILE):
|
||||
os.remove(DB_FILE)
|
||||
|
||||
con = sqlite3.connect(DB_FILE)
|
||||
cur = con.cursor()
|
||||
cur.execute("""
|
||||
create table people
|
||||
(
|
||||
name_last varchar(20),
|
||||
age integer
|
||||
)
|
||||
""")
|
||||
|
||||
cur.execute("insert into people (name_last, age) values ('Yeltsin', 72)")
|
||||
cur.execute("insert into people (name_last, age) values ('Putin', 51)")
|
||||
|
||||
con.commit()
|
||||
|
||||
cur.close()
|
||||
con.close()
|
16
third_party/python/Doc/includes/sqlite3/ctx_manager.py
vendored
Normal file
16
third_party/python/Doc/includes/sqlite3/ctx_manager.py
vendored
Normal file
|
@ -0,0 +1,16 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
con.execute("create table person (id integer primary key, firstname varchar unique)")
|
||||
|
||||
# Successful, con.commit() is called automatically afterwards
|
||||
with con:
|
||||
con.execute("insert into person(firstname) values (?)", ("Joe",))
|
||||
|
||||
# con.rollback() is called after the with block finishes with an exception, the
|
||||
# exception is still raised and must be caught
|
||||
try:
|
||||
with con:
|
||||
con.execute("insert into person(firstname) values (?)", ("Joe",))
|
||||
except sqlite3.IntegrityError:
|
||||
print("couldn't add Joe twice")
|
17
third_party/python/Doc/includes/sqlite3/execsql_fetchonerow.py
vendored
Normal file
17
third_party/python/Doc/includes/sqlite3/execsql_fetchonerow.py
vendored
Normal file
|
@ -0,0 +1,17 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect("mydb")
|
||||
|
||||
cur = con.cursor()
|
||||
SELECT = "select name_last, age from people order by age, name_last"
|
||||
|
||||
# 1. Iterate over the rows available from the cursor, unpacking the
|
||||
# resulting sequences to yield their elements (name_last, age):
|
||||
cur.execute(SELECT)
|
||||
for (name_last, age) in cur:
|
||||
print('%s is %d years old.' % (name_last, age))
|
||||
|
||||
# 2. Equivalently:
|
||||
cur.execute(SELECT)
|
||||
for row in cur:
|
||||
print('%s is %d years old.' % (row[0], row[1]))
|
13
third_party/python/Doc/includes/sqlite3/execsql_printall_1.py
vendored
Normal file
13
third_party/python/Doc/includes/sqlite3/execsql_printall_1.py
vendored
Normal file
|
@ -0,0 +1,13 @@
|
|||
import sqlite3
|
||||
|
||||
# Create a connection to the database file "mydb":
|
||||
con = sqlite3.connect("mydb")
|
||||
|
||||
# Get a Cursor object that operates in the context of Connection con:
|
||||
cur = con.cursor()
|
||||
|
||||
# Execute the SELECT statement:
|
||||
cur.execute("select * from people order by age")
|
||||
|
||||
# Retrieve all rows as a sequence and print that sequence:
|
||||
print(cur.fetchall())
|
16
third_party/python/Doc/includes/sqlite3/execute_1.py
vendored
Normal file
16
third_party/python/Doc/includes/sqlite3/execute_1.py
vendored
Normal file
|
@ -0,0 +1,16 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
cur = con.cursor()
|
||||
cur.execute("create table people (name_last, age)")
|
||||
|
||||
who = "Yeltsin"
|
||||
age = 72
|
||||
|
||||
# This is the qmark style:
|
||||
cur.execute("insert into people values (?, ?)", (who, age))
|
||||
|
||||
# And this is the named style:
|
||||
cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})
|
||||
|
||||
print(cur.fetchone())
|
12
third_party/python/Doc/includes/sqlite3/execute_3.py
vendored
Normal file
12
third_party/python/Doc/includes/sqlite3/execute_3.py
vendored
Normal file
|
@ -0,0 +1,12 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect("mydb")
|
||||
|
||||
cur = con.cursor()
|
||||
|
||||
who = "Yeltsin"
|
||||
age = 72
|
||||
|
||||
cur.execute("select name_last, age from people where name_last=:who and age=:age",
|
||||
locals())
|
||||
print(cur.fetchone())
|
24
third_party/python/Doc/includes/sqlite3/executemany_1.py
vendored
Normal file
24
third_party/python/Doc/includes/sqlite3/executemany_1.py
vendored
Normal file
|
@ -0,0 +1,24 @@
|
|||
import sqlite3
|
||||
|
||||
class IterChars:
|
||||
def __init__(self):
|
||||
self.count = ord('a')
|
||||
|
||||
def __iter__(self):
|
||||
return self
|
||||
|
||||
def __next__(self):
|
||||
if self.count > ord('z'):
|
||||
raise StopIteration
|
||||
self.count += 1
|
||||
return (chr(self.count - 1),) # this is a 1-tuple
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
cur = con.cursor()
|
||||
cur.execute("create table characters(c)")
|
||||
|
||||
theIter = IterChars()
|
||||
cur.executemany("insert into characters(c) values (?)", theIter)
|
||||
|
||||
cur.execute("select c from characters")
|
||||
print(cur.fetchall())
|
15
third_party/python/Doc/includes/sqlite3/executemany_2.py
vendored
Normal file
15
third_party/python/Doc/includes/sqlite3/executemany_2.py
vendored
Normal file
|
@ -0,0 +1,15 @@
|
|||
import sqlite3
|
||||
import string
|
||||
|
||||
def char_generator():
|
||||
for c in string.ascii_lowercase:
|
||||
yield (c,)
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
cur = con.cursor()
|
||||
cur.execute("create table characters(c)")
|
||||
|
||||
cur.executemany("insert into characters(c) values (?)", char_generator())
|
||||
|
||||
cur.execute("select c from characters")
|
||||
print(cur.fetchall())
|
24
third_party/python/Doc/includes/sqlite3/executescript.py
vendored
Normal file
24
third_party/python/Doc/includes/sqlite3/executescript.py
vendored
Normal file
|
@ -0,0 +1,24 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
cur = con.cursor()
|
||||
cur.executescript("""
|
||||
create table person(
|
||||
firstname,
|
||||
lastname,
|
||||
age
|
||||
);
|
||||
|
||||
create table book(
|
||||
title,
|
||||
author,
|
||||
published
|
||||
);
|
||||
|
||||
insert into book(title, author, published)
|
||||
values (
|
||||
'Dirk Gently''s Holistic Detective Agency',
|
||||
'Douglas Adams',
|
||||
1987
|
||||
);
|
||||
""")
|
16
third_party/python/Doc/includes/sqlite3/insert_more_people.py
vendored
Normal file
16
third_party/python/Doc/includes/sqlite3/insert_more_people.py
vendored
Normal file
|
@ -0,0 +1,16 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect("mydb")
|
||||
|
||||
cur = con.cursor()
|
||||
|
||||
newPeople = (
|
||||
('Lebed' , 53),
|
||||
('Zhirinovsky' , 57),
|
||||
)
|
||||
|
||||
for person in newPeople:
|
||||
cur.execute("insert into people (name_last, age) values (?, ?)", person)
|
||||
|
||||
# The changes will not be saved unless the transaction is committed explicitly:
|
||||
con.commit()
|
26
third_party/python/Doc/includes/sqlite3/load_extension.py
vendored
Normal file
26
third_party/python/Doc/includes/sqlite3/load_extension.py
vendored
Normal file
|
@ -0,0 +1,26 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
|
||||
# enable extension loading
|
||||
con.enable_load_extension(True)
|
||||
|
||||
# Load the fulltext search extension
|
||||
con.execute("select load_extension('./fts3.so')")
|
||||
|
||||
# alternatively you can load the extension using an API call:
|
||||
# con.load_extension("./fts3.so")
|
||||
|
||||
# disable extension loading again
|
||||
con.enable_load_extension(False)
|
||||
|
||||
# example from SQLite wiki
|
||||
con.execute("create virtual table recipe using fts3(name, ingredients)")
|
||||
con.executescript("""
|
||||
insert into recipe (name, ingredients) values ('broccoli stew', 'broccoli peppers cheese tomatoes');
|
||||
insert into recipe (name, ingredients) values ('pumpkin stew', 'pumpkin onions garlic celery');
|
||||
insert into recipe (name, ingredients) values ('broccoli pie', 'broccoli cheese onions flour');
|
||||
insert into recipe (name, ingredients) values ('pumpkin pie', 'pumpkin sugar flour butter');
|
||||
""")
|
||||
for row in con.execute("select rowid, name, ingredients from recipe where name match 'pie'"):
|
||||
print(row)
|
11
third_party/python/Doc/includes/sqlite3/md5func.py
vendored
Normal file
11
third_party/python/Doc/includes/sqlite3/md5func.py
vendored
Normal file
|
@ -0,0 +1,11 @@
|
|||
import sqlite3
|
||||
import hashlib
|
||||
|
||||
def md5sum(t):
|
||||
return hashlib.md5(t).hexdigest()
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
con.create_function("md5", 1, md5sum)
|
||||
cur = con.cursor()
|
||||
cur.execute("select md5(?)", (b"foo",))
|
||||
print(cur.fetchone()[0])
|
20
third_party/python/Doc/includes/sqlite3/mysumaggr.py
vendored
Normal file
20
third_party/python/Doc/includes/sqlite3/mysumaggr.py
vendored
Normal file
|
@ -0,0 +1,20 @@
|
|||
import sqlite3
|
||||
|
||||
class MySum:
|
||||
def __init__(self):
|
||||
self.count = 0
|
||||
|
||||
def step(self, value):
|
||||
self.count += value
|
||||
|
||||
def finalize(self):
|
||||
return self.count
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
con.create_aggregate("mysum", 1, MySum)
|
||||
cur = con.cursor()
|
||||
cur.execute("create table test(i)")
|
||||
cur.execute("insert into test(i) values (1)")
|
||||
cur.execute("insert into test(i) values (2)")
|
||||
cur.execute("select mysum(i) from test")
|
||||
print(cur.fetchone()[0])
|
8
third_party/python/Doc/includes/sqlite3/parse_colnames.py
vendored
Normal file
8
third_party/python/Doc/includes/sqlite3/parse_colnames.py
vendored
Normal file
|
@ -0,0 +1,8 @@
|
|||
import sqlite3
|
||||
import datetime
|
||||
|
||||
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
|
||||
cur = con.cursor()
|
||||
cur.execute('select ? as "x [timestamp]"', (datetime.datetime.now(),))
|
||||
dt = cur.fetchone()[0]
|
||||
print(dt, type(dt))
|
20
third_party/python/Doc/includes/sqlite3/pysqlite_datetime.py
vendored
Normal file
20
third_party/python/Doc/includes/sqlite3/pysqlite_datetime.py
vendored
Normal file
|
@ -0,0 +1,20 @@
|
|||
import sqlite3
|
||||
import datetime
|
||||
|
||||
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
|
||||
cur = con.cursor()
|
||||
cur.execute("create table test(d date, ts timestamp)")
|
||||
|
||||
today = datetime.date.today()
|
||||
now = datetime.datetime.now()
|
||||
|
||||
cur.execute("insert into test(d, ts) values (?, ?)", (today, now))
|
||||
cur.execute("select d, ts from test")
|
||||
row = cur.fetchone()
|
||||
print(today, "=>", row[0], type(row[0]))
|
||||
print(now, "=>", row[1], type(row[1]))
|
||||
|
||||
cur.execute('select current_date as "d [date]", current_timestamp as "ts [timestamp]"')
|
||||
row = cur.fetchone()
|
||||
print("current_date", row[0], type(row[0]))
|
||||
print("current_timestamp", row[1], type(row[1]))
|
13
third_party/python/Doc/includes/sqlite3/row_factory.py
vendored
Normal file
13
third_party/python/Doc/includes/sqlite3/row_factory.py
vendored
Normal file
|
@ -0,0 +1,13 @@
|
|||
import sqlite3
|
||||
|
||||
def dict_factory(cursor, row):
|
||||
d = {}
|
||||
for idx, col in enumerate(cursor.description):
|
||||
d[col[0]] = row[idx]
|
||||
return d
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
con.row_factory = dict_factory
|
||||
cur = con.cursor()
|
||||
cur.execute("select 1 as a")
|
||||
print(cur.fetchone()["a"])
|
12
third_party/python/Doc/includes/sqlite3/rowclass.py
vendored
Normal file
12
third_party/python/Doc/includes/sqlite3/rowclass.py
vendored
Normal file
|
@ -0,0 +1,12 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
con.row_factory = sqlite3.Row
|
||||
|
||||
cur = con.cursor()
|
||||
cur.execute("select 'John' as name, 42 as age")
|
||||
for row in cur:
|
||||
assert row[0] == row["name"]
|
||||
assert row["name"] == row["nAmE"]
|
||||
assert row[1] == row["age"]
|
||||
assert row[1] == row["AgE"]
|
6
third_party/python/Doc/includes/sqlite3/shared_cache.py
vendored
Normal file
6
third_party/python/Doc/includes/sqlite3/shared_cache.py
vendored
Normal file
|
@ -0,0 +1,6 @@
|
|||
import sqlite3
|
||||
|
||||
# The shared cache is only available in SQLite versions 3.3.3 or later
|
||||
# See the SQLite documentation for details.
|
||||
|
||||
sqlite3.enable_shared_cache(True)
|
20
third_party/python/Doc/includes/sqlite3/shortcut_methods.py
vendored
Normal file
20
third_party/python/Doc/includes/sqlite3/shortcut_methods.py
vendored
Normal file
|
@ -0,0 +1,20 @@
|
|||
import sqlite3
|
||||
|
||||
persons = [
|
||||
("Hugo", "Boss"),
|
||||
("Calvin", "Klein")
|
||||
]
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
|
||||
# Create the table
|
||||
con.execute("create table person(firstname, lastname)")
|
||||
|
||||
# Fill the table
|
||||
con.executemany("insert into person(firstname, lastname) values (?, ?)", persons)
|
||||
|
||||
# Print the table contents
|
||||
for row in con.execute("select firstname, lastname from person"):
|
||||
print(row)
|
||||
|
||||
print("I just deleted", con.execute("delete from person").rowcount, "rows")
|
26
third_party/python/Doc/includes/sqlite3/simple_tableprinter.py
vendored
Normal file
26
third_party/python/Doc/includes/sqlite3/simple_tableprinter.py
vendored
Normal file
|
@ -0,0 +1,26 @@
|
|||
import sqlite3
|
||||
|
||||
FIELD_MAX_WIDTH = 20
|
||||
TABLE_NAME = 'people'
|
||||
SELECT = 'select * from %s order by age, name_last' % TABLE_NAME
|
||||
|
||||
con = sqlite3.connect("mydb")
|
||||
|
||||
cur = con.cursor()
|
||||
cur.execute(SELECT)
|
||||
|
||||
# Print a header.
|
||||
for fieldDesc in cur.description:
|
||||
print(fieldDesc[0].ljust(FIELD_MAX_WIDTH), end=' ')
|
||||
print() # Finish the header with a newline.
|
||||
print('-' * 78)
|
||||
|
||||
# For each row, print the value of each field left-justified within
|
||||
# the maximum possible width of that field.
|
||||
fieldIndices = range(len(cur.description))
|
||||
for row in cur:
|
||||
for fieldIndex in fieldIndices:
|
||||
fieldValue = str(row[fieldIndex])
|
||||
print(fieldValue.ljust(FIELD_MAX_WIDTH), end=' ')
|
||||
|
||||
print() # Finish the row with a newline.
|
27
third_party/python/Doc/includes/sqlite3/text_factory.py
vendored
Normal file
27
third_party/python/Doc/includes/sqlite3/text_factory.py
vendored
Normal file
|
@ -0,0 +1,27 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
cur = con.cursor()
|
||||
|
||||
AUSTRIA = "\xd6sterreich"
|
||||
|
||||
# by default, rows are returned as Unicode
|
||||
cur.execute("select ?", (AUSTRIA,))
|
||||
row = cur.fetchone()
|
||||
assert row[0] == AUSTRIA
|
||||
|
||||
# but we can make sqlite3 always return bytestrings ...
|
||||
con.text_factory = bytes
|
||||
cur.execute("select ?", (AUSTRIA,))
|
||||
row = cur.fetchone()
|
||||
assert type(row[0]) is bytes
|
||||
# the bytestrings will be encoded in UTF-8, unless you stored garbage in the
|
||||
# database ...
|
||||
assert row[0] == AUSTRIA.encode("utf-8")
|
||||
|
||||
# we can also implement a custom text_factory ...
|
||||
# here we implement one that appends "foo" to all strings
|
||||
con.text_factory = lambda x: x.decode("utf-8") + "foo"
|
||||
cur.execute("select ?", ("bar",))
|
||||
row = cur.fetchone()
|
||||
assert row[0] == "barfoo"
|
63
third_party/python/Doc/includes/sublist.c
vendored
Normal file
63
third_party/python/Doc/includes/sublist.c
vendored
Normal file
|
@ -0,0 +1,63 @@
|
|||
#include <Python.h>
|
||||
|
||||
typedef struct {
|
||||
PyListObject list;
|
||||
int state;
|
||||
} SubListObject;
|
||||
|
||||
static PyObject *
|
||||
SubList_increment(SubListObject *self, PyObject *unused)
|
||||
{
|
||||
self->state++;
|
||||
return PyLong_FromLong(self->state);
|
||||
}
|
||||
|
||||
static PyMethodDef SubList_methods[] = {
|
||||
{"increment", (PyCFunction) SubList_increment, METH_NOARGS,
|
||||
PyDoc_STR("increment state counter")},
|
||||
{NULL},
|
||||
};
|
||||
|
||||
static int
|
||||
SubList_init(SubListObject *self, PyObject *args, PyObject *kwds)
|
||||
{
|
||||
if (PyList_Type.tp_init((PyObject *) self, args, kwds) < 0)
|
||||
return -1;
|
||||
self->state = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static PyTypeObject SubListType = {
|
||||
PyVarObject_HEAD_INIT(NULL, 0)
|
||||
.tp_name = "sublist.SubList",
|
||||
.tp_doc = "SubList objects",
|
||||
.tp_basicsize = sizeof(SubListObject),
|
||||
.tp_itemsize = 0,
|
||||
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
|
||||
.tp_init = (initproc) SubList_init,
|
||||
.tp_methods = SubList_methods,
|
||||
};
|
||||
|
||||
static PyModuleDef sublistmodule = {
|
||||
PyModuleDef_HEAD_INIT,
|
||||
.m_name = "sublist",
|
||||
.m_doc = "Example module that creates an extension type.",
|
||||
.m_size = -1,
|
||||
};
|
||||
|
||||
PyMODINIT_FUNC
|
||||
PyInit_sublist(void)
|
||||
{
|
||||
PyObject *m;
|
||||
SubListType.tp_base = &PyList_Type;
|
||||
if (PyType_Ready(&SubListType) < 0)
|
||||
return NULL;
|
||||
|
||||
m = PyModule_Create(&sublistmodule);
|
||||
if (m == NULL)
|
||||
return NULL;
|
||||
|
||||
Py_INCREF(&SubListType);
|
||||
PyModule_AddObject(m, "SubList", (PyObject *) &SubListType);
|
||||
return m;
|
||||
}
|
199
third_party/python/Doc/includes/test.py
vendored
Normal file
199
third_party/python/Doc/includes/test.py
vendored
Normal file
|
@ -0,0 +1,199 @@
|
|||
"""Test module for the custom examples
|
||||
|
||||
Custom 1:
|
||||
|
||||
>>> import custom
|
||||
>>> c1 = custom.Custom()
|
||||
>>> c2 = custom.Custom()
|
||||
>>> del c1
|
||||
>>> del c2
|
||||
|
||||
|
||||
Custom 2
|
||||
|
||||
>>> import custom2
|
||||
>>> c1 = custom2.Custom('jim', 'fulton', 42)
|
||||
>>> c1.first
|
||||
'jim'
|
||||
>>> c1.last
|
||||
'fulton'
|
||||
>>> c1.number
|
||||
42
|
||||
>>> c1.name()
|
||||
'jim fulton'
|
||||
>>> c1.first = 'will'
|
||||
>>> c1.name()
|
||||
'will fulton'
|
||||
>>> c1.last = 'tell'
|
||||
>>> c1.name()
|
||||
'will tell'
|
||||
>>> del c1.first
|
||||
>>> c1.name()
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
AttributeError: first
|
||||
>>> c1.first
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
AttributeError: first
|
||||
>>> c1.first = 'drew'
|
||||
>>> c1.first
|
||||
'drew'
|
||||
>>> del c1.number
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
TypeError: can't delete numeric/char attribute
|
||||
>>> c1.number=2
|
||||
>>> c1.number
|
||||
2
|
||||
>>> c1.first = 42
|
||||
>>> c1.name()
|
||||
'42 tell'
|
||||
>>> c2 = custom2.Custom()
|
||||
>>> c2.name()
|
||||
' '
|
||||
>>> c2.first
|
||||
''
|
||||
>>> c2.last
|
||||
''
|
||||
>>> del c2.first
|
||||
>>> c2.first
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
AttributeError: first
|
||||
>>> c2.first
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
AttributeError: first
|
||||
>>> c2.name()
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in ?
|
||||
AttributeError: first
|
||||
>>> c2.number
|
||||
0
|
||||
>>> n3 = custom2.Custom('jim', 'fulton', 'waaa')
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in ?
|
||||
TypeError: an integer is required (got type str)
|
||||
>>> del c1
|
||||
>>> del c2
|
||||
|
||||
|
||||
Custom 3
|
||||
|
||||
>>> import custom3
|
||||
>>> c1 = custom3.Custom('jim', 'fulton', 42)
|
||||
>>> c1 = custom3.Custom('jim', 'fulton', 42)
|
||||
>>> c1.name()
|
||||
'jim fulton'
|
||||
>>> del c1.first
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in ?
|
||||
TypeError: Cannot delete the first attribute
|
||||
>>> c1.first = 42
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in ?
|
||||
TypeError: The first attribute value must be a string
|
||||
>>> c1.first = 'will'
|
||||
>>> c1.name()
|
||||
'will fulton'
|
||||
>>> c2 = custom3.Custom()
|
||||
>>> c2 = custom3.Custom()
|
||||
>>> c2 = custom3.Custom()
|
||||
>>> n3 = custom3.Custom('jim', 'fulton', 'waaa')
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in ?
|
||||
TypeError: an integer is required (got type str)
|
||||
>>> del c1
|
||||
>>> del c2
|
||||
|
||||
Custom 4
|
||||
|
||||
>>> import custom4
|
||||
>>> c1 = custom4.Custom('jim', 'fulton', 42)
|
||||
>>> c1.first
|
||||
'jim'
|
||||
>>> c1.last
|
||||
'fulton'
|
||||
>>> c1.number
|
||||
42
|
||||
>>> c1.name()
|
||||
'jim fulton'
|
||||
>>> c1.first = 'will'
|
||||
>>> c1.name()
|
||||
'will fulton'
|
||||
>>> c1.last = 'tell'
|
||||
>>> c1.name()
|
||||
'will tell'
|
||||
>>> del c1.first
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
TypeError: Cannot delete the first attribute
|
||||
>>> c1.name()
|
||||
'will tell'
|
||||
>>> c1.first = 'drew'
|
||||
>>> c1.first
|
||||
'drew'
|
||||
>>> del c1.number
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
TypeError: can't delete numeric/char attribute
|
||||
>>> c1.number=2
|
||||
>>> c1.number
|
||||
2
|
||||
>>> c1.first = 42
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
TypeError: The first attribute value must be a string
|
||||
>>> c1.name()
|
||||
'drew tell'
|
||||
>>> c2 = custom4.Custom()
|
||||
>>> c2 = custom4.Custom()
|
||||
>>> c2 = custom4.Custom()
|
||||
>>> c2 = custom4.Custom()
|
||||
>>> c2.name()
|
||||
' '
|
||||
>>> c2.first
|
||||
''
|
||||
>>> c2.last
|
||||
''
|
||||
>>> c2.number
|
||||
0
|
||||
>>> n3 = custom4.Custom('jim', 'fulton', 'waaa')
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
TypeError: an integer is required (got type str)
|
||||
|
||||
|
||||
Test cyclic gc(?)
|
||||
|
||||
>>> import gc
|
||||
>>> gc.disable()
|
||||
|
||||
>>> class Subclass(custom4.Custom): pass
|
||||
...
|
||||
>>> s = Subclass()
|
||||
>>> s.cycle = [s]
|
||||
>>> s.cycle.append(s.cycle)
|
||||
>>> x = object()
|
||||
>>> s.x = x
|
||||
>>> del s
|
||||
>>> sys.getrefcount(x)
|
||||
3
|
||||
>>> ignore = gc.collect()
|
||||
>>> sys.getrefcount(x)
|
||||
2
|
||||
|
||||
>>> gc.enable()
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from distutils.util import get_platform
|
||||
PLAT_SPEC = "%s-%d.%d" % (get_platform(), *sys.version_info[:2])
|
||||
src = os.path.join("build", "lib.%s" % PLAT_SPEC)
|
||||
sys.path.append(src)
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest, __main__
|
||||
doctest.testmod(__main__)
|
10
third_party/python/Doc/includes/turtle-star.py
vendored
Normal file
10
third_party/python/Doc/includes/turtle-star.py
vendored
Normal file
|
@ -0,0 +1,10 @@
|
|||
from turtle import *
|
||||
color('red', 'yellow')
|
||||
begin_fill()
|
||||
while True:
|
||||
forward(200)
|
||||
left(170)
|
||||
if abs(pos()) < 1:
|
||||
break
|
||||
end_fill()
|
||||
done()
|
80
third_party/python/Doc/includes/typestruct.h
vendored
Normal file
80
third_party/python/Doc/includes/typestruct.h
vendored
Normal file
|
@ -0,0 +1,80 @@
|
|||
typedef struct _typeobject {
|
||||
PyObject_VAR_HEAD
|
||||
const char *tp_name; /* For printing, in format "<module>.<name>" */
|
||||
Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
|
||||
|
||||
/* Methods to implement standard operations */
|
||||
|
||||
destructor tp_dealloc;
|
||||
printfunc tp_print;
|
||||
getattrfunc tp_getattr;
|
||||
setattrfunc tp_setattr;
|
||||
PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
|
||||
or tp_reserved (Python 3) */
|
||||
reprfunc tp_repr;
|
||||
|
||||
/* Method suites for standard classes */
|
||||
|
||||
PyNumberMethods *tp_as_number;
|
||||
PySequenceMethods *tp_as_sequence;
|
||||
PyMappingMethods *tp_as_mapping;
|
||||
|
||||
/* More standard operations (here for binary compatibility) */
|
||||
|
||||
hashfunc tp_hash;
|
||||
ternaryfunc tp_call;
|
||||
reprfunc tp_str;
|
||||
getattrofunc tp_getattro;
|
||||
setattrofunc tp_setattro;
|
||||
|
||||
/* Functions to access object as input/output buffer */
|
||||
PyBufferProcs *tp_as_buffer;
|
||||
|
||||
/* Flags to define presence of optional/expanded features */
|
||||
unsigned long tp_flags;
|
||||
|
||||
const char *tp_doc; /* Documentation string */
|
||||
|
||||
/* call function for all accessible objects */
|
||||
traverseproc tp_traverse;
|
||||
|
||||
/* delete references to contained objects */
|
||||
inquiry tp_clear;
|
||||
|
||||
/* rich comparisons */
|
||||
richcmpfunc tp_richcompare;
|
||||
|
||||
/* weak reference enabler */
|
||||
Py_ssize_t tp_weaklistoffset;
|
||||
|
||||
/* Iterators */
|
||||
getiterfunc tp_iter;
|
||||
iternextfunc tp_iternext;
|
||||
|
||||
/* Attribute descriptor and subclassing stuff */
|
||||
struct PyMethodDef *tp_methods;
|
||||
struct PyMemberDef *tp_members;
|
||||
struct PyGetSetDef *tp_getset;
|
||||
struct _typeobject *tp_base;
|
||||
PyObject *tp_dict;
|
||||
descrgetfunc tp_descr_get;
|
||||
descrsetfunc tp_descr_set;
|
||||
Py_ssize_t tp_dictoffset;
|
||||
initproc tp_init;
|
||||
allocfunc tp_alloc;
|
||||
newfunc tp_new;
|
||||
freefunc tp_free; /* Low-level free-memory routine */
|
||||
inquiry tp_is_gc; /* For PyObject_IS_GC */
|
||||
PyObject *tp_bases;
|
||||
PyObject *tp_mro; /* method resolution order */
|
||||
PyObject *tp_cache;
|
||||
PyObject *tp_subclasses;
|
||||
PyObject *tp_weaklist;
|
||||
destructor tp_del;
|
||||
|
||||
/* Type attribute cache version tag. Added in version 2.6 */
|
||||
unsigned int tp_version_tag;
|
||||
|
||||
destructor tp_finalize;
|
||||
|
||||
} PyTypeObject;
|
175
third_party/python/Doc/includes/tzinfo-examples.py
vendored
Normal file
175
third_party/python/Doc/includes/tzinfo-examples.py
vendored
Normal file
|
@ -0,0 +1,175 @@
|
|||
from datetime import tzinfo, timedelta, datetime, timezone
|
||||
|
||||
ZERO = timedelta(0)
|
||||
HOUR = timedelta(hours=1)
|
||||
SECOND = timedelta(seconds=1)
|
||||
|
||||
# A class capturing the platform's idea of local time.
|
||||
# (May result in wrong values on historical times in
|
||||
# timezones where UTC offset and/or the DST rules had
|
||||
# changed in the past.)
|
||||
import time as _time
|
||||
|
||||
STDOFFSET = timedelta(seconds = -_time.timezone)
|
||||
if _time.daylight:
|
||||
DSTOFFSET = timedelta(seconds = -_time.altzone)
|
||||
else:
|
||||
DSTOFFSET = STDOFFSET
|
||||
|
||||
DSTDIFF = DSTOFFSET - STDOFFSET
|
||||
|
||||
class LocalTimezone(tzinfo):
|
||||
|
||||
def fromutc(self, dt):
|
||||
assert dt.tzinfo is self
|
||||
stamp = (dt - datetime(1970, 1, 1, tzinfo=self)) // SECOND
|
||||
args = _time.localtime(stamp)[:6]
|
||||
dst_diff = DSTDIFF // SECOND
|
||||
# Detect fold
|
||||
fold = (args == _time.localtime(stamp - dst_diff))
|
||||
return datetime(*args, microsecond=dt.microsecond,
|
||||
tzinfo=self, fold=fold)
|
||||
|
||||
def utcoffset(self, dt):
|
||||
if self._isdst(dt):
|
||||
return DSTOFFSET
|
||||
else:
|
||||
return STDOFFSET
|
||||
|
||||
def dst(self, dt):
|
||||
if self._isdst(dt):
|
||||
return DSTDIFF
|
||||
else:
|
||||
return ZERO
|
||||
|
||||
def tzname(self, dt):
|
||||
return _time.tzname[self._isdst(dt)]
|
||||
|
||||
def _isdst(self, dt):
|
||||
tt = (dt.year, dt.month, dt.day,
|
||||
dt.hour, dt.minute, dt.second,
|
||||
dt.weekday(), 0, 0)
|
||||
stamp = _time.mktime(tt)
|
||||
tt = _time.localtime(stamp)
|
||||
return tt.tm_isdst > 0
|
||||
|
||||
Local = LocalTimezone()
|
||||
|
||||
|
||||
# A complete implementation of current DST rules for major US time zones.
|
||||
|
||||
def first_sunday_on_or_after(dt):
|
||||
days_to_go = 6 - dt.weekday()
|
||||
if days_to_go:
|
||||
dt += timedelta(days_to_go)
|
||||
return dt
|
||||
|
||||
|
||||
# US DST Rules
|
||||
#
|
||||
# This is a simplified (i.e., wrong for a few cases) set of rules for US
|
||||
# DST start and end times. For a complete and up-to-date set of DST rules
|
||||
# and timezone definitions, visit the Olson Database (or try pytz):
|
||||
# http://www.twinsun.com/tz/tz-link.htm
|
||||
# http://sourceforge.net/projects/pytz/ (might not be up-to-date)
|
||||
#
|
||||
# In the US, since 2007, DST starts at 2am (standard time) on the second
|
||||
# Sunday in March, which is the first Sunday on or after Mar 8.
|
||||
DSTSTART_2007 = datetime(1, 3, 8, 2)
|
||||
# and ends at 2am (DST time) on the first Sunday of Nov.
|
||||
DSTEND_2007 = datetime(1, 11, 1, 2)
|
||||
# From 1987 to 2006, DST used to start at 2am (standard time) on the first
|
||||
# Sunday in April and to end at 2am (DST time) on the last
|
||||
# Sunday of October, which is the first Sunday on or after Oct 25.
|
||||
DSTSTART_1987_2006 = datetime(1, 4, 1, 2)
|
||||
DSTEND_1987_2006 = datetime(1, 10, 25, 2)
|
||||
# From 1967 to 1986, DST used to start at 2am (standard time) on the last
|
||||
# Sunday in April (the one on or after April 24) and to end at 2am (DST time)
|
||||
# on the last Sunday of October, which is the first Sunday
|
||||
# on or after Oct 25.
|
||||
DSTSTART_1967_1986 = datetime(1, 4, 24, 2)
|
||||
DSTEND_1967_1986 = DSTEND_1987_2006
|
||||
|
||||
def us_dst_range(year):
|
||||
# Find start and end times for US DST. For years before 1967, return
|
||||
# start = end for no DST.
|
||||
if 2006 < year:
|
||||
dststart, dstend = DSTSTART_2007, DSTEND_2007
|
||||
elif 1986 < year < 2007:
|
||||
dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006
|
||||
elif 1966 < year < 1987:
|
||||
dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986
|
||||
else:
|
||||
return (datetime(year, 1, 1), ) * 2
|
||||
|
||||
start = first_sunday_on_or_after(dststart.replace(year=year))
|
||||
end = first_sunday_on_or_after(dstend.replace(year=year))
|
||||
return start, end
|
||||
|
||||
|
||||
class USTimeZone(tzinfo):
|
||||
|
||||
def __init__(self, hours, reprname, stdname, dstname):
|
||||
self.stdoffset = timedelta(hours=hours)
|
||||
self.reprname = reprname
|
||||
self.stdname = stdname
|
||||
self.dstname = dstname
|
||||
|
||||
def __repr__(self):
|
||||
return self.reprname
|
||||
|
||||
def tzname(self, dt):
|
||||
if self.dst(dt):
|
||||
return self.dstname
|
||||
else:
|
||||
return self.stdname
|
||||
|
||||
def utcoffset(self, dt):
|
||||
return self.stdoffset + self.dst(dt)
|
||||
|
||||
def dst(self, dt):
|
||||
if dt is None or dt.tzinfo is None:
|
||||
# An exception may be sensible here, in one or both cases.
|
||||
# It depends on how you want to treat them. The default
|
||||
# fromutc() implementation (called by the default astimezone()
|
||||
# implementation) passes a datetime with dt.tzinfo is self.
|
||||
return ZERO
|
||||
assert dt.tzinfo is self
|
||||
start, end = us_dst_range(dt.year)
|
||||
# Can't compare naive to aware objects, so strip the timezone from
|
||||
# dt first.
|
||||
dt = dt.replace(tzinfo=None)
|
||||
if start + HOUR <= dt < end - HOUR:
|
||||
# DST is in effect.
|
||||
return HOUR
|
||||
if end - HOUR <= dt < end:
|
||||
# Fold (an ambiguous hour): use dt.fold to disambiguate.
|
||||
return ZERO if dt.fold else HOUR
|
||||
if start <= dt < start + HOUR:
|
||||
# Gap (a non-existent hour): reverse the fold rule.
|
||||
return HOUR if dt.fold else ZERO
|
||||
# DST is off.
|
||||
return ZERO
|
||||
|
||||
def fromutc(self, dt):
|
||||
assert dt.tzinfo is self
|
||||
start, end = us_dst_range(dt.year)
|
||||
start = start.replace(tzinfo=self)
|
||||
end = end.replace(tzinfo=self)
|
||||
std_time = dt + self.stdoffset
|
||||
dst_time = std_time + HOUR
|
||||
if end <= dst_time < end + HOUR:
|
||||
# Repeated hour
|
||||
return std_time.replace(fold=1)
|
||||
if std_time < start or dst_time >= end:
|
||||
# Standard time
|
||||
return std_time
|
||||
if start <= std_time < end - HOUR:
|
||||
# Daylight saving time
|
||||
return dst_time
|
||||
|
||||
|
||||
Eastern = USTimeZone(-5, "Eastern", "EST", "EDT")
|
||||
Central = USTimeZone(-6, "Central", "CST", "CDT")
|
||||
Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
|
||||
Pacific = USTimeZone(-8, "Pacific", "PST", "PDT")
|
Loading…
Add table
Add a link
Reference in a new issue