python / python/cpython

AttributeError on `with super()`

Aberta
#129,466 13 comentários 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

interpreter-core type-feature
Linguagem predominante
Python
Estrelas
77.2k
Forks
36k
Métricas de merge de PRs
Métricas de PR pendentes

Descrição

Bug report

Bug description:

Writing with super() raises an AttributeError. I ran into this implementing context managers inspired by contextlib.contextmnager but which had extra functionality. I can see no reason why with super() should be disallowed, and in fact, super().__enter__() and super().__exit__() work just fine.

Attempting to use an ExitStack as a work around was unsuccessful.

import sys
from contextlib import ExitStack

class Base:
    def __enter__(self):
        print("Entering base context manager")

    def __exit__(self, type, value, traceback):
        print("Exiting base context manager")

def __derived_enter__(self):
    self.context = self.contextlib_style_context()
    next(self.context)
    return self.context

def __derived_exit__(self, type, value, traceback):
    try:
        next(self.context)
    except StopIteration:
        pass

class DerivedUsingEnterExit(Base):
    def contextlib_style_context(self):
        print("Entering contextlib style context manager")
        super().__enter__()
        try:
            yield
        finally:
            super().__exit__(*sys.exc_info())

        print("Exiting contextlib style context manager")

    __enter__ = __derived_enter__
    __exit__ = __derived_exit__

class DerivedUsingWith(Base):
    def contextlib_style_context(self):
        print("Entering contextlib style context manager")
        with super():
            yield

        print("Exiting contextlib style context manager")

    __enter__ = __derived_enter__
    __exit__ = __derived_exit__

class DerivedUsingExitStack(Base):
    def contextlib_style_context(self):
        print("Entering contextlib style context manager")

        with ExitStack() as stack:
            stack.enter_context(super())
            yield

        print("Exiting contextlib style context manager")

    __enter__ = __derived_enter__
    __exit__ = __derived_exit__

# Runs successfully
with DerivedUsingEnterExit() as d:
    pass

# Raises AttributeError
with DerivedUsingWith() as d:
    pass

# Raises AttributeError
with DerivedUsingExitStack() as d:
    pass
CPython versions tested on:

3.13, 3.12

Operating systems tested on:

Windows

Guia de contribuição

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Direção de pesquisa

Comece reproduzindo os exemplos fornecidos de DerivedUsingWith e DerivedUsingExitStack no CPython 3.13 ou 3.12 e, em seguida, rastreie os pontos de entrada envolvidos de super() e do gerenciador de contexto. Compare-os com o caso funcional de super().enter() e super().exit(); concluído significa que o comportamento pretendido foi decidido e que o AttributeError relatado está coberto por um teste de regressão.

Escrita pelo modelo de indexação a partir do texto da issue.

Avaliação

Stack de tecnologia
python
Domínio
compilers
Tipo de issue
Bug
Dificuldade
4/5
Tempo estimado
3-5 dias
Status de atividade
Estagnada
Clareza
Razoavelmente clara
Facilidade para iniciantes
35/100

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.