3 ms·
I commented something relating to this in another post, but since in Python/C# the resource and the container of the resource don't actually have tied lifetimes
by sirwhinesalot 4y ago
I commented something relating to this in another post, but since in Python/C# the resource and the container of the resource don't actually have tied lifetimes, you can do a different pattern where MyFoo() is a perfectly normal class, with a method within it that actually creates the context manager that loads the resource temporarily.
If you do this, you can move and store MyFoo's around, but in order to access the resource without getting an exception to the face you need to use with, e.g.
myfoo = MyFoo()
# the actual resource is only acquired for the duration of the with block
with myfoo.acquire():
myfoo.read_stuff()
myfoos = [myfoo]
# later
with myfoos[0].acquire():
myfoo.read_stuff()
Lifetimes are loose in GCed languages, so you shouldn't really think of some object's lifetime and the resources lifetime to be tied in any way, nor should APIs be designed with that assumption, even if the object represents the resource (confusing I know, specially since the languages themselves get this wrong).