Factories in Python

R

Robert Ferrell

I'm wondering how Python cognoscenti use/implement factory patterns in
Python. In my limited C++ experience, one reason to use a factory
method is to make it easier to create instances of classes derived off
a base class. The instance is declared to be an instance of the base
class. The factory returns an instance of a derived class, and
everything is groovy. In Python, since type declarations need not be
static, it seems there is no need to have a factory method.

However, I'm guessing that I'm not understanding other benefits of
using factories in Python. Does anybody have examples or pointers on
how use of factories in Python?

thanks
-robert
 
D

Dave Kuhlman

Robert Ferrell wrote:

[snip]
However, I'm guessing that I'm not understanding other benefits of
using factories in Python. Does anybody have examples or pointers
on how use of factories in Python?

Here is a link:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/86900

A reason for using a factory is that the client (the code that
creates the instance) does not know which class or sub-class it
wants to create an instance of. So, you build a factory that is
smart enough to create an instance of the right class.

In my case, while parsing an XML document and creating instances
of nodes in the tree that represents the document, the classes
(the super-class of each node class) does the parsing. However,
each super-class must be smart enough to create a tree populated
with instances of sub-classes, which may contain additional custom
code,*if* they are available.

I'd be interested in other reasons for using factories.

- Dave
 
T

Troy Melhase

Dave said:
I'd be interested in other reasons for using factories.

My most frequent reason for using factories is to insulate client code from
refering directly to a class name. I find I do this most often when I have
code that's likely to change soon or change frequently. This approach
allows me to leave client code unchanged although the actual class names
and implementations may vary greatly.

Consider:

class MightBeWhatIWant:
pass

class HelperForThat:
pass

def build():
return MightBeWhatIWant()

As the problem is revealed thru elbow grease, this might change:

class ThisIsWhatIReallyNeeded:
pass

class SomethingIMissedEarlier:
pass

def build():
return ThisIsWhatIReallyNeeded()

Granted, these aren't factories in the strictest GoF sense, but I think the
intent is clear.

troy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,998
Messages
2,570,242
Members
46,834
Latest member
vina0631

Latest Threads

Top