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

Fix return type annotations for functions used with @contextmanager #8617

Merged
merged 1 commit into from
Oct 30, 2024

Conversation

SpecLad
Copy link
Contributor

@SpecLad SpecLad commented Oct 30, 2024

Motivation and context

Some of them are annotated with an Iterator return type. However...

It just occurred to me that @contextmanager cannot work with a function that returns a plain iterator, since it relies on the generator class's throw method. contextmanager is defined in typeshed as accepting an iterator-returning function, but that appears to be a bug: python/typeshed#2772.

Change all such annotations to a Generator type instead.

Some annotations are also broken in other ways; fix them too.

How has this been tested?

Checklist

  • I submit my changes into the develop branch
  • [ ] I have created a changelog fragment
  • [ ] I have updated the documentation accordingly
  • [ ] I have added tests to cover my changes
  • [ ] I have linked related issues (see GitHub docs)
  • [ ] I have increased versions of npm packages if it is necessary
    (cvat-canvas,
    cvat-core,
    cvat-data and
    cvat-ui)

License

  • I submit my code changes under the same MIT License that covers the project.
    Feel free to contact the maintainers if that's a concern.

Summary by CodeRabbit

  • New Features

    • Enhanced type hinting across multiple methods to clarify their return types as generators, improving code readability and maintainability.
  • Bug Fixes

    • Added comments in the _AvVideoReading class to address potential memory corruption issues with the av library, providing guidance for developers.
  • Documentation

    • Updated method signatures in documentation to reflect changes in return types, ensuring accurate representation of functionality.

Some of them are annotated with an `Iterator` return type. However...

It just occurred to me that `@contextmanager` cannot work with a function
that returns a plain iterator, since it relies on the generator class's
`throw` method. `contextmanager` is defined in typeshed as accepting an
iterator-returning function, but that appears to be a bug:
<python/typeshed#2772>.

Change all such annotations to a `Generator` type instead.

Some annotations are also broken in other ways; fix them too.
Copy link
Contributor

coderabbitai bot commented Oct 30, 2024

Walkthrough

The changes encompass modifications to type hinting across several Python files, specifically altering return types from Iterator to Generator. This includes updates in methods within the Client, ProgressReporter, _AvVideoReading classes, and the atomic_writer function. The adjustments enhance clarity regarding the intended use of these methods as generators that yield values. No changes were made to the underlying logic or functionality, ensuring that existing behaviors remain intact.

Changes

File Path Change Summary
cvat-sdk/cvat_sdk/core/client.py Updated organization_context method return type from Iterator[None] to Generator[None, None, None].
cvat-sdk/cvat_sdk/core/progress.py Updated task method return type from ContextManager[None] to Generator[None, None, None].
cvat-sdk/cvat_sdk/core/utils.py Updated atomic_writer function return type from Iterator[IO] to Generator[IO, None, None].
cvat/apps/engine/media_extractors.py Updated read_av_container method return type from ContextManager[av.container.InputContainer] to Generator[av.container.InputContainer, None, None].
tests/python/cli/util.py Updated https_reverse_proxy function return type from Iterator[str] to Generator[str, None, None].

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ProgressReporter
    participant Utils
    participant MediaExtractor
    participant TestUtil

    Client->>Client: organization_context() -> Generator[None, None, None]
    ProgressReporter->>ProgressReporter: task() -> Generator[None, None, None]
    Utils->>Utils: atomic_writer() -> Generator[IO, None, None]
    MediaExtractor->>MediaExtractor: read_av_container() -> Generator[av.container.InputContainer, None, None]
    TestUtil->>TestUtil: https_reverse_proxy() -> Generator[str, None, None]
Loading

Poem

In the code where rabbits play,
Generators hop and sway.
From iterators, they now leap,
Yielding values, oh so deep!
With every change, we cheer and clap,
For clearer paths on our coding map! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
cvat-sdk/cvat_sdk/core/utils.py (1)

46-46: LGTM: Return type correctly changed to Generator for context manager.

The change from Iterator[IO] to Generator[IO, None, None] is correct because:

  1. It properly specifies the types for a context manager (yield type, send type, return type)
  2. It aligns with Python's typing guidelines for @contextmanager-decorated functions
  3. It matches the actual implementation which yields an IO object

For future reference, when using @contextmanager, always use Generator[YieldType, None, None] as the return type annotation, as context managers don't support send or return operations.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9ecafb6 and 48a69cf.

