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

Type checking for Custom Generics #160

Open
codedecde opened this issue Sep 17, 2021 · 3 comments · May be fixed by #209
Open

Type checking for Custom Generics #160

codedecde opened this issue Sep 17, 2021 · 3 comments · May be fixed by #209
Labels
enhancement New feature or request

Comments

@codedecde
Copy link

codedecde commented Sep 17, 2021

Currently, is_instance fails for any generic type
Eg:

from dataclasses import dataclass
from typing import Generic, TypeVar
import dacite

T = TypeVar('T')
@dataclasses
class A(Generic[T]):
    a: str
    
obj = A[str](a='hi')
dacite.types.is_instance(obj, A[str])  # False

This impacts cases when custom generics are a part of dataclass instances, requiring disabling type_checking for creation of all attributes.
Eg:

from typing import Generic, TypeVar
from dataclasses import dataclass
import dacite
T = TypeVar('T')
@dataclass
class A(Generic[T]):
    a: str
@dataclass
class B:
    x: int
    y: A[str]
obj = dacite.from_dict(B, {"x": 3, "y": {"a": "hi"}}, config=dacite.config.Config(check_types=False))  # check_types=True fails

One potential solution:
Make a best effort check for generic types by checking if the obtained value is an instance of the origin class of the generic type. Specifically, add

elif is_generic(type_):
    return isinstance(value, type_.__origin__)

After this line.

Related: #131, #157

@konradhalas konradhalas added the enhancement New feature or request label Apr 12, 2022
@mciszczon mciszczon linked a pull request Jan 12, 2023 that will close this issue
5 tasks
@avlonder
Copy link

FYI, I forked dacite and made some changes to make generics work. I use it in a personal project where I have more unit tests written around it. Did not find issues until now (python 3.9).

@mciszczon
Copy link
Collaborator

FYI, I forked dacite and made some changes to make generics work. I use it in a personal project where I have more unit tests written around it. Did not find issues until now (python 3.9).

Hi, asking here as well: would you be interested in making a PR back to this repo? Thanks! :)

@avlonder
Copy link

avlonder commented Jan 11, 2025

Hi, asking here as well: would you be interested in making a PR back to this repo? Thanks! :)

Sure, I'll update the docs and add some tests first though.

Edit: Done.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants