Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Convereter.structure use_alias not working with Union types #706

Open
@SimplyKnownAsG

Description

@SimplyKnownAsG

I'm usingcattrs==25.3.0, and I'm trying to use a Union with subtypes that have aliases. I cannot get either theuse_alias input in Converter nor themake_dict_structure_fn method [mentioned here] to correctly resolve non-conflicting union types while still using the alias. Union types without aliases work just fine. Lists (and presumably dict values) of some type with use_alias also work.

Is there another way this can/should be configured to make it work as I had expected? Is my expectation correct?

fromattrsimportdefine,field,hasfromcattrsimportConverter,gen@defineclassCat:cat_name:str=field(alias="catName")@defineclassDog:dog_name:str=field(alias="dogName")@defineclassApartment:pet:Cat|Dogc0=Converter()c1=Converter(use_alias=True)c2=Converter()c2.register_structure_hook_factory(has,lambdacl:gen.make_dict_structure_fn(cl,c2,_cattrs_use_alias=True))defstructure(data,cls):print("")for (c,prefix)in (                (c0,"default     "),                (c1,"use_alias   "),                (c2,"hook_factory")            ):result=Nonetry:result=c.structure(data,cls)exceptExceptionasex:result=type(ex)print(f"{prefix} structure({data},{cls.__name__}) =={result}")snake_dog=dict(dog_name="snake")camelDog=dict(dogName="camel")snake_cat=dict(cat_name="snake")camelCat=dict(catName="camel")structure(dict(pet=snake_dog),Apartment)structure(dict(pet=camelCat),Apartment)

with output below. I expecteduse_alias andhook_factory to work withcamelCat.

default      structure({'pet': {'dog_name': 'snake'}}, Apartment) == Apartment(pet=Dog(dog_name='snake'))use_alias    structure({'pet': {'dog_name': 'snake'}}, Apartment) == <class 'cattrs.errors.ClassValidationError'>hook_factory structure({'pet': {'dog_name': 'snake'}}, Apartment) == <class 'cattrs.errors.ClassValidationError'>default      structure({'pet': {'catName': 'camel'}}, Apartment) == <class 'cattrs.errors.ClassValidationError'>use_alias    structure({'pet': {'catName': 'camel'}}, Apartment) == <class 'cattrs.errors.ClassValidationError'>hook_factory structure({'pet': {'catName': 'camel'}}, Apartment) == <class 'cattrs.errors.ClassValidationError'>

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp