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

Skip to content

Commit 76d962d

Browse files
committed
Treat None as a constant.
1 parent 11d9b06 commit 76d962d

2 files changed

Lines changed: 22 additions & 4 deletions

File tree

Misc/NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ Core and builtins
2626
- Added C macros Py_CLEAR and Py_VISIT to ease the implementation of
2727
types that support garbage collection.
2828

29+
- Compiler now treats None as a constant.
30+
2931
Extension modules
3032
-----------------
3133

Python/compile.c

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -363,12 +363,13 @@ markblocks(unsigned char *code, int len)
363363
}
364364

365365
static PyObject *
366-
optimize_code(PyObject *code, PyObject* consts)
366+
optimize_code(PyObject *code, PyObject* consts, PyObject *names)
367367
{
368368
int i, j, codelen;
369369
int tgt, tgttgt, opcode;
370370
unsigned char *codestr;
371371
unsigned int *blocks;
372+
char *name;
372373

373374
/* Make a modifiable copy of the code string */
374375
if (!PyString_Check(code))
@@ -418,6 +419,21 @@ optimize_code(PyObject *code, PyObject* consts)
418419
continue;
419420
SETARG(codestr, i, (j^1));
420421
codestr[i+3] = NOP;
422+
423+
/* Replace LOAD_GLOBAL/LOAD_NAME None with LOAD_CONST None */
424+
case LOAD_NAME:
425+
case LOAD_GLOBAL:
426+
j = GETARG(codestr, i);
427+
name = PyString_AsString(PyTuple_GET_ITEM(names, j));
428+
if (name == NULL || strcmp(name, "None") != 0)
429+
continue;
430+
for (j=0 ; j < PyTuple_GET_SIZE(consts) ; j++) {
431+
if (PyTuple_GET_ITEM(consts, j) == Py_None) {
432+
codestr[i] = LOAD_CONST;
433+
SETARG(codestr, i, j);
434+
break;
435+
}
436+
}
421437
break;
422438

423439
/* Skip over LOAD_CONST trueconst JUMP_IF_FALSE xx POP_TOP.
@@ -441,7 +457,7 @@ optimize_code(PyObject *code, PyObject* consts)
441457
continue;
442458
if (!ISBASICBLOCK(blocks,i,6))
443459
continue;
444-
if (GETARG(codestr, i) == 2 && \
460+
if (GETARG(codestr, i) == 2 &&
445461
GETARG(codestr, i+3) == 2) {
446462
codestr[i] = ROT_TWO;
447463
codestr[i+1] = JUMP_FORWARD;
@@ -450,7 +466,7 @@ optimize_code(PyObject *code, PyObject* consts)
450466
codestr[i+5] = NOP;
451467
continue;
452468
}
453-
if (GETARG(codestr, i) == 3 && \
469+
if (GETARG(codestr, i) == 3 &&
454470
GETARG(codestr, i+3) == 3) {
455471
codestr[i] = ROT_THREE;
456472
codestr[i+1] = ROT_TWO;
@@ -542,7 +558,7 @@ PyCode_New(int argcount, int nlocals, int stacksize, int flags,
542558
co->co_nlocals = nlocals;
543559
co->co_stacksize = stacksize;
544560
co->co_flags = flags;
545-
co->co_code = optimize_code(code, consts);
561+
co->co_code = optimize_code(code, consts, names);
546562
Py_INCREF(consts);
547563
co->co_consts = consts;
548564
Py_INCREF(names);

0 commit comments

Comments
 (0)