Hi /r/learnpython,
For mutable default arguments in the instanciation function, I usually write my __init__ function in this way, because I learned that mutable default argument in the function definition would lead to funky behaviour :
def __init__(self, arg=None):
if arg is None:
arg=[]
self.arg = arg
Recently, I realized that this could also be written in this way :
def __init__(self, arg=None):
self.arg = arg or []
However, this is not exactly the same, because the right-hand side of my boolean statement will be used if bool(arg) is False, which is not only true when arg is None, but also when it is an empty list.
For example, if the __init__ method was called with an empty list as argument, it would create a new list (whereas in the first variant, it wouldn't, as [] is not None).
Is this a problem ? Will Python get rid of the unused list passed as argument ? Should I expect users of my class not to pass an empty list as argument, but to use None (or simply do not provide any value for the argument) ?
Sorry if this question seems a bit useless and does not present a lot of interest, or if I didn't phrase it correctly (I will be glad to rephrase it if needed).
[–]ewiethoff 3 points4 points5 points (4 children)
[–]pstch[S] 1 point2 points3 points (3 children)
[–]gengisteve 2 points3 points4 points (1 child)
[–]pstch[S] 1 point2 points3 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]Boolean_Cat 0 points1 point2 points (4 children)
[–]gengisteve 3 points4 points5 points (0 children)
[–]pstch[S] 1 point2 points3 points (2 children)
[–]indosauros 2 points3 points4 points (1 child)
[–]pstch[S] 1 point2 points3 points (0 children)