cattrs icon indicating copy to clipboard operation
cattrs copied to clipboard

takes_metadata option for Factory

Open delfick opened this issue 3 years ago • 1 comments

  • cattrs version: 1.10.0
  • Python version: 3.10
  • Operating System: Mac

Description

Hello,

Is it possible to add a takes_metadata like option to cattrs.Factory similar to the takes_self but provides some kind of metadata object you provide when you call converter.structure?

This way I can create an instance of a class that can be slightly different depending on the metadata (or context) I provide converter.structure when I make the class.

Something similar is mentioned here https://github.com/python-attrs/cattrs/issues/90#issuecomment-648462067 but that's for the whole converter rather than per property on the class

delfick avatar Feb 16 '22 06:02 delfick

I ended up making https://strcs.readthedocs.io to make this possible. it works quite well. Essentially it's a cattrs structure hook that then uses creator functions that I create.

One problem I have though is that I have to clear the entire _structure_func.dispatch cache in a couple places https://github.com/delfick/strcs/blob/main/strcs/base.py#L432 (it's necessary to drop down to what cattrs would do for that field in a way that means it still goes back to my hook, but the dispatch cache means it doesn't call my check function again)

I was wondering if there were options available to cattrs to change how that caching works so I only have to reset the cache for the current type rather than all types?

delfick avatar Oct 30 '22 01:10 delfick