Skip to content

Add type hints for empty collections (EmptyList, EmptyDict, EmptySet, EmptyTuple) #141838

@a-jean-andreasian

Description

@a-jean-andreasian

Feature or enhancement

Proposal:

Proposal: Add Empty Collection Type Hints for Enhanced Type Precision

Problem: The current type system doesn't distinguish between empty and non-empty containers, which can lead to ambiguity in function contracts and require additional code inspection.

Current limitation:

def get_user_data() -> List[Dict[str, str]]:
    # The return type doesn't indicate whether empty results are possible
    if not users_exist:
        return []  # Empty list
    return [{"name": "john"}]

Proposal: We suggest adding special forms for empty collections:

  • EmptyList for []
  • EmptyDict for {}
  • EmptySet for set()
  • EmptyTuple for ()

Use cases:

from typing import EmptyList, EmptyDict

# Clearer function contracts
def initialize() -> EmptyDict:
    return {}

# Optional results with precise types
def find_users(query: str) -> List[User] | EmptyList:
    if not query:
        return []
    return [user1, user2]

# Configuration with empty defaults
def load_settings() -> Dict[str, Setting] | EmptyDict:
    if not config_exists():
        return {}
    return parse_config()

Benefits:

  • More precise type annotations
  • Better communication of function semantics
  • Enhanced static analysis capabilities
  • Self-documenting code without runtime cost

Implementation consideration: These could be implemented as _SpecialForm instances, similar to existing special types, ensuring no runtime impact.

This would provide developers with additional expressiveness when designing APIs and function interfaces, particularly for cases where empty collections have specific semantic meaning.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions