python factory function best practices
- by Jason S
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)