Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FakeHint returned instead of expected type when deserialising with JsonConverter #12

Open
callumPearce opened this issue Oct 11, 2023 · 0 comments

Comments

@callumPearce
Copy link

from __future__ import annotations
from dataclasses import dataclass
from typing import Annotated, Any
from databind.core import Context, Converter
from databind.json import JsonConverter, load
from typeapi import TypeHint


@dataclass(frozen=True)
class Inner:
    one: str
    two: str

    def __str__(self) -> str:
        f"{self.one}.{self.two}"

    @classmethod
    def from_string(cls, val: str) -> Inner:
        vals = val.split(".")
        return Inner(one=vals[0], two=vals[1])


class InnerConverter(Converter):
    def convert(self, ctx: Context) -> Any:
        if not isinstance(ctx.value, str):
            raise TypeError("expected a string to deserialize Inner")
        if not isinstance(ctx.datatype, TypeHint):
            raise NotImplementedError
        if ctx.direction.is_serialize():
            return str(ctx.value)
        elif ctx.direction.is_deserialize():
            if isinstance(ctx.value, str):
                return Inner.from_string(ctx.value)
            raise NotImplementedError
        assert False, "invalid direction"


@dataclass(frozen=True)
class Outer:
    number: int
    inner: Annotated[Inner, JsonConverter(InnerConverter)]


dict = {"number": 3, "inner": "hello.world"}
loaded = load(dict, Outer)
if not isinstance(loaded.inner, Inner):
    print(type(loaded.inner))

Expected Behaviour

No output is printed as the inner field has type Inner after being deserialised.

Actual Behaviour

Prints type:

<class 'typeapi.future.fake.FakeHint'>
@NiklasRosenstein NiklasRosenstein transferred this issue from NiklasRosenstein/python-databind Nov 10, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant