title: Implementing use of 'with object() as f' in custom class in python
body: <p>I have to open a file-like object in python (it's a serial connection through /dev/) and then close it. This is done several times in several methods of my class. How I WAS doing it was opening the file in the constructor, and then closing it in the destructor. I'm getting weird errors though and I think it has to do with the garbage collector and such, I'm still not used to not knowing exactly when my objects are being deleted =\</p>
  
  <p>The reason I was doing this is because I have to use <code>tcsetattr</code> with a bunch of parameters each time I open it and it gets annoying doing all that all over the place. So I want to implement an inner class to handle all that so I can use it doing<br>
  <code>with Meter('/dev/ttyS2') as m:</code></p>
  
  <p>I was looking online and I couldn't find a really good answer on how the <code>with</code> syntax is implemented. I saw that it uses the <code>__enter__(self)</code> and <code>__exit(self)__</code> methods. But is all I have to do implement those methods and I can use the with syntax? Or is there more to it?</p>
  
  <p>Is there either an example on how to do this or some documentation on how it's implemented on file objects already that I can look at?</p>