diff --git a/functions/tips/main.py b/functions/tips/main.py index 3e61cb1c26c..8196e0db371 100644 --- a/functions/tips/main.py +++ b/functions/tips/main.py @@ -39,6 +39,8 @@ # [END functions_tips_connection_pooling] +from functools import reduce + # Placeholder def file_wide_computation(): @@ -50,6 +52,42 @@ def function_specific_computation(): return 1 +def light_computation(): + numbers = list(range(1, 10)) + return reduce(lambda x, t: t + x, numbers) + + +def heavy_computation(): + # Multiplication is more computationally expensive than addition + numbers = list(range(1, 10)) + return reduce(lambda x, t: t * x, numbers) + + +# [START functions_tips_global_scope] +# [START run_tips_global_scope] +# Global (instance-wide) scope +# This computation runs at instance cold-start +instance_var = heavy_computation() + + +def scope_demo(request): + """ + HTTP Cloud Function that declares a variable. + Args: + request (flask.Request): The request object. + + Returns: + The response text, or any set of values that can be turned into a + Response object using `make_response` + . + """ + function_var = light_computation() + return 'Per instance: {}, per function: {}'.format( + instance_var, function_var) +# [END run_tips_global_scope] +# [END functions_tips_global_scope] + + # [START functions_tips_lazy_globals] # Always initialized (at cold-start) non_lazy_global = file_wide_computation() diff --git a/functions/tips/main_test.py b/functions/tips/main_test.py index aacfea6a1ea..e4fb31ac753 100644 --- a/functions/tips/main_test.py +++ b/functions/tips/main_test.py @@ -35,6 +35,12 @@ def test_lazy_globals(app): main.lazy_globals(flask.request) +def test_scope_demo(app): + with app.test_request_context(): + res = main.scope_demo(flask.request) + assert res == 'Per instance: 362880, per function: 45' + + @responses.activate def test_connection_pooling_200(app): responses.add(responses.GET, 'http://example.com',