Created
May 1, 2025 17:01
-
-
Save mypy-play/7bf94309042921d3d681363413c8f3e1 to your computer and use it in GitHub Desktop.
Shared via mypy Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Optional, Union, cast, Literal, NewType, TypeGuard | |
from collections import defaultdict | |
from dataclasses import dataclass | |
@dataclass | |
class Application: | |
id: int | |
parent_id: Optional[int] = None | |
ParentApplication = NewType('ParentApplication', Application) | |
ChildApplication = NewType('ChildApplication', Application) | |
def abort_if_application_is_child(application: 'Application') -> ParentApplication: | |
if application.parent_id is not None: | |
raise Exception('Application is Child') | |
return cast(ParentApplication, application) | |
def function_only_valid_to_call_for_parents(parent_application: ParentApplication): | |
... | |
def function_only_valid_to_call_for_children(child_application: ChildApplication): | |
... | |
def existing_function_that_doesnt_care_parent_or_child(application: Application): | |
... | |
application = Application(id=123) | |
any_other_application = Application(id=456) | |
application = abort_if_application_is_child(application) | |
function_only_valid_to_call_for_parents(application) # no problem | |
function_only_valid_to_call_for_children(application) # problem | |
existing_function_that_doesnt_care_parent_or_child(application) # no problem | |
function_only_valid_to_call_for_children(any_other_application) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment