Skip to content
Advertisement

Converting arguments to custom objects using dataclasses package

I recently discovered the dataclasses Python package. I’m running into an issue when using custom classes in my type annotation. I’ve got a simple example below.

When the Entry class gets passed the location argument, the value of that argument should be used to construct a Location object. Similarly, when the Entry class gets passed a string for the creationDate argument, it should be parsed (using dateutil.parser.parse) to create a datetime.datetime object. In my code, the location and creationDate arguments are not converted to the Location and datetime.datetime objects. I’m not sure how to make this work. Please advise.

Granted, I could do this without using the dataclasses package. It would add more boilerplate code. I’m also using this as an excuse to learn the dataclasses package so I can use it more efficiently the next time.

Try it

JavaScript

Advertisement

Answer

One option could be to use dataclass-wizard, which is a bit more lightweight than pydantic. It uses typing-extensions module for earlier python versions, but in 3.10+ it only relies on core python stdlib.

Usage:

JavaScript

Result:

JavaScript

Side note: I haven’t actually thought of using dateutil.parser.parse to parse date strings, though that might be a good idea coinidentally. The current implementation uses datetime.fromisoformat which does work well enough in the general use case.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement