Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Lib/test/test_compile.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import contextlib
import dis
import io
import itertools
import math
import opcode
import os
Expand Down Expand Up @@ -2648,6 +2649,24 @@ def test_nested(self):
self.compare_instructions(seq, [('LOAD_CONST', 1, 1, 0, 0, 0)])
self.compare_instructions(seq.get_nested()[0], [('LOAD_CONST', 2, 2, 0, 0, 0)])

def test_static_attributes(self):
code = (
'class T:\n'
' def __init__(self):\n'
' self.{V1} = 10\n'
' self.{V2} = 10\n'
' def foo(self):\n'
' self.{V3} = self.{V4}\n'
)
for perm in itertools.permutations(["a", "b", "c", "d"]):
var_names = { f'V{i + 1}': perm[i] for i in range(len(perm)) }
exec_locals = {}
exec(code.format(**var_names), {}, exec_locals)
t = exec_locals['T']
static_attributes_sorted = tuple(sorted(t.__static_attributes__))
self.assertEqual(t.__static_attributes__, static_attributes_sorted)



if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Make the :func:`compile` builtin function deterministic by sorting
:attr:`~class.__static_attributes__` before writing to bytecode.
12 changes: 11 additions & 1 deletion Python/compile.c
Original file line number Diff line number Diff line change
Expand Up @@ -911,7 +911,17 @@ PyObject *
_PyCompile_StaticAttributesAsTuple(compiler *c)
{
assert(c->u->u_static_attributes);
return PySequence_Tuple(c->u->u_static_attributes);
PyObject *static_attributes_unsorted = PySequence_List(c->u->u_static_attributes);
if (static_attributes_unsorted == NULL) {
return NULL;
}
if (PyList_Sort(static_attributes_unsorted) != 0) {
Py_DECREF(static_attributes_unsorted);
return NULL;
}
PyObject *static_attributes = PySequence_Tuple(static_attributes_unsorted);
Py_DECREF(static_attributes_unsorted);
return static_attributes;
}

int
Expand Down
Loading