@@ -535,6 +535,37 @@ compiler_enter_scope(struct compiler *c, identifier name,
535535 compiler_unit_free (u );
536536 return 0 ;
537537 }
538+ if (u -> u_ste -> ste_needs_class_closure ) {
539+ /* Cook up a implicit __class__ cell. */
540+ _Py_IDENTIFIER (__class__ );
541+ PyObject * tuple , * name , * zero ;
542+ int res ;
543+ assert (u -> u_scope_type == COMPILER_SCOPE_CLASS );
544+ assert (PyDict_Size (u -> u_cellvars ) == 0 );
545+ name = _PyUnicode_FromId (& PyId___class__ );
546+ if (!name ) {
547+ compiler_unit_free (u );
548+ return 0 ;
549+ }
550+ tuple = PyTuple_Pack (2 , name , Py_TYPE (name ));
551+ if (!tuple ) {
552+ compiler_unit_free (u );
553+ return 0 ;
554+ }
555+ zero = PyLong_FromLong (0 );
556+ if (!zero ) {
557+ Py_DECREF (tuple );
558+ compiler_unit_free (u );
559+ return 0 ;
560+ }
561+ res = PyDict_SetItem (u -> u_cellvars , tuple , zero );
562+ Py_DECREF (tuple );
563+ Py_DECREF (zero );
564+ if (res < 0 ) {
565+ compiler_unit_free (u );
566+ return 0 ;
567+ }
568+ }
538569
539570 u -> u_freevars = dictbytype (u -> u_ste -> ste_symbols , FREE , DEF_FREE_CLASS ,
540571 PyDict_Size (u -> u_cellvars ));
@@ -1331,6 +1362,9 @@ compiler_mod(struct compiler *c, mod_ty mod)
13311362static int
13321363get_ref_type (struct compiler * c , PyObject * name )
13331364{
1365+ if (c -> u -> u_scope_type == COMPILER_SCOPE_CLASS &&
1366+ !PyUnicode_CompareWithASCIIString (name , "__class__" ))
1367+ return CELL ;
13341368 int scope = PyST_GetScope (c -> u -> u_ste , name );
13351369 if (scope == 0 ) {
13361370 char buf [350 ];
@@ -1704,24 +1738,24 @@ compiler_class(struct compiler *c, stmt_ty s)
17041738 compiler_exit_scope (c );
17051739 return 0 ;
17061740 }
1707- /* return the (empty) __class__ cell */
1708- str = PyUnicode_InternFromString ("__class__" );
1709- if (str == NULL ) {
1710- compiler_exit_scope (c );
1711- return 0 ;
1712- }
1713- i = compiler_lookup_arg (c -> u -> u_cellvars , str );
1714- Py_DECREF (str );
1715- if (i == -1 ) {
1716- /* This happens when nobody references the cell */
1717- PyErr_Clear ();
1718- /* Return None */
1719- ADDOP_O (c , LOAD_CONST , Py_None , consts );
1720- }
1721- else {
1741+ if (c -> u -> u_ste -> ste_needs_class_closure ) {
1742+ /* return the (empty) __class__ cell */
1743+ str = PyUnicode_InternFromString ("__class__" );
1744+ if (str == NULL ) {
1745+ compiler_exit_scope (c );
1746+ return 0 ;
1747+ }
1748+ i = compiler_lookup_arg (c -> u -> u_cellvars , str );
1749+ Py_DECREF (str );
1750+ assert (i == 0 );
17221751 /* Return the cell where to store __class__ */
17231752 ADDOP_I (c , LOAD_CLOSURE , i );
17241753 }
1754+ else {
1755+ assert (PyDict_Size (c -> u -> u_cellvars ) == 0 );
1756+ /* This happens when nobody references the cell. Return None. */
1757+ ADDOP_O (c , LOAD_CONST , Py_None , consts );
1758+ }
17251759 ADDOP_IN_SCOPE (c , RETURN_VALUE );
17261760 /* create the code object */
17271761 co = assemble (c , 1 );
0 commit comments