I've read this SO discussion about factory methods, and have an alternate constructor use case.
My class looks like this:
class Foo(object):
def __init__(self, bar):
self.bar = bar
@classmethod
def from_data(cls, datafile):
bar = datafile.read_bar()
# Now I want to process bar in some way
bar = _process_bar(bar)
return cls(bar)
def _process_bar(self, bar)
return bar + 1
My question is, if a @classmethod factory method wants to use a function in its code, should that function (_proces_bar) be:
- A
@classmethod, which seems a bit weird because you won't ever call it likeFoo._process_bar() - A method outside of the class
Foobut in the same.pyfile. I'd go with this, but it seems kind of weird. Will those methods always be available to an instance ofFoo, regardless of how it was instantiated? (e.g. what if it's saved to a Pickle then reloaded? Presumably methods outside the class will then not be available!) - A
@staticmethod? (see 1. This seems weird) - Something else? (but not this!)
processis only used infrom_data, make it a local function. Otherwise, I'd go with a module-level func. Could you elaborate on the import problem?@staticmethodwould be weird? Just declare it withdef _process_bar(bar):and call it infrom_data()withcls._process_bar(bar).