Effective Type Hinting Practices in Python
Discover how to implement type hints in your Python code to improve clarity and reduce bugs, making it easier for others to understand and maintain your code.
0 likes
178 views
Rule Content
---
name: Effective Type Hinting Practices in Python
description: Discover how to implement type hints in your Python code to improve clarity and reduce bugs, making it easier for others to understand and maintain your code.
category: Python Cursor Rules
version: "1.0"
globs:
- "**/*.py"
triggers:
- file_open
- file_save
rules:
- id: use_type_hints
description: Ensure all function and method definitions include type hints for parameters and return values.
pattern: |
def $FUNC_NAME($PARAMS):
replacement: |
def $FUNC_NAME($PARAMS: $PARAM_TYPE) -> $RETURN_TYPE:
message: "Consider adding type hints to function parameters and return values to enhance code clarity and maintainability."
severity: warning
- id: prefer_builtin_generics
description: Use built-in generics for type annotations instead of importing from the typing module.
pattern: |
from typing import List, Dict, Tuple
replacement: |
# Remove unnecessary imports; use built-in generics like list, dict, tuple directly.
message: "Use built-in generics (list, dict, tuple) for type annotations to simplify code and adhere to modern Python practices."
severity: warning
- id: avoid_any_type
description: Avoid using 'Any' as a type hint unless absolutely necessary.
pattern: |
: Any
replacement: |
: $SPECIFIC_TYPE
message: "Replace 'Any' with a more specific type to improve type checking and code readability."
severity: warning
- id: use_optional_for_none
description: Use 'Optional' for parameters or return types that can be 'None'.
pattern: |
: None
replacement: |
: Optional[$TYPE]
message: "Use 'Optional' from the typing module to indicate that a variable can be of a specific type or 'None'."
severity: warning
- id: use_type_aliases
description: Create type aliases for complex or repetitive type annotations to improve readability.
pattern: |
# Complex type annotations repeated multiple times
replacement: |
# Define a type alias at the beginning of your module
$TYPE_ALIAS = $COMPLEX_TYPE
message: "Consider defining a type alias for complex or repetitive type annotations to enhance code readability and maintainability."
severity: suggestion