Is it OK to replace a method by a plain function?
<p>This works as expected, but I am somehow unsure about this approach. Is it safe? Is it pythonic?</p>

<pre><code>class Example:
    def __init__(self, parameter):
        if parameter == 0:
            # trivial case, the result is always zero
            self.calc = lambda x: 0.0  # &lt;== replacing a method
        self._parameter = parameter

    def calc(self, x):
        # ... long calculation of result ...
        return result
</code></pre>

<p>(If there is any difference between Python2 and Python3, I'm using Python3 only.)</p>

<p><em>I decided to post a summary of several comments and answers. Please do not vote for this summary, but give +1 to the original authors instead</em>.</p>

<ul>
<li>the approach is safe except for special <code>__methods__</code></li>
<li>the approach is deemed unpythonic, undesirable, or unnecessary etc.</li>
<li>the parameter determining the function to use must be constant. If it is not the case, this approach makes no sense at all.</li>
<li>from several suggestions I prefer the code below for general cases and the obvious <code>if cond: return 0.0</code> for simple cases:</li>
</ul>

<hr>

<pre><code> class Example:
    def __init__(self, parameter):
        if parameter == 0:
            self.calc = self._calc_trivial
        else:
            # ... pre-compute data if necessary ...
            self.calc = self._calc_regular
        self._parameter = parameter

    def _calc_regular(self, x):
        # ... long calculation of result ...
        return result

    @staticmethod
    def _calc_trivial(x):
       return 0.0
</code></pre>

python