ramonhagenaars / jsons

🐍 A Python lib for (de)serializing Python objects to/from JSON
https://jsons.readthedocs.io
MIT License
288 stars 40 forks source link

`attr_getters` attrs not available during `__post_init__` #156

Open paulmakepeace opened 2 years ago

paulmakepeace commented 2 years ago

I'm trying to pass in a config object that can be used to set defaults for attributes dynamically:

from dataclasses import dataclass
import jsons

@dataclass
class Car(jsons.JsonSerializable):
  engine: str = None

  def __post_init__(self):
    if self.engine is None
      self.engine = self.config["engine_default"]

car = Car.loads("{}", attr_getters={"config": lambda: {"engine_default": "mid"}})

fails with,

jsons.exceptions.DeserializationError:
  Could not deserialize value "{}" into "__main__.Car". 'Car' object has no attribute 'config'

(If there's no __post_init__, car.config works just fine here, but later in the cycle.)

If there's a better way of achieving this I'd be happy to hear it--I'd likely use the same idea to inject a logger dependency too.