Search code examples
pythonpython-3.x

How does defining what a function will return work


If i have a function Like:

def datamodelAuth(data : dict) -> str: 
    dataModelkeys = list(dataModel.keys())
    dataKeys = list(data.keys())
    count = 0
    for keys in dataModelkeys:
        if keys not in dataKeys:
        return f"{keys} not found"
    else:
        count += 1
   if count == len(dataModelkeys):
       ret = createUser(data)    # this function returns a string
       return ret

Will this return the string from the createUser() function?

I have tried testing with string but i still had issues.


Solution

  • def datamodelAuth(data : dict) -> str: means the function datamodelAuth returns a string. This is called a type hint. Type hints don’t enforce the type at runtime; they’re primarily for code readability and static analysis tools like mypy. So this will not transform your output is mainly a hint for the reader.

    MOREOVER: the function you have given could be improve easily using sets.

    def datamodelAuth(data : dict) -> str: 
        missing_keys = set(dataModel) - set(data)
        if missing_keys:
            raise KeyError(f"Missing key(s): {', '.join(missing_keys)}")
        return createUser(data)
    

    This function if we consider that createUser always returns a string then should always return a string, but if createUser returs something that is not a string will return whatever that function returns since specifying def datamodelAuth(data : dict) -> str: is only a hint a does nothing at runtime.

    Extra: you should consider using sanke_case for naming functios in python to follow general standards.