Python – Init a class with a default list property correctly

Sometimes, (but only sometimes) we think that writing too much code is useless and writing less code in python is more readable and performs faster. While in the general case this is true, this article is simply going to show a strange and unwanted error (or feature, if you can sell it this well), that will happen if you use default list as a property in a python class, without setting the property to None.

There is definitely a class in this picture.

Imagine that you have the following class:

Somehow, you might decide to rewrite the __init__ with default empty list in it, in order to remove the if players is None check and to save 3 rows. It will look like this:

What can go wrong? Well, if you pass a non empty list every time, when you use the class everything will be ok. But if you create two instances of the StrangeFootballClub class with the default empty list, then strange things will happen – the two instances will refer to the same list. Definitely a bug (unless you really manage to convince someone it is a feature) and black python magic…

Take a look here:

Take home message – do not oversimplify everything, some standard checks are there for a reason!

Enjoy it:)

Tagged with: , , , ,