[Tutor] How to type annotate complex dictionary containing lambdas?

boB Stepp robertvstepp at gmail.com
Sun Nov 17 17:59:14 EST 2019


Well, I am stumped on trying to navigate type annotation for this
overly complex dictionary.

On Sun, Nov 17, 2019 at 4:09 PM Mats Wichmann <mats at wichmann.us> wrote:
>
> On 11/17/19 12:46 PM, boB Stepp wrote:
>
> > Apparently because of the lambda outside of the list, I apparently
> > must annotate them as "Callable".
>
> yup, you're right, I spaced out that bit when trying to definitively
> tell you the value was either a str or a List.  Sigh...

I thought I would make the mypy and Mats suggested changes and have this:

      goal_year_params: Dict[str, Union[str, Callable[[int], date],
List[Any]]] = {
          "greeting_msg": "Please enter the date by which you wish to attain"
          " your goal.\n",
          "input_prompt": "Enter year of your goal as an integer:  ",
          "date_value_err_ck": lambda goal_year: date(goal_year, 1, 1),
          "err_msg": "That is not a valid year.  Please try again.",
          "conditions": [
              (
                  lambda goal_year: goal_year < date.today().year,
                  lambda goal_year: print(
                      "Have you invented a time machine?  If not,
please enter a"
                      " year that makes more sense!"
                  ),
              ),
              (
                  lambda goal_year: goal_year >= date.today().year + 100,
                  lambda goal_year: print(
                      "Have you discovered the secret to eternal life?
 And how"
                      " long is this book anyway?  Please enter a year that"
                      " makes more sense."
                  ),
              ),
          ],
      }
>>    goal_year = get_input(**goal_year_params)

It flags this function call using the dictionary, goal_year_params and
lists the following (seemingly) contradictory errors for this flagged
statement:

    1 pages_per_day.py|113 col 29 error| Argument 1 to "get_input" has
incompatible type "**Dict[str, Union[str, Callable[[int], date],
List[Any]]]"; expected "Callable[[int], date]"
    2 pages_per_day.py|113 col 29 error| Argument 1 to "get_input" has
incompatible type "**Dict[str, Union[str, Callable[[int], date],
List[Any]]]"; expected "List[Any]"
    3 pages_per_day.py|113 col 29 error| Argument 1 to "get_input" has
incompatible type "**Dict[str, Union[str, Callable[[int], date],
List[Any]]]"; expected "str"

How can mypy be expecting 3 separate and different types?  Does it not
understand the syntax **goal_year_params ?  Or, the probable answer,
what is it I don't understand about mypy in this instance?


-- 
boB


More information about the Tutor mailing list