[sonic_platform_base] Reallocate empty lists in the constructor of the base class#65
[sonic_platform_base] Reallocate empty lists in the constructor of the base class#65jleveque merged 1 commit intosonic-net:masterfrom ds952811:master
Conversation
… the base class When we use a mutable object as a default value in the base class, a value that can be modified in place in the subclasses, such as the empty lists of the chassis base class, and it is most likely unwanted. And hence, this commit will try to address this issue by allocating new empty list objects at the constructor of the base class, and the subclass should rely on the constructor of superclass for this. As a result, it simplifies the source code, and reduce the maintenance efforts Signed-off-by: Dante (Kuo-Jung) Su <[email protected]>
|
Here is an example to help you understand what's exactly the problem we try to address. root@sonic:~# cat test.py import sonic_platform.platform chassis = sonic_platform.platform.Platform().get_chassis() print("FAN number: {}".format(chassis.get_num_fans())) chassis = sonic_platform.platform.Platform().get_chassis() print("FAN number: {}".format(chassis.get_num_fans())) root@sonic: |
|
So just to confirm, you're claiming that with the current code, after the second call to |
Yes, as the fan list of the base class will be modified in place, so the number of devices will be double at 2nd call, and triple at 3rd call. The same issues apply to all the LIST objects in the base classes (As they're mutable objects) |
|
Here is a good article to help you have a better understanding of this issue |
… the base class
When we use a mutable object as a default value in the base class, a value that can be modified in place in the subclasses, such as the empty lists of
the chassis base class, and it is most likely unwanted.
And hence, this commit will try to address this issue by allocating new empty
list objects at the constructor of the base class, and the subclass should
rely on the constructor of superclass for this.
As a result, it simplifies the source code, and reduce the maintenance efforts
Signed-off-by: Dante (Kuo-Jung) Su [email protected]