Search code examples
pythonlistmemoryextend

Python: List type becomes None (out of scope?) when extended insde a list created inside an argument


I was trying to extend the list class so I can add a name to a list, lateron I wanted to created all the lists

So I have the following code: But the problem is that it only works for one level

class seg(list):
    def __init__(self, value):
        self.value = value

def show_hierarchy(fl,hierarchy=""):
    hierarchy += fl.value + " - "
    print(hierarchy.rstrip(" - "))
    for lists in fl:
        show_hierarchy(lists, hierarchy)

# one level deep
fl = seg("1")
fl.extend([
    seg("1.1"),
    seg("1.2"),
    seg("1.3"),
    seg("1.4")])

print(fl)
show_hierarchy(fl)

# two levels deep
fl = seg("1")
fl.extend([
    seg("1.1"),
    seg("1.2").extend([
        seg("1.2.1"),
        seg("1.2.2")])])

print(fl)
show_hierarchy(fl)

With the following output:

[[], [], [], []]
1
1 - 1.1
1 - 1.2
1 - 1.3
1 - 1.4
[[], None]
1
1 - 1.1

I really want to know what happends and how I can solve this.


Solution

  • By convention, mutator methods on Python containers return None (not always, consider list.pop). You can, of course, change this behavior in your derived class, although, I am agnostic about whether or not this is a good idea:

    In [121]: class seg(list):
         ...:     def __init__(self, value):
         ...:         self.value = value
         ...:     def extend(self, value):
         ...:         list.extend(self, value)
         ...:         return self
         ...:
    
    In [122]: fl = seg("1")
         ...: fl.extend([
         ...:     seg("1.1"),
         ...:     seg("1.2").extend([
         ...:         seg("1.2.1"),
         ...:         seg("1.2.2")])])
         ...:
    Out[122]: [[], [[], []]]
    
    In [123]: def show_hierarchy(fl,hierarchy=""):
         ...:     hierarchy += fl.value + " - "
         ...:     print(hierarchy.rstrip(" - "))
         ...:     for lists in fl:
         ...:         show_hierarchy(lists, hierarchy)
         ...:
    
    In [124]: show_hierarchy(fl)
    1
    1 - 1.1
    1 - 1.2
    1 - 1.2 - 1.2.1
    1 - 1.2 - 1.2.2