Assigning attribute to instance method causes AttributeError
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Python
- Estrellas
- 77.2k
- Forks
- 36k
- Métricas de merge de PR
- Métricas de PR pendientes
Descripción
Bug report
Assigning (and reassigning) attributes to functions works as expected as with any object.
def bar(self):
...
bar.something = 1
print(bar.something)
# prints: 1
bar.something = 2
print(bar.something)
# prints: 2
However, the experience is not consistent with class methods. When dealing with the class, you can assign and reassign similar to regular functions.
class Foo:
def bar(self):
...
Foo.bar.something = 1
print(Foo.bar.something)
# prints: 1
Foo.bar.something = 2
print(Foo.bar.something)
# prints: 2
This even carries through after instantiation:
foo = Foo()
print(foo.bar.something)
# prints: 2
We can clearly see the value exists in the __dict__:
print(foo.bar.__dict__)
# {'something': 2}
However, trying to assign to the method from the instance fails:
foo.bar.something = 2
# AttributeError: 'method' object has no attribute 'something'
While I guess I can see why this might be (since you would be modifying an object on the class and not the instance--if this indeed is the rationale), this is not intuitive. It seems inconsistent with setting attributes otherwise.
If this behavior is intended and not a bug, then perhaps the error should be more explicit. The error stating that the method has no attribute named something is not correct. It does have the attribute and we can otherwise interact with it, just not set it.
Either we should be able to assign back to that attribute from the instance, or we should receive a more explicit error why this is not possible.
Your environment
- CPython versions tested on: 3.7.12, 3.8.11, 3.9.9, 3.10.8, 3.11.0rc1
- Operating system and architecture:
▶ uname -a
Linux hopkins 6.0.2-arch1-1 #1 SMP PREEMPT_DYNAMIC Sat, 15 Oct 2022 14:00:49 +0000 x86_64 GNU/Linux
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Comienza reproduciendo los ejemplos de asignación de atributos a métodos de instancia del issue en las versiones de Python afectadas. Revisa el comportamiento de los atributos de método y de los descriptores antes de decidir si se debe admitir la asignación o aclarar el error; el trabajo estará completo cuando haya un comportamiento acordado y la cobertura de regresión correspondiente.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- python
- Área
- backend
- Tipo de issue
- Error
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Estado de actividad
- Estancado
- Claridad
- Necesita aclaración
- Aptitud para principiantes
- 25/100