18

What's the equivalent of this in IronPython? Is it just a try-finally block?

using (var something = new ClassThatImplementsIDisposable())
{
  // stuff happens here
}
Michael
  • 8,362
  • 6
  • 61
  • 88
Josh Kodroff
  • 27,301
  • 27
  • 95
  • 148

5 Answers5

27

IronPython supports using IDisposable with with statement, so you can write something like this:

with ClassThatImplementsIDisposable() as something:
    pass
Bojan Resnik
  • 7,320
  • 28
  • 29
6

IronPython (as of the 2.6 release candidates) supports the with statement, which wraps an IDisposable object in a manner similar to using.

dthor
  • 1,749
  • 1
  • 18
  • 45
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Just curious - why the downvotes? As far as I know, this is true- python, as a language, doesn't include this in the language. – Reed Copsey Nov 18 '09 at 16:39
  • Actually, with is different. It does not handle IDisposable out of the box with .NET - you would need to wrap this into your own type, and specify an __exit__ routine to do the disposal. It is not the same as using in C#. – Reed Copsey Nov 18 '09 at 16:57
  • 1
    Downvoted because this is the same as using, and does handle IDisposable. – Dino Viehland Nov 18 '09 at 19:29
  • @Dino: That is not true in the current, stable release. True in 2.6 RCs, though. Updated my answer for that. – Reed Copsey Nov 18 '09 at 23:25
6

With statement. For example:

with open("/temp/abc") as f:
    lines = f.readlines()
Javier
  • 4,552
  • 7
  • 36
  • 46
  • This does not support IDisposable out of the box. It works with python types with an __exit__ routine specified. – Reed Copsey Nov 18 '09 at 16:58
2

There is the with statement: http://www.ironpythoninaction.com/magic-methods.html#context-managers-and-the-with-statement

with open(filename) as handle:
    data = handle.read()
    ...
Bastien Léonard
  • 60,478
  • 20
  • 78
  • 95
  • No. The "with" statement only works with lockable objects, to which category file objects just happens to belong. It does *not* work with arbitrary types, say, integers. – Teddy Nov 18 '09 at 16:52
0

the using block is in fact the following under the hood:

try {
  (do something unmanaged here)
}
finally {
  unmanagedObject.Dispose();
}

Hope this helps you understand the logic behind the using statement.

Webleeuw
  • 7,222
  • 33
  • 34