0

I need to write code that deals with different hardware setups. A prori I don't know which hardware is connected to my system. So I use a object factory that reads some identifiers from the hardware and returns a specialized object. I would like to combine this approach with contextlib but did find out that the object still exists outside the with block. In my case this is a problem as I need to close the connection to my device.

A minimal working example for my problem:

import contextlib

class Dog:
    def speak(self):
        print('wuff')

class Cat:
    def speak(self):
        print('miau')


@contextlib.contextmanager
def get_animal(n):
    print('buy animal')
    if n==0:
        yield Dog()
    else:
        yield Cat()
    print('lost animal')

if __name__ == "__main__":
    with get_animal(0) as animal:
        animal.speak()
    animal.speak()

This yields

> buy animal
> wuff
> lost animal
> wuff

How can I modify this code such that the final animal.speak() results in a error? I know that I can use del animal to release animal but there must be a more elegant way.

4

0 回答 0