Search code examples
pythonreturn-type

Python how to restrict output type as dictionary?


I find an example.

from typing import List
def twoSum(nums: List[int], target: int) -> List[int]:
    pass

So I'm trying to restrict the input as an integer, and the output as a dictionary. survey = {"sid": survey_id, "title": 22} this line work. However, survey = [survey_id, 22], the return type becomes list also works. How can I fix it?

def question(survey_id: int) -> dict:
    #survey = {"sid": survey_id, "title": 22}
    survey = [survey_id, 22]
    return survey

question("3456")    
['3456', 22]

More specifically, I'd like to restrict the return type as a dictionary with integer and string only. How can I make it?


Solution

  • The Python interpreter can't enforce that a function returns a specific type. If you want to prevent the program from executing when the types are not correctly defined, Python is not a good choice of language.

    On the other hand, you can use a static typechecker like mypy to ensure that type hints are correctly observed. These type hints aren't enforced at runtime, but they can ensure that modifications to functions do not introduce typing-related bugs.