Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2e8f8a3

Browse files
committed
Added compare operations for functions and code objects.
(Also hash, but it doesn't work yet.)
1 parent 4199fac commit 2e8f8a3

2 files changed

Lines changed: 57 additions & 2 deletions

File tree

Objects/funcobject.c

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,27 @@ func_repr(op)
106106
return newstringobject(buf);
107107
}
108108

109+
static int
110+
func_compare(f, g)
111+
funcobject *f, *g;
112+
{
113+
if (f->func_globals != g->func_globals)
114+
return (f->func_globals < g->func_globals) ? -1 : 1;
115+
return cmpobject(f->func_code, g->func_code);
116+
}
117+
118+
static long
119+
func_hash(f)
120+
funcobject *f;
121+
{
122+
long h;
123+
h = hashobject(f->func_code);
124+
if (h == -1) return h;
125+
h = h ^ (long)f->func_globals;
126+
if (h == -1) h = -2;
127+
return h;
128+
}
129+
109130
typeobject Functype = {
110131
OB_HEAD_INIT(&Typetype)
111132
0,
@@ -116,6 +137,10 @@ typeobject Functype = {
116137
0, /*tp_print*/
117138
func_getattr, /*tp_getattr*/
118139
0, /*tp_setattr*/
119-
0, /*tp_compare*/
140+
func_compare, /*tp_compare*/
120141
func_repr, /*tp_repr*/
142+
0, /*tp_as_number*/
143+
0, /*tp_as_sequence*/
144+
0, /*tp_as_mapping*/
145+
func_hash, /*tp_hash*/
121146
};

Python/compile.c

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,35 @@ code_repr(co)
9292
return newstringobject(buf);
9393
}
9494

95+
static int
96+
code_compare(co, cp)
97+
codeobject *co, *cp;
98+
{
99+
int cmp;
100+
cmp = cmpobject((object *)co->co_code, (object *)cp->co_code);
101+
if (cmp) return cmp;
102+
cmp = cmpobject(co->co_consts, cp->co_consts);
103+
if (cmp) return cmp;
104+
cmp = cmpobject(co->co_names, cp->co_names);
105+
return cmp;
106+
}
107+
108+
static long
109+
code_hash(co)
110+
codeobject *co;
111+
{
112+
long h, h1, h2, h3;
113+
h1 = hashobject((object *)co->co_code);
114+
if (h1 == -1) return -1;
115+
h2 = hashobject(co->co_consts);
116+
if (h2 == -1) return -1;
117+
h3 = hashobject(co->co_names);
118+
if (h3 == -1) return -1;
119+
h = h1 ^ h2 ^ h3;
120+
if (h == -1) h = -2;
121+
return h;
122+
}
123+
95124
typeobject Codetype = {
96125
OB_HEAD_INIT(&Typetype)
97126
0,
@@ -102,11 +131,12 @@ typeobject Codetype = {
102131
0, /*tp_print*/
103132
code_getattr, /*tp_getattr*/
104133
0, /*tp_setattr*/
105-
0, /*tp_compare*/
134+
code_compare, /*tp_compare*/
106135
code_repr, /*tp_repr*/
107136
0, /*tp_as_number*/
108137
0, /*tp_as_sequence*/
109138
0, /*tp_as_mapping*/
139+
code_hash, /*tp_hash*/
110140
};
111141

112142
codeobject *

0 commit comments

Comments
 (0)