On Saturday, 3 March 2018 17:16:14 UTC, Ned Batchelder  wrote:
> On 3/2/18 10:36 AM, Paul Moore wrote:
> > Or (real Python):
> >
> >      def fn():
> >          for i in range(10000):
> >              with open(f"file{i}.txt", "w") as f:
> >                  f.write("Some text")
> >
> > How would you write this in your RAII style - without leaving 10,000
> > file descriptors open until the end of the function?
> 
> IIUC, if the OP's proposal were accepted, the __del__ method would be 
> called as soon as the *value*'s reference count went to zero. That means 
> this wouldn't leave 10,000 files open, since each open() would assign a 
> new file object to f, which would make the previous file object's ref 
> count be zero, and it would be closed.

You have understood correctly. Here is the equivalent RAII version:-

def fn():
    for i in range(10000):
         f = RAIIFile(f"file{i}.txt", "w")
         f.write("Some text")

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to