Skip to content

Make annotation for methods more permissive #2903

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

jonathanberthias
Copy link

Summary

The type annotation for methods in the Route constructor restricts the input to lists of strings when it can accept any iterable. The methods on the Route itself are stored as a set.

I had the issue when I was trying to build new routes from other preexisting routes:

new_route = Route(
    route.path.replace("/prefix1", "/prefix2"),
    route.endpoint,
    methods=route.methods,  # type error: Argument "methods" to "Route" has incompatible type "set[str] | None"; expected "list[str] | None"
    name=f"new_{route.name}",
)

I changed the annotation to Collection, though the current implementation would work with any Iterable. Collection allows lists, sets, tuples, and Iterable would also allow generators. Let me know what you prefer.

Checklist

  • I understand that this PR may be closed in case there was no previous discussion. (This doesn't apply to typos!)
  • I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
  • I've updated the documentation accordingly.

@@ -211,7 +211,7 @@ def __init__(
path: str,
endpoint: typing.Callable[..., typing.Any],
*,
methods: list[str] | None = None,
methods: typing.Collection[str] | None = None,
Copy link
Member

Choose a reason for hiding this comment

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

We typically use typing.Sequence across the project.

Copy link
Author

Choose a reason for hiding this comment

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

Indeed, but in this case it makes sense to allow sets in addition to list and tuples

Copy link

Choose a reason for hiding this comment

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

Reminder: https://docs.python.org/3/library/typing.html#deprecated-aliases
Shouldn't we start applying new standards?

Copy link
Author

Choose a reason for hiding this comment

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

I followed the current convention of importing everything from the typing module, but if #2867 gets merged before this PR, then I'll adjust 😄

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.

3 participants