title: Managing file open and close responsibilities with different objects
body: <p>In a main method, <code>my_object</code> needs access to several members of <code>passed_object</code>, including a file that is opened (<code>passed_file = passed_object.create_file()</code>.  An example of this: </p>
  
  <pre><code>import os
  
  def main():
  
      print('Start of program...')
      passed_object = PassedObject()
      my_object = MyObject(passed_object)
  
      my_object.use_passed_object()
      print('End of program.')
  
  class MyObject(object):
  
      def __init__(self, passed_object):
          self.passed_object = passed_object
  
      def use_passed_object(self):
          f = self.passed_object.create_file()
          print('attribute:')
          print(self.passed_object.attr1)
          print('contents of first file:')
          print(list(f))
  
  class PassedObject(object):
  
      def __init__(self):
  
          self.attr1 = 'some attribute string'
  
      def create_file(self):
  
          path = '/tmp'
          files = [file for file in os.listdir(path) 
           if os.path.isfile(os.path.join(path, file))]
  
          f = open(files[0], 'r')
          return f
  
  main()
  </code></pre>
  
  <p>The problem: <code>passed_object</code> creates a file object(s) that is needed by <code>my_object</code>, and by others not shown in this simple example.  How can I close these file objects when <code>my_object</code> is done with it without breaking encapsulation?</p>
  
  <p>Potential solutions I see:</p>
  
  <ul>
  <li><p>don't pass <code>passed_object</code>: pass <code>passed_object.create_file()</code> and <code>passed_object.attr1</code>, then use a context manager in main <code>with open...</code>.  However, I now have to pass in each attribute/created object to <code>my_class</code>.</p></li>
  <li><p>write method <code>my_object.close_file()</code>, and call it from main.  This seems to break encapsulation also, as main shouldn't need to know about this.</p></li>
  <li><p>write a <code>my_object.__del__()</code> method that closes the file. </p></li>
  <li><p>don't worry about closing it; your program terminates in a few lines.</p></li>
  </ul>