title: Writing a Python class that can only be used as a context manager
body: <p>Is there a way in Python to write a class that will error unless it's used with a with statement?</p>
  
  <pre><code># Okay:
  with Foo() as f1:
      f1.func1()
      f1.func2()
  
  # Not okay:
  f2 = Foo()
  f2.func1()
  </code></pre>
  
  <p>I can do it manually: have <code>__enter__</code> set a flag and have every other method check for that flag. But is there a nicer way to do it?</p>
  
  <p>Here's code for the not-so-since way:</p>
  
  <pre><code>class Foo(object):
      def __init__(self):
          self._entered = False
  
      def __enter__(self):
          self._entered = True
          return self
  
      def _verify_entered(self):
          if not self._entered:
              raise Exception("Didn't get call to __enter__")
  
      def __exit__(self, typ, val, traceback):
          self._verify_entered()
          print("In __exit__")
  
      def func1(self):
          self._verify_entered()
          # do stuff ...
  
      def func2(self):
          self._verify_entered()
          # do other stuff
  </code></pre>