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

Event field types include None but (maybe) shouldn't #1298

Closed
timoffex opened this issue Feb 10, 2025 · 2 comments
Closed

Event field types include None but (maybe) shouldn't #1298

timoffex opened this issue Feb 10, 2025 · 2 comments

Comments

@timoffex
Copy link
Contributor

With the new 4.2.0 release that adds the py.typed marker, mypy is reporting that my Event handling code should be ready for None values. For instance,

if isinstance(event, h2.events.RequestReceived):
    stream = HTTP2StreamHandler(
        self._state,
        event.stream_id, # mypy: incompatible type "int | None"; expected "int"
        event.headers,   # mypy: incompatible type "list[HeaderTuple] | None"; expected "Iterable[HeaderTuple]"
    )

I can expect these fields to always be set, right? I could add assert statements like this:

if isinstance(event, h2.events.RequestReceived):
    assert event.stream_id is not None
    assert event.headers is not None
    stream = HTTP2StreamHandler(
        self._state,
        event.stream_id,
        event.headers,
    )

But it's clunky to make users do this.

I see that Event objects are constructed incrementally, so their fields can be None temporarily in h2 code, but I wish the types could reflect what I should expect as a user. What would you think of something like this?

class RequestReceived(Event):
    stream_id: int
    headers: list[HeaderTuple]

    def __init__(self) -> None:
        self.stream_ended: StreamEnded | None = None
        self.priority_updated: PriorityUpdated | None = None

It would work as long as h2 itself does not access stream_id / headers before setting them.

@Kriechi
Copy link
Member

Kriechi commented Feb 10, 2025

This should now already be addressed in #1296 - please review and provide feedback!

@timoffex
Copy link
Contributor Author

Wonderful, I should have known you guys were already a step ahead! It looks like the PR fixes all the events I was using, so I will close the issue.

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

No branches or pull requests

2 participants