📒 Files selected for processing (5)
  • cvat-sdk/cvat_sdk/core/client.py (2 hunks)
  • cvat-sdk/cvat_sdk/core/progress.py (2 hunks)
  • cvat-sdk/cvat_sdk/core/utils.py (2 hunks)
  • cvat/apps/engine/media_extractors.py (1 hunks)
  • tests/python/cli/util.py (2 hunks)
🔇 Additional comments (9)
cvat-sdk/cvat_sdk/core/utils.py (1)

16-16: LGTM: Import of Generator type is correctly added.

The addition of Generator import from typing module is necessary and properly placed with other typing imports.

tests/python/cli/util.py (2)

12-12: LGTM: Import statement updated correctly.

The addition of Generator to the imports is necessary for the new type annotation.


42-42: LGTM: Return type annotation correctly updated for @contextmanager usage.

The change from Iterator[str] to Generator[str, None, None] is correct because:

  1. @contextmanager requires a generator function that can handle .throw() method calls
  2. The type parameters accurately reflect the function's behavior:
    • str: the yielded HTTPS URL
    • First None: send type (not used in context managers)
    • Second None: return type (context managers always return None)
cvat-sdk/cvat_sdk/core/progress.py (2)

9-9: LGTM: Appropriate import addition for Generator type.

The addition of Generator to the typing imports is correct and necessary for the updated return type annotation.


29-29: LGTM: Correct return type for @contextmanager function.

The change from ContextManager[None] to Generator[None, None, None] is correct. The Generator type more accurately represents the implementation requirements of @contextmanager, which needs access to the generator's throw() method. The type parameters [None, None, None] correctly specify that the generator:

  • yields None
  • doesn't receive values via send()
  • doesn't return a value
cvat-sdk/cvat_sdk/core/client.py (3)

13-13: LGTM: Import change aligns with type annotation updates.

The addition of Generator to the imports is necessary to support the updated return type annotations for context manager functions.


124-124: LGTM: Correct return type for context manager.

The change from Iterator[None] to Generator[None, None, None] is correct for @contextmanager decorated functions. The Generator type more accurately represents the context manager protocol by specifying:

  • Yield type (None): What the context manager yields
  • Send type (None): No values are sent to the generator
  • Return type (None): No value is returned after cleanup

This change improves type safety as Generator provides the complete type information needed by the context manager protocol.


124-124: Verify consistent usage of Generator type across context managers.

Let's ensure this type annotation change has been consistently applied across all context manager functions in the codebase.

✅ Verification successful

Based on the search results, I can generate the final response now:

Type annotations for context managers are consistently using Generator

The codebase shows consistent usage of Generator type hints for context manager functions. All context managers found are properly typed:

  • make_sdk_client() -> Generator[Client, None, None] in tests
  • organization_context() -> Generator[None, None, None] in cvat-sdk
  • Other context managers are either test utilities or internal implementation details

The remaining Iterator type hints found in the codebase are used appropriately for different iterator implementations and are not related to context managers.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other @contextmanager decorated functions to verify consistent type annotations
echo "Checking for other context manager functions..."
rg --type py "@contextmanager" -B 2 -A 2

# Search for Iterator type annotations that might need to be updated
echo "Checking for remaining Iterator type annotations..."
rg --type py "Iterator\[" -B 2 -A 2

Length of output: 12162

cvat/apps/engine/media_extractors.py (1)

542-544: LGTM! The return type annotation change is correct.

The change from ContextManager to Generator is appropriate here since:

  1. The function is decorated with @contextmanager
  2. The function yields a value (the container)
  3. The type parameters Generator[av.container.InputContainer, None, None] correctly specify:
    • The yielded type: av.container.InputContainer
    • No send type: None
    • No return type: None

@codecov-commenter
Copy link

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 74.30%. Comparing base (bce96ea) to head (48a69cf).
Report is 3 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #8617      +/-   ##
===========================================
+ Coverage    74.22%   74.30%   +0.08%     
===========================================
  Files          403      401       -2     
  Lines        43375    43319      -56     
  Branches      3925     3925              
===========================================
- Hits         32195    32189       -6     
+ Misses       11180    11130      -50     
Components Coverage Δ
cvat-ui 78.70% <ø> (+0.16%) ⬆️
cvat-server 70.55% <100.00%> (+<0.01%) ⬆️

@SpecLad SpecLad merged commit 23e1e0a into cvat-ai:develop Oct 30, 2024
34 checks passed
@SpecLad SpecLad deleted the fix-generator branch October 30, 2024 13:31
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.

2 participants