[Python] Using a programmatically generated type in type hints

Discussão em 'Python' iniciado por Stack, Março 18, 2025.

  1. Stack

    Stack Membro Participativo

    For some external reasons I'm generating a set of dataclasses dynamically with make_dataclass. In other parts of my codebase, I want to use these types in type hints. But both mypy and pyright complain.

    $ pyright dynamic_types.py
    /home/user/testing/dynamic_types.py
    /home/user/testing/dynamic_types.py:23:18 - error: Variable not allowed in type expression (reportInvalidTypeForm)
    1 error, 0 warnings, 0 informations
    $ mypy dynamic_types.py
    dynamic_types.py:23: error: Variable "dynamic_types.mydc" is not valid as a type [valid-type]
    dynamic_types.py:23: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
    Found 1 error in 1 file (checked 1 source file)


    I understand the argument, but in my case the "dynamic" part is a dictionary within the same module. Is there some way I could get this to work?

    MWE:

    from dataclasses import asdict, field, make_dataclass


    class Base:
    def my_method(self):
    pass


    spec = {
    "kind_a": [("foo", int, field(default=None)), ("bar", str, field(default=None))]
    }


    def make_mydc(kind: str) -> type:
    """Create dataclass from list of fields and types."""
    fields = spec[kind]
    return make_dataclass("mydc_t", fields, bases=(Base,))


    mydc = make_mydc("kind_a")


    def myfunc(data: mydc):
    print(asdict(data))


    data = mydc(foo=42, bar="test")
    myfunc(data)


    I can't use Base to type hint because it doesn't have all the attributes.

    Continue reading...

Compartilhe esta Página