4 ms·
But Python has had this behavior for ever with default values: class A: def x(self, b=B()): # doesn't work return B() # works cla
by progval 6y ago
But Python has had this behavior for ever with default values:
class A:
def x(self, b=B()): # doesn't work
return B() # works
class B:
pass
- nbadg 6y agoGenerally speaking that's considered unpythonic though. Default values are evaluated exactly once, at function definition time. So if you do this, then your default B() will always be the exact same instance of the B class -- literally the same object in memory -- every time you call the function. That's rarely what you want; you usually want the default to be a fresh instance of B(). So instead, the pythonic way is for the default to be None, and then to convert those Nones into their actual defaults in the top of the function/method. This then has the added benefit of playing more nicely with subclassing (as well as composition), because instead of needing to bubble the defaults up the call chain, you simply pass down None and let the implementing function worry about resolving it into the actual default.
- progval 6y agoYes of course, that's just an example. In practice is can happen with immutable values, like a namedtuple.
- travisjungroth 6y agoI make way more small, immutable classes than the average Python developer. I've never had the reference issue with defaults and always have it with hints.
- Siira 6y agoYou can use “None” there, and set the default value in the function.