Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading