[Python] How can I provide type hints while destructuring my class

Discussão em 'Python' iniciado por Stack, Maio 5, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to create a class that looks something like ConfigAndPath:

    import pathlib
    from typing import TypeVar, Generic
    from dataclasses import dataclass, astuple

    class ConfigBase:
    pass
    T = TypeVar("T", bound=ConfigBase)

    @dataclass
    class ConfigAndPath(Generic[T]):
    path: pathlib.Path
    config: T


    I often have a list of these ConfigAndPath, and so would want to destructure it in list comprehensions like this:

    l: list[ConfigAndPath[MyConfig]] = ...
    filenames = [_path.name for _path, _my_config in l]


    So I added an __iter__ method to my class:

    # In ConfigAndPath
    def __iter__(self):
    return iter(astuple(self))


    However, I'm not sure how to make it so that my typechecker (Pyright) realizes that _path is a pathlib.Path and _my_config is a MyConfig. This works with NamedTuple, however I can't appear to use generics with NamedTuple due to it not allowing multiple inheritance. Is this possible to specify what I want?

    I tried writing an as_tuple method:

    # In ConfigAndPath
    def as_tuple(self) -> Tuple[pathlib.Path, T]:
    return self.path, self.config


    Which then allows me to write

    filenames2 = [_path.name for _path, _my_config in [i.as_tuple() for i in l]]


    Which gives me a type hint but is quite verbose and walks the list twice.

    Continue reading...

Compartilhe esta Página