Using a classmethod to wrap class functions, but not as an alternate constructor

Question:

I’ve gotten in the habit of using classmethods to wrap class functions rather than as an alternate constructor. It seems great to keep all relevant functions within the class namespace rather than defining a wrapper function in the general namespace. I’ve been told this is unpythonic and I haven’t seen this pattern elsewhere. Why is pattern B preferable to pattern A?

Trivial examples:

Pattern A (my pattern):

class Foo():
  def __init__(self, bar):
    self.bar = bar

  def baz(self):
    print(self.bar)

  @classmethod
  def foobaz(cls, bar):
    foo = cls(bar)
    foo.baz()

Pattern B (a normal pattern):

class Foo():
  def __init__(self, bar):
    self.bar = bar

  def baz(self):
    print(self.bar)

def foobaz(bar):
    foo = Foo(bar)
    foo.baz()
Asked By: Austin Weisgrau

||

Answers:

"unpythonic" is rather subjective (in most cases 🙂 ). Although I’d myself opt for using the function pattern in most places – it may make sense in certain projects, or even in certain parts of larger projects to prefer using the class namespace as you want.

That said, nothing against your pattern. If it does matter anything, I ‘ve been lecturing on "things I consider Pythonic and what not" for well over ten years now.

In terms of execution time, there might be a small overhead on using "classmethod" over a straight function, but it would be "two orders of magnitude below negligible".

Documentation-wise it looks like having your methods as classmethods make more sense as well.

Answered By: jsbueno

Later on I realized that calling Foo(bar).baz() is superior to either of the above methods. Defining the foobaz method is okay but is unnecessary and adds extra code. This requires one less method to be defined yet is just as clear. Not sure why it didn’t occur to me before.

Answered By: Austin Weisgrau