I came across this super weird functionality when in the last SMP project. It really makes absolutely no sense why Python would behave like this. Of course, trying to find things via the all-knowing Google proved inconclusive. Here’s what was happening.
First, I have a Stack class that is definedlike so:
-
class Stack:
-
def __init__(self, initial = []):
-
self.container = initial
The reasoning behind that is that I wanted a default constructor that could initialize a Stack to not have anything in it, as well as initialize a Stack that already had some pre-defined stuff. Since you can’t overload methods, you can just do default parameters giving you (seemingly) the same functionality.
I was sorely mistaken. It took about an hour of trying to track down the problem, but in using that class definition something unexpected happens. Say I have the following code:
-
mystack = Stack()
-
mystack.push(1)
-
mystack.push(2)
-
mystack = Stack([3, 4, 5])
-
mystack.push(6)
You should think that at the end of that code, the stack would just contain 4 and 3. However, it actually contains all the elements, 6, 5, 4, 3, 2, 1 in that order. Wtf? I would think that if I wanted to call a constructor that it would actually create for me a new object. The only way I could find around it was to take out the default parameter in the constructor altogether like so:
-
def __init__(self, initial):
-
self.container = initial
And declare a new empty stack like so:
-
mystack = Stack([])
And then it seems to work just fine.