Skip to content

Commit de41cb5

Browse files
committed
Add module __getattr__
1 parent 261d87f commit de41cb5

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Modules/socketmodule.c

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5574,6 +5574,23 @@ static PyType_Spec sock_spec = {
55745574
.slots = sock_slots,
55755575
};
55765576

5577+
static PyObject *
5578+
socket_getattr(PyObject *self, PyObject *name)
5579+
{
5580+
const char *attrname = PyUnicode_AsUTF8(name);
5581+
PyObject *sock_type = PyType_FromSpec(&sock_spec);
5582+
if (sock_type == NULL) {
5583+
return NULL;
5584+
}
5585+
5586+
if (!strcmp(attrname, "SocketType")) {
5587+
PyErr_Warn(PyExc_DeprecationWarning, "Use socket.socket type instead");
5588+
return sock_type;
5589+
}
5590+
5591+
PyErr_Format(PyExc_AttributeError, "module _socket has no attribute %s", attrname);
5592+
return NULL;
5593+
}
55775594

55785595
#ifdef HAVE_GETHOSTNAME
55795596
/* Python interface to gethostname(). */
@@ -6959,6 +6976,18 @@ Set the default timeout in seconds (float) for new socket objects.\n\
69596976
A value of None indicates that new socket objects have no timeout.\n\
69606977
When the socket module is first imported, the default is None.");
69616978

6979+
static PyObject *
6980+
socket_getattr(PyObject *self, PyObject *name)
6981+
{
6982+
const char *attrname = PyUnicode_AsUTF8(name);
6983+
if (strcmp(attrname, "asd") == 0) {
6984+
return PyLong_FromLong(42);
6985+
}
6986+
6987+
PyErr_Format(PyExc_AttributeError, "Module has no attribute '%s'", attrname);
6988+
return NULL;
6989+
}
6990+
69626991
#if defined(HAVE_IF_NAMEINDEX) || defined(MS_WINDOWS)
69636992
/* Python API for getting interface indices and names */
69646993

@@ -7179,6 +7208,7 @@ range of values.");
71797208
/* List of functions exported by this module. */
71807209

71817210
static PyMethodDef socket_methods[] = {
7211+
{"__getattr__", socket_getattr, METH_O, "Module __getattr__"},
71827212
#ifdef HAVE_GETADDRINFO
71837213
{"gethostbyname", socket_gethostbyname,
71847214
METH_VARARGS, gethostbyname_doc},

0 commit comments

Comments
 (0)