pydantic icon indicating copy to clipboard operation
pydantic copied to clipboard

Allow computed fields (and methods) to be provided with `create_model()`

Open Viicos opened this issue 8 months ago • 5 comments

Initial Checks

  • [x] I have searched Google & GitHub for similar requests and couldn't find anything
  • [x] I have read and followed the docs and still think this feature is missing

Description

As per https://github.com/pydantic/pydantic/issues/11708 and https://github.com/pydantic/pydantic/discussions/7760.

Affected Components

Viicos avatar Apr 07 '25 09:04 Viicos

@Viicos

Hi, I did some additional investigation.

After the change pydantic/pydantic#11032, which caused the issue, it turns out that PydanticDescriptorProxy objects are now stored in __annotations__.

As a result, it's no longer possible to iterate over them during the DecoratorInfos.build call. Hope this helps a bit ;)

karta9821 avatar Apr 07 '25 18:04 karta9821

I just ran into this. Did anyone come up with a hotfix that worked for them?

esad-pomelo avatar Apr 21 '25 14:04 esad-pomelo

A possible fix - make the annotation declaration optional:

https://github.com/pydantic/pydantic/blob/2e7cddb6a7600311c4a29763efd55596a826edde/pydantic/main.py#L1742-L1746

     annotations[f_name] = f_def[0] 
     fields[f_name] = f_def[1] 
 else: 
     annotations[f_name] = f_def 

            if f_def[0]:
                annotations[f_name] = f_def[0]
            fields[f_name] = f_def[1]
        else:
            annotations[f_name] = f_def

I've copied create_model to include this.

https://github.com/commonism/aiopenapi3/blob/167c51068c8a59126d03ab3193d72d610d3dcbd9/aiopenapi3/pydanticv2.py#L38-L116

It defines fields without annotation instead of using None as annotation. I use it for properties.

commonism avatar Apr 22 '25 05:04 commonism

As a workaround that can be used with the current create_model() function, anything can be passed to __validators__ (it is used directly to update the class namespace).

I think we'll add a new parameter (something like __namespace_updates__ or similar), and we may deprecate __validators__ in favor of this one.

Viicos avatar Apr 29 '25 09:04 Viicos

As it's too late for 2.12, any chance for 2.13?

commonism avatar Nov 11 '25 13:11 commonism