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

Add support for typing.NewType fields #1114

Open
loopj opened this issue Jan 17, 2025 · 0 comments
Open

Add support for typing.NewType fields #1114

loopj opened this issue Jan 17, 2025 · 0 comments
Labels
enhancement New feature or request

Comments

@loopj
Copy link

loopj commented Jan 17, 2025

It is sometimes convenient to use typing.NewType when defining model fields, to provide additional static type checking.

Here's a contrived example:

Speed = NewType("Speed", float) # Speed in MPH

@dataclass
class Car:
    speed: Speed

At runtime, python effectively converts Speed straight back into a float:

>>> car = Car(100.0)
>>> car.speed
100.0

>>> type(car.speed)
<class 'float'>

But since xsdata is using get_type_hints under the hood, this returns the type hinted type directly:

>>> get_type_hints(Car)
{'speed': car.Speed}

>>> type(get_type_hints(Car)["speed"])
<class 'typing.NewType'>

>>> get_type_hints(Car)["speed"].__supertype__
<class 'float'>

This causes parsing to blow up:

xsdata.exceptions.XmlContextError: Error on Car::speed: Xml Attribute does not support typing `car.Speed`

I propose we add a built-in converter for typing.NewType types, which handles these cases by calling __supertype__.

@tefra tefra added the enhancement New feature or request label Jan 19, 2025
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

No branches or pull requests

2 participants