Skip to content

Don't show dataclasses.InitVar as a class member #790

Open

Description

@elliot-100

Problem Description

Given these definitions which are intended to do very similar things:

from dataclasses import dataclass, field, InitVar


class Dog:
    name: str

    def __init__(self, name: str, id: int):
        self.name = name
        self.vet_code: str = f"{self.name}-{id}"

@dataclass
class Cat:
    name: str
    id: InitVar[int]
    vet_code: str = field(init=False)

    def __post_init__(self, id):
        self.vet_code = f"{self.name}-{id}"

pdoc will produce output like:

class Dog:
    Dog(name: str, id: int)
    name: str
    vet_code: str

@dataclass
class Cat:
    Cat(name: str, id: dataclasses.InitVar[int])
    name: str
    id: dataclasses.InitVar[int]
    vet_code: str

i.e. Cat.id is included as a class member, even though it is type-annotated as an init-only variable.

Proposal

Suppress dataclasses.InitVar class members from output.

Alternatives

We can prefix the InitVar name with _, which will hide it in pdoc output by default...

Additional context

...but it would be nice to not have to do that.

Activity

  1. mhils commented on Apr 9, 2025

    @mhils
    Member

    Sounds fair to me, contributions welcome!

  2. cfreal commented on May 26, 2026

    @cfreal

    Hi @mhils,

    There seems to be two ways of handling this:

    1. Either we use a regex to remove the pattern in _PrettySignature._params, similarly to _remove_collections_abc()
    def _remove_dataclasses_InitVar(x: str) -> str:
        """Remove 'dataclasses.InitVar' from type signatures."""
        x = re.sub(r"\bdataclasses\.InitVar\[(.+?)\]", r"\1", x)
        x = re.sub(r"\bInitVar\[(.+?)\]", r"\1", x)
        return x
    1. Or we edit it at the "logical" level in Function.signature()
            for p in sig.parameters.values():
                p._annotation = safe_eval_type(  # type: ignore
                    p.annotation, globalns, localns, mod, self.fullname
                )
                # unwrap InitVar[X] into X

    I'm willing to implement either one, but I don't know the project enough to pick the best one. Can you tell me which way to go?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions