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

feat: add typevar expansion #3242

Merged
merged 4 commits into from
Mar 23, 2024
Merged

Conversation

harryle95
Copy link
Contributor

Description

Add a method for typevar expansion on registration
This allows the use of generic route handler and generic controller without relying on forward references.

Closes #3206

A self-contained example - which would fail in the previous version:

from dataclasses import dataclass, field
from typing import Generic, TypeVar
from uuid import UUID, uuid4

from litestar import Controller, Litestar, Router, post


@dataclass
class BookDataClass:
    title: str
    id: UUID = field(default_factory=uuid4)


@dataclass
class AuthorDataClass:
    title: str
    id: UUID = field(default_factory=uuid4)


T = TypeVar("T")


class GenericController(Controller, Generic[T]):
    model_class: T

    def __class_getitem__(cls, model_class: type) -> type:
        cls_dict = {"model_class": model_class}
        return type(f"GenericController[{model_class.__name__}", (cls,), cls_dict)

    def __init__(self, owner: Router) -> None:
        super().__init__(owner)
        self.signature_namespace[T] = self.model_class  

class BaseController(GenericController[T]):
    @post()
    async def create(self, data: T) -> T:  
        return data


class AuthorDataClassController(BaseController[AuthorDataClass]):
    path = "/AuthorDataClass"


class BookDataClassController(BaseController[BookDataClass]):
    path = "/BookDataClass"
    signature_namespace = {"S": int, "U": float}


app = Litestar([AuthorDataClassController, BookDataClassController])

All failed tests were not caused by this new update. Please let me know what you think.

@harryle95 harryle95 requested review from a team as code owners March 22, 2024 12:04
@harryle95 harryle95 changed the title feat: add typevar expansion #3240 feat: add typevar expansion Mar 22, 2024
Copy link

codecov bot commented Mar 22, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 98.25%. Comparing base (4b79615) to head (95d20c4).

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #3242   +/-   ##
========================================
  Coverage    98.25%   98.25%           
========================================
  Files          322      322           
  Lines        14666    14670    +4     
  Branches      2333     2334    +1     
========================================
+ Hits         14410    14414    +4     
  Misses         116      116           
  Partials       140      140           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Comment on lines 135 to 143
"""Expand TypeVar for any parameters in type_hint

Args:
type_hint: mapping of parameter to type obtained from calling `get_type_hints` or `get_fn_type_hints`
namespace: mapping of TypeVar to concrete type

Returns:
type_hint with any TypeVar parameter expanded
"""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"""Expand TypeVar for any parameters in type_hint
Args:
type_hint: mapping of parameter to type obtained from calling `get_type_hints` or `get_fn_type_hints`
namespace: mapping of TypeVar to concrete type
Returns:
type_hint with any TypeVar parameter expanded
"""
"""Expand :class:`~typing.TypeVar` for any parameters in ``type_hint``
Args:
type_hint: mapping of parameter to type obtained from calling ``get_type_hints`` or ``get_fn_type_hints``
namespace: mapping of :class:`~typing.TypeVar` to concrete type
Returns:
``type_hint`` with any :class:`~typing.TypeVar` parameter expanded
"""

Copy link
Member

@guacs guacs left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @haryle! This is a cool change.

Copy link
Contributor

@peterschutt peterschutt left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @haryle - LGTM!

One nit, can we please not add arbitrary style changes - there are a few cases of added line wraps for imports that would otherwise be lines untouched by the PR. Perhaps you have some global formatter settings that conflict with ours?

Cheers

Comment on lines 40 to 47
from typing_extensions import (
Annotated,
NotRequired,
Required,
get_args,
get_origin,
get_type_hints,
)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please limit the changes to those necessary for the PR.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, all the import formating changes were done by my linter. I will reformat them.

TypedDict,
get_args,
get_type_hints,
)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.

Copy link
Member

@guacs guacs left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is good to go after the comments by @peterschutt has been resolved :)

Copy link

Documentation preview will be available shortly at https://litestar-org.github.io/litestar-docs-preview/3242

Copy link
Contributor

@peterschutt peterschutt left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@peterschutt peterschutt merged commit 96c59fe into litestar-org:develop Mar 23, 2024
20 checks passed
@harryle95 harryle95 deleted the develop branch March 23, 2024 10:20
@JacobCoffee
Copy link
Member

@all-contributors add @haryle code tests

Copy link
Contributor

@JacobCoffee

I've put up a pull request to add @haryle! 🎉

provinzkraut pushed a commit that referenced this pull request Mar 29, 2024
* feat: add typevar expansion #3240

* chore: resolve all PR suggestion #3242

* chore: resolve import formatting

* chore: resolve import formatting
provinzkraut pushed a commit that referenced this pull request Mar 29, 2024
* feat: add typevar expansion #3240

* chore: resolve all PR suggestion #3242

* chore: resolve import formatting

* chore: resolve import formatting
provinzkraut pushed a commit that referenced this pull request Mar 30, 2024
* feat: add typevar expansion #3240

* chore: resolve all PR suggestion #3242

* chore: resolve import formatting

* chore: resolve import formatting
JacobCoffee pushed a commit that referenced this pull request Apr 5, 2024
* feat: add typevar expansion #3240

* chore: resolve all PR suggestion #3242

* chore: resolve import formatting

* chore: resolve import formatting
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

Successfully merging this pull request may close these issues.

4 participants