Skip to content

Instantly share code, notes, and snippets.

@mypy-play
Created May 1, 2025 16:48
Show Gist options
  • Save mypy-play/9d14f793f03b3a92047f7826accad490 to your computer and use it in GitHub Desktop.
Save mypy-play/9d14f793f03b3a92047f7826accad490 to your computer and use it in GitHub Desktop.
Shared via mypy Playground
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 function_that_doesnt_care(application: Application):
...
application = Application(id=123)
application = abort_if_application_is_child(application)
foo(application) # no problem
bar(application) # problem
baz(application) # no problem
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment