coady / multimethod

Multiple argument dispatching.
https://coady.github.io/multimethod
Other
284 stars 23 forks source link

Doesn't work properly with pydantic types #78

Closed akhundMurad closed 1 year ago

akhundMurad commented 1 year ago

Hello! I am trying to use it with pydantic.BaseModel and I am facing the issue:

class Mapper:
    @multimethod
    def map(self, source, target_type):
        ...

    @map.register
    def _(self, source: ProfileDTO, target_type: typing.Type[UserDTO]) -> UserDTO:
        # logic
        ...

Where ProfileDTO and UserDTO are pydantic models.

Then I am trying to use this class:

mapper = Mapper()
mapper.map(profile, UserDTO)

But the library doesn't use the registered method, because it recognizes typing.Type[UserDTO] construction like pydantic.main.ModelMetaclass.

Is there some solution for this?

coady commented 1 year ago

It should work with pydantic classes, that is, anything which supports issubclass. The problem appears to be not supporting Type[...]. Some workarounds to try which are similar:

akhundMurad commented 1 year ago

Thanks for quick response!