如何使用python上下文管理器;借用;物体

如何使用python上下文管理器;借用;物体,python,contextmanager,Python,Contextmanager,我想创建一个Python上下文管理器,作为一种受控的“库”,借出对象,然后在with语句的作用域退出时将它们取回 在psuedo代码中,我的想法如下: class Library: def __init__(self): self.lib = [1,2,3,4] self.lock = Condition(Lock()) def __enter__(self): with self.lock: # Some

我想创建一个Python上下文管理器,作为一种受控的“库”,借出对象,然后在
with
语句的作用域退出时将它们取回

在psuedo代码中,我的想法如下:

class Library:
    def __init__(self):
        self.lib = [1,2,3,4]
        self.lock = Condition(Lock())

    def __enter__(self):
        with self.lock:
            # Somehow keep track of this object-thread association
            if len(self.lib) > 0:
                return self.lib.pop() 
            else:
                self.lock.wait()
                return self.lib.pop()

    def __exit__(self):
        with self.lock:
            # Push the object that the calling thread obtained with
            # __enter__() back into the array
            self.lock.notify()

问题是什么?@ArminRigo如何实现示例代码中提到的注释?