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

Casting Protocol #187

Open
ZeroIntensity opened this issue Jun 19, 2024 · 0 comments
Open

Casting Protocol #187

ZeroIntensity opened this issue Jun 19, 2024 · 0 comments
Assignees
Labels
api This has to do with the Python API (view) c api This has to do with the C API (_view) complex This should only be looked at by someone who knows what they're doing feature New feature
Milestone

Comments

@ZeroIntensity
Copy link
Owner

Proposal:

view.py should support casting any arbitrary type through a __view_cast__ protocol. This will make file upload types in #174 possible. Adding asynchronous support will be a royal pain in the ass, but I can't really get around that.

Example API

from view import new_app
from typing import Self

app = new_app()
ViewNativeType = str | int | bytes | ...  # Rest of the native types, this will go in the view.typing module

class MyCustomType:
    def __init__(self, whatever: str) -> None:
        self.whatever = whatever

    @classmethod
    async def __view_cast__(cls, obj: ViewNativeType) -> Self:
        if not isinstance(obj, str):
            raise TypeError("")  # This could possibly be something like a TypeCastError?
        return cls(obj)

@app.get("/")
@app.body("something", MyCustomType)
async def index(something: MyCustomType):
    return something.whatever

app.run()

It might be a good idea to remove __view_body__ and __view_construct__, or at least add some sort of base class to implement the behavior using __view_cast__:

class SupportsViewBody:
    __view_body__: ClassVar[dict[str, type[Any]]]

    async def __view_cast__(cls, obj: ViewNativeType) -> Self:
        if not isinstance(obj, dict):
            raise TypeError(...)

        # We can use our own TypeCode API!
        tp = compile_type(cls.__view_body__)
        return tp.cast(obj)
@ZeroIntensity ZeroIntensity added feature New feature complex This should only be looked at by someone who knows what they're doing c api This has to do with the C API (_view) api This has to do with the Python API (view) labels Jun 19, 2024
@ZeroIntensity ZeroIntensity self-assigned this Jun 19, 2024
@ZeroIntensity ZeroIntensity added this to the Beta Release milestone Jun 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
api This has to do with the Python API (view) c api This has to do with the C API (_view) complex This should only be looked at by someone who knows what they're doing feature New feature
Projects
None yet
Development

No branches or pull requests

1 participant