constructor classmethods

Chris Angelico rosuav at gmail.com
Thu Nov 3 10:47:03 EDT 2016


On Thu, Nov 3, 2016 at 7:50 PM,  <teppo.pera at gmail.com> wrote:
> Little bit background related to this topic. It all starts from this article:
> http://misko.hevery.com/attachments/Guide-Writing%20Testable%20Code.pdf
>
> The guide is written in c++ in mind, yet the concepts stands for any programming language really. Read it through and think about it. If you come back to this topic and say: "yeah, but it's c++", then you haven't understood it.

I don't have a problem with something written for C++ (though I do
have a problem with a thirty-eight page document on how to make your
code testable - TLDR), but do bear in mind that a *lot* of C++ code
can be simplified when it's brought to Python. One Python feature that
C++ doesn't have, mentioned already in this thread, is the way you can
have a ton of parameters with defaults, and you then specify only
those you want, as keyword args:

def __init__(self, important_arg1, important_arg2,
        queue=None, cache_size=50, whatever=...):
    pass

MyClass("foo", 123, cache_size=75)

I can ignore all the arguments that don't matter, and provide only the
one or two that I actually need to change. Cognitive load is
drastically reduced, compared to the "alternative constructor"
pattern, where I have to remember not to construct anything in the
normal way.

You can't do that in C++, so it's not going to be mentioned in that
document, but it's an excellent pattern to follow.

ChrisA



More information about the Python-list mailing list