Descriptor support in msgspec.Struct / dataclasses
Los mantenedores suelen responder en 1 día
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Aptitud para principiantes
- 35/100
Línea de trabajo
Comienza con el ejemplo de descriptor del issue y compara su comportamiento esperado con la documentación enlazada de dataclass de Python. Traza cómo se serializan los objetos de msgspec.Struct y dataclass, y determina si se debe admitir el acceso al descriptor o documentarlo como no admitido; se considera completado cuando el comportamiento elegido está cubierto por pruebas o documentado claramente.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Description
msgspec.Struct and dataclasses differ in how they behave with descriptors.
From the dataclass documentation
Fields that are assigned descriptor objects as their default value have the following special behaviors:
- The value for the field passed to the dataclass’s init() method is passed to the descriptor’s set() method rather than overwriting the descriptor object.
- Similarly, when getting or setting the field, the descriptor’s get() or set() method is called rather than returning or overwriting the descriptor object.
Currently the msgspec documentation has no mention of the behavior with descriptors. From messing around with it, it seems msgspec just overwrites the descriptor object with whatever was passed into the constructor.
Here's an example:
from typing import Any
import msgspec
class AnObj:
def __init__(self, name, val):
self._name = name
self._val = val
class AClass:
def __init__(self, name: str):
self.name = name
self._attr_name = "__art_prop"
def __get__(self, instance, owner) -> AnObj:
print(f"Getting {self._attr_name}")
return AnObj(self.name, getattr(instance, self._attr_name, None))
def __set__(self, instance, value: Any):
print(f"Setting {self._attr_name} to {value}")
setattr(instance, self._attr_name, value)
class MeValue(msgspec.Struct):
aval: int
afile: AClass = AClass("testfile")
@classmethod
def enc_hook(self, obj: Any) -> Any:
"""Custom serialization hook."""
print("enc_hook", type(obj))
if isinstance(obj, AnObj):
return f"AnObj({obj._name}, {obj._val})"
raise NotImplementedError(f"Objects of type {type(obj)} are not supported")
def serialize(self) -> bytes:
"""Serialize the object to json bytes."""
return msgspec.json.Encoder(enc_hook=self.enc_hook).encode(self)
value = MeValue(aval=1, afile=1)
print(value.serialize())
I'd like it to return
b'{"aval":1, "afile": "AnObj(testfile, 1)"}'
on serialization. Currently I get
b'{"aval":1,"afile":1}'
A similar issue arises when trying to serialize dataclasses containing descriptors with the msgspec encoder, since the encoder takes a look at the dataclass object's __dict__, and not the fields returned by dataclasses.fields.
I understand that calling into python for accesses will impact performance and so maybe something this library is against doing. Let me know your thoughts. At the very least, maybe the docs can be updated with a note about descriptor behavior.
- Lenguaje dominante
- Python
- Estrellas
- 4.2k
- Forks
- 209
- Merge medio
- 2 d 3 h
- PR fusionados (30 d)
- 51
Preparar el entorno
Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.
- Sin Dockerfile ni archivo de Docker Compose
- Sin plantilla de pull request
- Leer la 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.
Más de msgspec/msgspec
-
msgpack can't encode a frozendict dict key that it decodes (Python 3.15)Posiblemente ocupada @digit50 la tomó hace 1 día. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 80/100
Los mantenedores suelen responder en 1 día
-
Segfault reading decimal_format after a failed Encoder.__init__ re-callPosiblemente ocupada @digit50 la tomó hace 1 día. Abierto
Dificultad 3/5 1-2 días Aptitud para principiantes 62/100
msgspec/msgspec#1279 · 4 comentarios ·
Los mantenedores suelen responder en 1 día
-
Segfault decoding a TypedDict that references a recursive TypedDict which failed to buildPosiblemente ocupada @Tiancheng-Xu la tomó hace 4 días. Abierto
Dificultad 4/5 3-5 días Aptitud para principiantes 48/100
msgspec/msgspec#1251 · 2 comentarios ·
Los mantenedores suelen responder en 1 día
-
Fix Free-Threading supportPosiblemente ocupada Un pull request vinculado a esta issue está abierto o ya se fusionó. Abiertoenhancement
Dificultad 5/5 Más de una semana Aptitud para principiantes 25/100
msgspec/msgspec#1249 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
convert: mapping fields named like mapping methods (keys, get, ...) resolve to the bound methodPosiblemente ocupada @MbappeWU la tomó hace 3 días. Abierto
Dificultad 3/5 1-2 días Aptitud para principiantes 68/100
Los mantenedores suelen responder en 1 día
Todos los issues de msgspec/msgspec
Issues similares
-
bot-triaged module: LrScheduler module: optimizer triaged
Dificultad 2/5 1-3 horas Aptitud para principiantes 70/100
Los mantenedores suelen responder en 1 día
-
documentation glm5 llm-model
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
vllm-project/vllm-ascend#19062 ·
Los mantenedores suelen responder en 1 día
-
Author Page: shuai-zhao-llmAbiertoauthor-page correction
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
acl-org/acl-anthology#10496 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
Issue Type: Bug Report
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
celery/celery#10875 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
enhancement good first issue
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
SasanLabs/VulnerableApp#836 ·
Los mantenedores suelen responder en 1 día