Return to Home Page
      Blog     Consulting     Seminars     Calendar     Books     CD-ROMS     Newsletter     About     FAQ      Search
 

Creation of objects is such a common pattern that in Python it has made it into the language. In Python, classes are themselves factories. Classes are just callable objects that create objects, and classes are also first class objects which can be passed around in variables and aliased using other mechanisms, such as in import statements.

This means that probably about 95% of the factory pattern code on this page is totally redundant in Python. They are caused by thinking in Java or C++, in which the 'new' keyword is always followed by the name of a class. In Python there is no new keyword, and so the problems caused by it are not there to solve.

Of course, there will come a point when you might want a factory object that will store classes for you by name. But you would only ever create it in Python when you actually need it, and it would start off as a dictionary. Here is some pseudo-code to create a GUI dynamically using a form definition and a 'widgets' factory object, which is just a dictionary of widget classes:


class DynamicForm
  def build_form(self, form_definition, widgets):
     for item in form_definition:
        control = widgets[item.klass]()
        self.controls.add()

The widgets dictionary would be created externally by code that works out what the widgets should be, and stores them by name in the dictionary.

If you decide that 'widgets' needs to be more complex than a dictionary (e.g. implements lazy loading of classes etc), then just change it to a class that implements the same interface as a dictionary (in this case all you need is __getitem__ ).

Starting out with factories is just way over the top in Python. Classes are factories -- problem solved.

f  e  x



Add your comment below. Use an empty line between each paragraph. Paragraphs will be automatically formatted, and single carriage returns will be respected. Use <code> to begin a code block, and </code> to end a code block. Your email address will not be visible to spam harvesters or used in any way except to contact you with further questions.

Your Email Address:

Search     Home     WebLog     Consulting     Seminars     Calendar     Books     CD-ROMS     Newsletter     About     Contact     Site Design     Server Maintenance     Powered by Zope
©2007 MindView, Inc.