1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] How do I add default parameters to functions when using type hinting?

Discussão em 'Python' iniciado por Stack, Setembro 28, 2024 às 00:22.

  1. Stack

    Stack Membro Participativo

    If I have a function like this:

    def foo(name, opts={}):
    pass


    And I want to add type hints to the parameters, how do I do it? The way I assumed gives me a syntax error:

    def foo(name: str, opts={}: dict) -> str:
    pass


    The following doesn't throw a syntax error but it doesn't seem like the intuitive way to handle this case:

    def foo(name: str, opts: dict={}) -> str:
    pass


    I can't find anything in the typing documentation or on a Google search.

    Edit: I didn't know how default arguments worked in Python, but for the sake of this question, I will keep the examples above. In general it's much better to do the following:

    def foo(name: str, opts: dict=None) -> str:
    if not opts:
    opts={}
    pass

    Continue reading...

Compartilhe esta Página