python factory function best practices

Posted by Jason S on Programmers See other posts from Programmers or by Jason S
Published on 2012-09-29T13:58:21Z Indexed on 2012/09/29 15:51 UTC
Read the original article Hit count: 203

Filed under:
|

Suppose I have a file foo.py containing a class Foo:

class Foo(object):
   def __init__(self, data):
      ...

Now I want to add a function that creates a Foo object in a certain way from raw source data. Should I put it as a static method in Foo or as another separate function?

class Foo(object):
   def __init__(self, data):
      ...
# option 1:
   @staticmethod
   def fromSourceData(sourceData):
      return Foo(processData(sourceData))

# option 2:
def makeFoo(sourceData):
   return Foo(processData(sourceData))

I don't know whether it's more important to be convenient for users:

foo1 = foo.makeFoo(sourceData)

or whether it's more important to maintain clear coupling between the method and the class:

foo1 = foo.Foo.fromSourceData(sourceData)

© Programmers or respective owner

Related posts about design

Related posts about python