Factory functions?

Remco Gerlich scarblac at pino.selwerd.nl
Sun Apr 1 17:14:28 EDT 2001


Roy Smith <roy at panix.com> wrote in comp.lang.python:
> Typically, when I write a new class module, I'll call the class the same 
> name as the module, and then create objects of that class by doing:
> 
> import foo
> myFooObject = foo.foo()
> 
> I've always found this kind of awkward and ugly, and somewhat confusing, 
> especially when the names are kind of long, i.e.
> 
> myFrobnitz = reverseIteratorFrobnitz.reverseIteratorFrobnitz()

Don't Do That Then! :-)

> It seems to me, you could "solve" this problem (I put "solve" in quotes 
> because I'm not yet really convinced there's a problem that needs solving) 
> by using a factory function, i.e.
> 
> -----file reverseIteratorFrobnitz.py-----
> 
> import iteratorFrobnitz
> 
> class reverseIteratorFrobnitz (iteratorFrobnitz.iteratorFrobnitz):
>    def __init__ (self, name):
>       self.name = name;
>       self.interationSense = -1
> 
> def new (name):
>    return reverseIteratorFrobnitz (name)

Shorter would be:
new = reverseIteratorFrobnitz
 
> -----------------------------------------
> 
> Then when I want to use one of these, I just do:
> 
> import reverseIteratorFrobnitz
> myFrobnitz = reverseIteratorFrobnitz.new ("Dinsdale")
> 
> What are the pros and cons of doing it one way or the other (i.e. calling 
> the built-in class creator directly, or calling a trivial factory function 
> to create an object for you and return it).  Is it really just a matter of 
> style and esthetics more than anything else?

I'd say you could also put more classes in a module (you can also do
that by from...importing classes from other modules in one), or pick
shorter names, or to use from...import in the first place, or give the
module a different name, or do what you did.

I think a factory function called "new" that instantiates some class is
unclear. But if you use it everywhere, it's great. Style, indeed.

You give the class some great, clear, slightly too large name. Then you also
call it "new" to avoid having to use the name...

I'm not saying this because Dinsdale nailed my head to the floor. Really, he
was very reasonable about it. Great guy, good ol' Dinsey.

("And then, even the police began to notice.")

This is one of those nonsensical rants I seem to have at times. Never mind.

-- 
Remco Gerlich



More information about the Python-list mailing list