title: What's the best way to extend the functionality of factory-produced classes outside of the module in python?
body: <p>I've been reading lots of previous SO discussions of factory functions, etc. and still don't know what the best (pythonic) approach is to this particular situation. I'll admit up front that i am imposing a somewhat artificial constraint on the problem in that i want my solution to work without modifying the module i am trying to extend: i could make modifications to it, but let's assume that it must remain as-is because i'm trying to understand best practice in this situation.</p>
  
  <p>I'm working with the <a href="http://pypi.python.org/pypi/icalendar" rel="nofollow">http://pypi.python.org/pypi/icalendar</a> module, which handles parsing from and serializing to the Icalendar spec (hereafter ical). It parses the text into a hierarchy of dictionary-like "component" objects, where every "component" is an instance of a trivial derived class implementing the different valid ical types (VCALENDAR, VEVENT, etc.) and they are all spit out by a recursive factory from the common parent class:<br></p>
  
  <pre><code>class Component(...):
    @classmethod
    def from_ical(cls, ...)
  </code></pre>
  
  <p>I have created a 'CalendarFile' class that extends the ical 'Calendar' class, including in it generator function of its own:</p>
  
  <pre><code>class CalendarFile(Calendar):
    @classmethod
    def from_file(cls, ics):
  </code></pre>
  
  <p>which opens a file (<code>ics</code>) and passes it on: </p>
  
  <pre><code>     instance = cls.from_ical(f.read())
  </code></pre>
  
  <p>It initializes and modifies some other things in <code>instance</code> and then returns it. The problem is that <code>instance</code> ends up being a <code>Calendar</code> object instead of a <code>CalendarFile</code> object, in spite of <code>cls</code> being <code>CalendarFile</code>. Short of going into the factory function of the ical module and fiddling around in there, is there any way to essentially "recast" that object as a 'CalendarFile'?</p>
  
  <p>The alternatives (again without modifying the original module) that I have considered are:<ul><li>make the <code>CalendarFile</code> class a has-a <code>Calendar</code> class (each instance creates its own internal instance of a <code>Calendar</code> object), but that seems methodically stilted.
  <li>fiddle with the returned object to give it the methods it needs (i know there's a term for creating a customized object but it escapes me).
  <li>make the additional methods into functions and just have them work with instances of <code>Calendar</code>.
  <li>or perhaps the answer is that i shouldn't be trying to subclass from a module in the first place, and this type of code belongs in the module itself.
  </ul></p>
  
  <p>Again i'm trying to understand what the "best" approach is and also learn if i'm missing any alternatives. Thanks.</p>