python / python/cpython

missing global names inside a class body (calling `exec` with a `ChainMap`)

Offen
#121,306 19 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

interpreter-core triaged type-feature
Vorherrschende Sprache
Python
Sterne
77.2k
Forks
36k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug report

Bug description:

I need to implement layered context running python code, so I choose ChainMap. But Python needs every globals passed to exec to be a dict, so I mixins it into ChainMap.

This patch runs well as far, but in a class it can't get the value from the outside.

I think this may because in the class context CPython uses some function like PyDict_Get instead of __getitem__, so the values didn't get copied into the class's globals context.

This bug caused this code fails:

from collections import ChainMap

class ChainMap(ChainMap, dict):  # globals must be a real dict
    pass

source = """
a = 1

class A:
    print(a)
"""

exec(source, ChainMap())  # this line raises NameError
Other reproduction approaches

This is reproduceable in pyodide (a wasm port of CPython 3.12.1), so you can run the code above by just clicking one of the following link:

  • Stackblitz - you can edit code and the result will sync instantly
  • Python Online - this is faster but just has a console instead of an IDE

CPython versions tested on:

3.12

Operating systems tested on:

Linux, Windows

Linked PRs
  • gh-121389

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne damit, den Fehler bei exec(source, ChainMap()) mit dem Beispiel der Klasse A auf CPython 3.12 zu reproduzieren, und untersuche dann den Pfad der Namensauflösung im Klassenrumpf. Vergleiche das Verhalten mit einem echten dict und prüfe den verlinkten PR gh-121389; abgeschlossen ist die Arbeit, wenn der äußere Name innerhalb des Klassenrumpfs verfügbar ist, ohne das bestehende exec-Verhalten zu beeinträchtigen.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
compilers
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
25/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.