how to count lines in a file ?

Bjorn Pettersen BPettersen at NAREX.com
Fri Jul 26 13:08:18 EDT 2002


> From: Alex Martelli [mailto:aleax at aleax.it] 
[snip]
> It's not as bad as it looks.  I wish there was some slightly 
> handier way to express try/finally, yes -- say the equivalent 
> of atexit but applied to exiting the current function, to 
> avoid the deep nesting and open/close separation that 
> try/finally may require:
> 
> a = open('a')
> try:
>     b = open('b')
>     try:
>         c = open('c')
>         try:
>             process(a,b,c)
>         finally:
>             c.close()
>     finally: 
>         b.close()
> finally:
>     a.close()

If you make it a little more special purpose, I could propose syntax
like e.g.:

  let a = open('a'):
      process(a)

being equivalent to:

  a = None
  try:
     a = open('a')
     process(a)
  finally:
     del a

assuming a's __del__ was guaranteed to close the file, although it would
probably be safer to create a new statement like:

  close a

which would call a.__close__ which would "do the right thing". Something
like 'let' also works well with Python indentation.

For a different approach you can look at Ruby which only has M/S GC, but
also can guarantee file object lifetimes.

-- bjorn




More information about the Python-list mailing list