Skip to content
Advertisement

assert menu.__str__() == “” AssertionError

I get assertion error when i try to assert “” (empty string) into str function. Could anyone enlighten me as of why that happens. Totally clueless here. I know the str function needs to return a string but as far as i know it is returning a string when i run:

The error comes when i run:

menu = Menu() 
assert menu.str() == "" 

here is my code:

    class Node:

    def __init__(self):
        self.counter = counter
        my_list = []
        self.my_list = my_list
        

    def __str__(self):
        for element in self.a_list:
            if element:
                return "n".join(f"{counter}. {element}" for counter, 
                element in enumerate(self.my_list, 1)) 
            print()
    
          

Advertisement

Answer

As the declaration is def __str__(self): you need to call it like

assert menu.__str__() == ""

Or using str method

assert str(menu) == ""

Also you have a for loop, that includes another loop on the same a_list. A good implementation is

# with classic for loop syntax
def __str__(self):
    result = ""
    for counter, element in enumerate(self.a_list, 1):
        result += f"{counter}. {element}n"
    return result


# with generator syntax
def __str__(self):
    return "n".join(f"{c}. {elem}" for c, elem in enumerate(self.a_list, 1))
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement