Skip to content
Advertisement

type hints in a Python Google Cloud Function?

In a Python Google Cloud Function with a lot of sub-functions in the “main.py”, I added type hints (= return value annotation as part of function annotation) in pep8 style like this:

from typing import Union

def f1() -> int:
    return 5555

def f2() -> Union[int, int]:
    return 9999, 1111

def my_main_function(request) -> str:
    a = f1()
    x, y = f2()
    return 'Done.'

Union is taken from here, it is needed if there is more than one type hint.

The function cannot get deployed, there is no log about what is wrong, just an orange error log entry that has the same text as the start item above it.

MY_TIME_ZONE_LOCATION:MY_CLOUD_FUNCTION_NAME MY_MAIL.com {@type:
type.googleapis.com/google.cloud.audit.AuditLog, authenticationInfo:
{…}, methodName:
google.cloud.functions.v1.CloudFunctionsService.UpdateFunction,
resourceName:
projects/MY_PROJECT_NAME/locations/MY_TIME_ZONE_LOCATION/functions/MY_CLOUD_FUNCTION_NAME,
serviceName: cloudfunctions.googleapis.com, status… {@type:
type.googleapis.com/google.cloud.audit.AuditLog, authenticationInfo:
{…}, methodName:
google.cloud.functions.v1.CloudFunctionsService.UpdateFunction,
resourceName:
projects/MY_PROJECT_NAME/locations/MY_TIME_ZONE_LOCATION/functions/MY_CLOUD_FUNCTION_NAME,
serviceName: cloudfunctions.googleapis.com, status… ```

And when I replace the -> with : # -> so that all type strings are commented out, it works, therefore, the type hints seem to disturb the Google Cloud Function.

Are type hints supported at all? How can I get type hints to work in a Google Cloud Function?

Advertisement

Answer

From the comments follows that the error was in another code snippet that went as follows:

def f3() -> int, int:
     return 4444, 2222

That code was corrected to include Tuple (Union also worked but is not the default for many types in one type hint):

def f3() -> Tuple[int, int]:
     return 4444, 2222
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement