librelist archives

« back to archive

with ... as?

with ... as?

From:
Timur Tabi
Date:
2013-11-24 @ 20:05
I'm not very good at Python, and I'm having a hard time understanding 
the with...as construction.  I did look it up, but I still don't get it.

All of the examples on the Wand web site use with...as:

with Image(filename='pikachu.png') as img:
     print('width =', img.width)
     print('height =', img.height)

However, this works:

img = Image(filename='pikachu.png')
print('width =', img.width)
print('height =', img.height)

Not only is it simpler, but it avoids one level of indentation.  Also, 
if I understand the with..as documentation, the scope of 'img' is 
limited to the 'with' statement, so I can't do this:

with Image(filename='pikachu.png') as img:
     print('width =', img.width)
print('height =', img.height)

So what am I missing?

Re: [wand] with ... as?

From:
Hong Minhee
Date:
2013-11-25 @ 03:17
Hi Timur,

Python with statement is a language construct called RAII in other
programming languages e.g. C#’s using, Java 7’s try-with-resources.  In
Wand, with statement automatically called Image.close() method in the end
(even if there’s an error).  It works in the similar way to:

  img = Image(filename='pikachu.png')
  try:
      print('width =', img.width)
      print('height =', img.height)
  finally:
      img.close()

You can find more information about RAII from here:

  http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization


Thanks,
Minhee


On Mon, Nov 25, 2013 at 5:05 AM, Timur Tabi <timur@tabi.org> wrote:

> I'm not very good at Python, and I'm having a hard time understanding
> the with...as construction.  I did look it up, but I still don't get it.
>
> All of the examples on the Wand web site use with...as:
>
> with Image(filename='pikachu.png') as img:
>      print('width =', img.width)
>      print('height =', img.height)
>
> However, this works:
>
> img = Image(filename='pikachu.png')
> print('width =', img.width)
> print('height =', img.height)
>
> Not only is it simpler, but it avoids one level of indentation.  Also,
> if I understand the with..as documentation, the scope of 'img' is
> limited to the 'with' statement, so I can't do this:
>
> with Image(filename='pikachu.png') as img:
>      print('width =', img.width)
> print('height =', img.height)
>
> So what am I missing?
>
>