Home > Mobile >  assert menu.__str__() == "" AssertionError
assert menu.__str__() == "" AssertionError

Time:10-26

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:

main_menu = Menu()
main_menu.add("Open new account")
main_menu.add("Log into existing account")
print(main_menu)

The error comes when i run:

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

here is my code:

class Menu:

    def __init__(self):
        #self.counter = counter
        a_list = []
        self.a_list = a_list
        

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

    def add(self, element):
            self.element = element
            self.a_list.append(element)
            return self.a_list
        

    def remove(self, element):
        return self.a_list.remove(element)

    def insert(self, element, a_position):
        return self.a_list.insert(a_position -1, element)

    
    def position(self, element):
        try:
            return self.a_list.index(element)
        except ValueError:
            return 0

CodePudding user response:

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))

CodePudding user response:

Your __str__() function does not return a string if nothing is added to the object before the assertion. An assertion error would be generated even if the function was called correctly.

CodePudding user response:

I believe that the answer from @azro fixed the Error by removing:

for element in self.a_list:

        if element:

From the str(self): function

  • Related