Skip to content
Advertisement

Reorder a tree node according to specific attribute in python

The code of simple tree

class A_1:
    saveable =True
    
class A_2:
    saveable =False
    
class B_1:
    saveable =True
    
class B_2:
    saveable =False
    
class C_1:
    saveable =False
    
class C_2:
    saveable =True
    

class A:
    saveable = True
    inline = [A_1,A_2]
class B:
    saveable = False
    inline = [B_1,B_2]

class C:
    saveable = True
    inline = [C_1,C_2]

class Main:
    inline =[A,B,C]

the code diagram is :given

I want a function or a method that order the node according saveable attribute. I want the output like:

>>Main.inline
[B, C, A]

>>A.inline
[A_2,A_1]

and so on

if we plot the output is same like: required

Advertisement

Answer

While I disagree with the approach, this is what you need to do: (I’ve modified the code as little as possible, and added tests at the bottom to prove it works)

import operator

class A_1:
    saveable =True

class A_2:
    saveable =False

class B_1:
    saveable =True

class B_2:
    saveable =False

class C_1:
    saveable =False

class C_2:
    saveable =True

class Ordered(type):
    def __new__(cls, name, bases, attr):
        new_klass = super(Ordered, cls).__new__(cls, name, bases, attr)
        # Uncomment the line bellow after you've read the comment in all the 
        # way at the bottom of the code.
        #
        # new_klass.inline.sort(key=lambda x: x.__name__, reverse=True)
        new_klass.inline.sort(key=operator.attrgetter('saveable'))
        return new_klass

class A(metaclass=Ordered):
    saveable = True
    inline = [A_1,A_2]

class B(metaclass=Ordered):
    saveable = False
    inline = [B_1,B_2]

class C(metaclass=Ordered):
    saveable = True
    inline = [C_1,C_2]

class Main(metaclass=Ordered):
    inline =[A,B,C]

# this differs from your example slightly, since you asked 
# for `[B, C, A]`, in order to get that working, is just a 
# matter of changing the `sort()` above, and uncommenting 
# the commented line in the function. I left it there in
# case you REALLY wanted it. I figured this would be enough
# and the alternative just complicates things further
assert Main.inline == [B, A, C]
# assert Main.inline == [B, C, A]
assert A.inline == [A_2, A_1]
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement