1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] How to use MaxLen of typing.Annotation of python 3.9?

Discussão em 'Python' iniciado por Stack, Setembro 17, 2025.

  1. Stack

    Stack Membro Participativo

    I'm aware there's this new typing format Annotated where you can specify some metadata to the entry variables of a function. From the docs, you could specify the maximum length of an incoming list such as:

    • Annotated can be used with nested and generic aliases:
    ​

    T = TypeVar('T')
    Vec = Annotated[list[tuple[T, T]], MaxLen(10)]
    V = Vec[int]

    V == Annotated[list[tuple[int, int]], MaxLen(10)]


    But I cannot fully comprehend what MaxLen is. Are you supposed to import a class from somewhere else? I've tried importing typing.MaxLen but it doesn't seem to exist (I'm using Python 3.9.6, which I think it should exist here...?).

    Example code of what I imagined should have worked:

    from typing import List, Annotated, MaxLen

    def function(foo: Annotated[List[int], MaxLen(10)]):
    # ...
    return True


    Where can one find MaxLen?

    EDIT:

    It seems like MaxLen is some sort of class you have to create. The problem is that I cannot see how you should do it. Are there public examples? How can someone implement this function?

    Continue reading...

Compartilhe esta Página