-
-
Notifications
You must be signed in to change notification settings - Fork 33.5k
Closed as not planned
Closed as not planned
Copy link
Labels
type-featureA feature request or enhancementA feature request or enhancement
Description
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:
EmptyListfor[]EmptyDictfor{}EmptySetforset()EmptyTuplefor()
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
Labels
type-featureA feature request or enhancementA feature request or enhancement