Skip to content

Switch to Python 3.9+ type annotation syntax everywhere#539

Open
NobleCoder69 wants to merge 1 commit intoneurobagel:mainfrom
NobleCoder69:fix-type-annotations-518
Open

Switch to Python 3.9+ type annotation syntax everywhere#539
NobleCoder69 wants to merge 1 commit intoneurobagel:mainfrom
NobleCoder69:fix-type-annotations-518

Conversation

@NobleCoder69
Copy link

@NobleCoder69 NobleCoder69 commented Mar 4, 2026

Replaced legacy typing syntax (Optional, Union, List, etc.)
with Python 3.9+ built-in generics and PEP 604 union types.

Examples:

  • Optional[str] → str | None
  • Union[A, B] → A | B
  • List[str] → list[str]

All tests passing (145/145).

Summary by Sourcery

Modernize type annotations to use Python 3.9+ syntax across API models and utility helpers.

Enhancements:

  • Update Pydantic API models to use PEP 604 union types and built-in collection generics instead of legacy typing.Optional/Union forms.
  • Align utility function signatures with the newer type annotation style for optional and collection parameters.

Copilot AI review requested due to automatic review settings March 4, 2026 20:39
@sourcery-ai
Copy link

sourcery-ai bot commented Mar 4, 2026

Reviewer's Guide

Refactors type annotations to use Python 3.9+ syntax (PEP 585 built-in generics and PEP 604 unions) across API models and utility helpers, replacing Optional/Union and untyped collections with the newer T | None and list[T] style while keeping runtime behavior the same.

Class diagram for updated API response and query models

classDiagram
    class QueryModel {
        +float min_age
        +float max_age
        +str sex
        +str diagnosis
        +int min_num_imaging_sessions
        +int min_num_phenotypic_sessions
        +str assessment
        +str image_modal
        +str pipeline_name
        +str pipeline_version
        +check_maxage_ge_minage() QueryModel
    }

    class SessionResponse {
        +str subject_id
        +str dataset_uuid
        +int num_matching_phenotypic_sessions
        +int num_matching_imaging_sessions
        +str session_type
        +float age
        +str sex
        +list diagnosis
        +str subject_group
        +list assessment
        +list image_modal
        +str session_file_path
        +dict completed_pipelines
    }

    class CohortQueryResponse {
        +str dataset_uuid
        +str dataset_name
        +str dataset_portal_uri
        +int dataset_total_subjects
        +bool records_protected
        +int num_matching_subjects
        +list image_modals
        +dict available_pipelines
        +list~SessionResponse~ subject_data
    }

    class DatasetQueryResponse {
        +str dataset_uuid
        +str dataset_name
        +list~str~ authors
        +str homepage
        +list~str~ references_and_links
        +list~str~ keywords
        +str repository_url
        +str access_instructions
        +str access_type
        +str access_email
        +str access_link
        +int dataset_total_subjects
        +bool records_protected
        +int num_matching_subjects
    }

    class SubjectsQueryResponse {
        +str dataset_uuid
        +list~SessionResponse~ subject_data
    }

    class StandardizedTermVocabularyNamespace {
        +str vocabulary_name
        +str namespace_url
        +str namespace_prefix
        +str version
        +list~dict~ terms
    }

    CohortQueryResponse "*" o-- "*" SessionResponse : uses
    SubjectsQueryResponse "*" o-- "*" SessionResponse : uses
Loading

File-Level Changes

Change Details Files
Update Pydantic model fields to Python 3.9+ union syntax and clarify optionality.
  • Change nullable scalar fields from implicit optional types to explicit `T
None(e.g.,min_age, max_age, sex, diagnosis, pipeline-related fields).</li><li>Update response models to replace Optional[T]andUnion[list[SessionResponse], str]withT
Update utility query-builder function signature to Python 3.9+ type syntax.
  • Replace Optional[...] annotations with `...
Nonefor scalar parameters such assex, diagnosis, and session counts.</li><li>Annotate ageastuple

Possibly linked issues

  • #: PR replaces Optional/Union/List, etc. with 3.9+ generics and union syntax, exactly fulfilling the issue request.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@github-actions github-actions bot added the _community [BOT ONLY] PR label for community contributions. Used for tracking label Mar 4, 2026
Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

We've reviewed this pull request using the Sourcery rules engine

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Migrates type annotations to Python 3.9+ syntax (built-in generics and PEP 604 unions) across API utilities and Pydantic models.

Changes:

  • Replaced Optional[...]/Union[...] with T | None and A | B.
  • Began shifting to built-in generic aliases (e.g., list[...]).
  • Updated model field annotations to reflect optionality more explicitly.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.

File Description
app/api/utility.py Updates create_query parameter type hints to PEP 604 unions and removes Optional import.
app/api/models.py Converts Pydantic model field annotations from Optional/Union to `

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.


from enum import Enum
from typing import Optional, Union
# remove this line completely
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

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

This looks like a temporary PR note that was accidentally committed into the source. Please remove this comment and, if needed, replace it with the actual intended change (i.e., delete the unused typing import line rather than leaving an instruction in code).

Suggested change
# remove this line completely

Copilot uses AI. Check for mistakes.
pipeline_name: Optional[str] = None,
pipeline_version: Optional[str] = None,
dataset_uuids: Optional[list] = None,
age: tuple | None = (None, None),
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

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

These annotations are very broad (tuple and list without element types), which weakens type checking and IDE support. Consider specifying element types (e.g., tuple[float | None, float | None] | None for age and list[str] | None for dataset_uuids, if those match the actual expected values).

Copilot uses AI. Check for mistakes.
image_modal: str | None = None,
pipeline_name: str | None = None,
pipeline_version: str | None = None,
dataset_uuids: list | None = None,
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

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

These annotations are very broad (tuple and list without element types), which weakens type checking and IDE support. Consider specifying element types (e.g., tuple[float | None, float | None] | None for age and list[str] | None for dataset_uuids, if those match the actual expected values).

Copilot uses AI. Check for mistakes.
Comment on lines +49 to +56
sex: str | None = Field(default=None, pattern=CONTROLLED_TERM_REGEX, examples=["vocab:12345"])
diagnosis: str | None = Field(default=None, pattern=CONTROLLED_TERM_REGEX, examples=["vocab:12345"])
min_num_imaging_sessions: int | None = Field(default=None, ge=0)
min_num_phenotypic_sessions: int | None = Field(default=None, ge=0)
assessment: str | None = Field(default=None, pattern=CONTROLLED_TERM_REGEX, examples=["vocab:12345"])
image_modal: str | None = Field(default=None, pattern=CONTROLLED_TERM_REGEX, examples=["vocab:12345"])
pipeline_name: str | None = Field(default=None, pattern=CONTROLLED_TERM_REGEX, examples=["vocab:12345"])
pipeline_version: str | None = Field(default=None, pattern=VERSION_REGEX, examples=["1.0.0"])
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

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

These lines are quite long and harder to scan/review. Consider formatting these Field(...) calls across multiple lines (as they were previously) or running the project formatter (e.g., Black) so arguments wrap consistently.

Copilot uses AI. Check for mistakes.
@NobleCoder69
Copy link
Author

Hi @alyssadai,

This PR is intended to resolve issue #518 by migrating the type annotations to Python 3.9+ syntax across the repository. Please let me know if any changes are required.

@neurobagel-bot neurobagel-bot bot moved this to Community in Neurobagel Mar 5, 2026
@codecov
Copy link

codecov bot commented Mar 13, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 97.16%. Comparing base (4a712d1) to head (57522f8).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #539      +/-   ##
==========================================
- Coverage   97.16%   97.16%   -0.01%     
==========================================
  Files          34       34              
  Lines        1304     1303       -1     
==========================================
- Hits         1267     1266       -1     
  Misses         37       37              

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

_community [BOT ONLY] PR label for community contributions. Used for tracking

Projects

Status: Community

Development

Successfully merging this pull request may close these issues.

2 participants