Skip to content

PEP 695 syntax breaks parsing of forward type reference #762

Open
@ncanceill

Description

@ncanceill

Problem Description

Python 3.12 introduced PEP 695 Type Parameter Syntax. This seems to break type parsing for a forward type reference to a generic class in a method of another generic class:

class Foo[T]:
    def foo(self) -> "Bar[T]":  # this breaks!
        ...

class Bar[T]:
    def bar(self, _: T) -> None:
        ...

That is a valid Python 3.12 module, but running pdoc on it will result in:
Error parsing type annotation Bar[T] for package.module.Foo.foo. Import of T failed: name 'T' is not defined

The generated HTML therefore does not have a link:

<span class="return-annotation">) -&gt; <span class="s1">'Bar[T]'</span>:</span>

Steps to reproduce the behavior:

Run pdoc on a package containing the example module above.

Note that using the old syntax does not break parsing, probably because it requires a TypeVar to be defined:

from typing import Generic, TypeVar

T = TypeVar("T")

class Foo(Generic[T]):
    def foo(self) -> "Bar[T]":  # this is fine
        ...

class Bar(Generic[T]):
    def bar(self, _: T) -> None:
        ...

Note also that the problem only occurs with a forward reference, insofar as the following example does not break parsing either:

class Foo[T]:
    def foo(self, _: T) -> None:
        ...

class Bar[T]:
    def bar(self) -> Foo[T]:  # this is fine
        ...

System Information

pdoc: 15.0.0
Python: 3.12.7
Platform: Linux-6.1.0-21-amd64-x86_64-with-glibc2.36

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions