Skip to content
Advertisement

Serialising with cattrs and want to omit field x1 string field

Using cattrs to structure data and I want to omit x1 string field.

I want to perform a trivial cleanup on strings that have been passed in except for the password field.

I can get it to work on all strings

JavaScript

I can fool cattrs by passing in the adminpass field as Any

JavaScript

but this is a bit clunky.

The docs show how to omit individual fields – but I can’t figure out how then I would call the tidystr function. Following the docs closely I would do

JavaScript

which obviously won’t work because tidystr() isn’t being called.

I’ve tried various ways and am lost. The docs also show something like what I’m trying to do but the example is changing the keys not the values.

Advertisement

Answer

I’m the author of cattrs. Let’s see how we can solve this.

First we need a way to recognize which fields you want to tidy up and which you don’t. Looks like you’d like to apply tidying to all strings by default and opt-out for some fields.

Option #1: NewType

Use a NewType for the password field.

JavaScript

(Any function taking a string will happily take a NewType based on it instead, and it’ll actually be a string at runtime.)

Option 2: Annotated

We can use typing.Annotated to build our own little mini system for structuring.

The class becomes:

JavaScript

Then, we need to create the appropriate hook:

JavaScript

The implementation is a little gnarly since Python doesn’t have super good type inspection capabilities, but we can use an internal cattrs function instead.

This approach is, in general, very powerful.

Option 3: wait for 22.3.0

I’m adding an option to override the structure and unstructure functions for individual fields in the next version. Then, you’ll be able to do something like:

JavaScript

Can’t promise a release date though ;)

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