3

When I'm creating a new class, if one of my attribute is an empty list, pychram suggest to change it to this:

class meet_angle_cond:
    def __init__(self, xy_lat_lon_list=None):
        if xy_lat_lon_list is None:
           xy_lat_lon_list = []
           self.xy_lat_lon_list = xy_lat_lon_list

I'm struggling to understand why this is better than:

class meet_angle_cond:
    def __init__(self, xy_lat_lon_list=[]):
           self.xy_lat_lon_list = xy_lat_lon_list

It seems to me that this way is more effective and readable.

Premkumar chalmeti
  • 800
  • 1
  • 8
  • 23

1 Answers1

1

Because lists are mutable. Check these snippets.

def append_to(element, to=[]):
    to.append(element)
    return to

What You Might Have Expected to Happen

my_list = append_to(12)
print(my_list)

my_other_list = append_to(42)
print(my_other_list)

Expected output,

[12]
[42]

Actual output,

[12]
[12, 42]

So pycharm suggests you to use None as default argument.

Premkumar chalmeti
  • 800
  • 1
  • 8
  • 23