Skip to content

Resolving multiple imports guarded by typing.TYPE_CHECKING #375

@lchojnacki

Description

@lchojnacki

Hello!

At the beginning: I saw #22, but this case looks like a separate issue.

Description

Version 1.15.0 introduced a change in the way imports guarded by if typing.TYPE_CHECKING are handled. The _resolve_type_guarded_imports function searches for TYPE_CHECKING occurrences using a regular expression, and then runs the code inside that block with exec.

This solution is pretty smart and it works, until we have multiple levels of TYPE_CHECKING guards.

Example

bokeh/model/model.py: https://github.com/bokeh/bokeh/blob/branch-3.3/src/bokeh/model/model.py#L42

if TYPE_CHECKING:
    from ..core.has_props import Setter

bokeh/core/has_props.py: https://github.com/bokeh/bokeh/blob/branch-3.3/src/bokeh/core/has_props.py#L98

if TYPE_CHECKING:
    from ..client.session import ClientSession
    from ..server.session import ServerSession

if TYPE_CHECKING:
    Setter = Union[ClientSession, ServerSession]

The resolver finds TYPE_CHECKING guard in model.py and tries to execute the import, but it's unable to find the Setter in has_props.py (the TYPE_CHECKING flag is set to False, and the file has_props.py is just being executed by python, not parsed by _resolve_type_guarded_imports function).

Proposition

I'm wondering if it would be possible to resolve this type of imports recursively, using _resolve_type_guarded_imports? Or do you have any other ideas? I guess I have to stay with version <1.15.0 until this gets fixed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions