【以下的问题经过翻译处理】 我在 python 3.6 lambda 中实现了单例设计模式,发现之前的 lambda 执行影响了当前的执行。具体来说,单例类的实例在多个 lambda 环境中是相同的。我很好奇这些对于如何隔离 python lambda 意味着什么?
我遵循了这个流行的堆栈溢出帖子的“方法 3”中描述的单例实现:https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
这是一个例子。
lambda代码:
import json
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances\[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances\[cls]
class Foo(metaclass=Singleton):
def init(self):
self.bar = []
print(f"'bar' attribute is {self.bar}")
def lambda_handler(event, context):
foo = Foo()
print(f"after instantiating 'foo', bar attribute is {foo.bar}")
foo.bar.append(0)
print(f"after append, bar attribute is {foo.bar}")
连续多次手动触发 lamba 后产生的 Cloudwatch 日志。我相信新实例没有在第一个之后的 lambda 中实例化,因为“bar”属性包含来自前一个 lambda 的数据。
01:57:14 START RequestId: 69e78a31-4a5e-4e84-abd9-44108f390838 Version: $LATEST
01:57:14 'bar' attribute is []
01:57:14 after instantiating 'foo', bar attribute is []
01:57:14 after append, bar attribute is [0]
01:57:14 END RequestId: 69e78a31-4a5e-4e84-abd9-44108f390838
01:57:14 REPORT RequestId: 69e78a31-4a5e-4e84-abd9-44108f390838 Duration: 1.49 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 56 MB Init Duration: 114.96 ms
01:57:21 START RequestId: adacf02b-39b8-468e-a7a5-f4c09bda5758 Version: $LATEST
01:57:21 after instantiating 'foo', bar attribute is [0]
01:57:21 after append, bar attribute is [0, 0]
01:57:21 END RequestId: adacf02b-39b8-468e-a7a5-f4c09bda5758
01:57:21 REPORT RequestId: adacf02b-39b8-468e-a7a5-f4c09bda5758 Duration: 1.38 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 56 MB
01:57:22 START RequestId: d66468cd-f09d-4c28-9343-0eeb52b316e9 Version: $LATEST
01:57:22 after instantiating 'foo', bar attribute is [0, 0]
01:57:22 after append, bar attribute is [0, 0, 0]
01:57:22 END RequestId: d66468cd-f09d-4c28-9343-0eeb52b316e9
01:57:22 REPORT RequestId: d66468cd-f09d-4c28-9343-0eeb52b316e9 Duration: 1.62 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 56 MB
01:57:23 START RequestId: 89813b23-9cb1-4284-ab11-472b84151666 Version: $LATEST
01:57:23 after instantiating 'foo', bar attribute is [0, 0, 0]
01:57:23 after append, bar attribute is [0, 0, 0, 0]
01:57:23 END RequestId: 89813b23-9cb1-4284-ab11-472b84151666
01:57:23 REPORT RequestId: 89813b23-9cb1-4284-ab11-472b84151666 Duration: 1.39 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 56 MB