Skip to content

sample use case: return type of @contextmanager decorated functions #15

@ippeiukai

Description

@ippeiukai

I want to contribute a real life use case that we encountered which may justify the needs of Intersection types.

Can anyone suggest an alternative without using Intersection?

from typing import *
from contextlib import AbstractContextManager, ContextDecorator, contextmanager

    
@contextmanager
def _hoge():
    ...
    try:
        yield
    finally:
        ...


def foo() -> ContextManager[Never] & ContextDecorator:  # How should we annotate this without Intersection?
    ...
    return _hoge()


# ====
# foo is used both as ContextManager and ContextDecorator

with foo():
    ...

@foo()
def bar():
    ...

NOTE: the spec of @contextmanager is here:
https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager

Essentially, what the decorated function returns is a ContextManager that uses ContextDecorator mixin.

Metadata

Metadata

Assignees

No one assigned

    Labels

    sample use casehere to make sure none of these get lost

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions