[Python] When is typing.cast required?

Discussão em 'Python' iniciado por Stack, Abril 7, 2025.

  1. Stack

    Stack Membro Participativo

    Here's the code

    # args: argparse.Namespace
    source: str = args.source

    ...

    # subparsers: argparse._SubParsersAction
    parser = subparsers.add_parser()


    In the first line of code, : str is enough to tell Pylance that source is a string, although args.source is Any.

    However, in the second line, when I add : argparse.ArgumentParser, the type of parser is still Any | argparse.ArgumentParser. I have to manually use cast(argparse.ArgumentParser) to get the desired effect, since add_parser() is typed as returing Any.

    Why is that the case? Both are assignment to me, one from a field, one from the return of a function.

    Continue reading...

Compartilhe esta Página