pythonerror-handlingattributeerrorpython-classpython-object

Attribute error when trying to going back and forth between functions in Python


I'm getting the error "AttributeError: 'NoneType' object has no attribute 'name'" for the code below:

class Student:
    def __init__(self, name, house):
        if not name:
            raise ValueError("Missing name!")
        self.name = name
        self.house = house

def main():
    student = get_student()
    print(f"{student.name} from {student.house}")


def get_student():
    name = input("Name: ")
    house = input("House: ")
    try:
        return Student(name, house)
    except ValueError:
        print("Please make sure to enter a name...")
        main()


if __name__ == "__main__":
    main()

I was hoping that the main() call inside get_student() function will create a recursion-like effect and will allow the program to go on until both 'name' and 'house' have been inserted. However, what happens is a little different.

When I enter name and house, the program works. When I omit entering a name, it does print the ValueError message in get_student() and prompts for another set of inputs.. but, then I get "AttributeError: 'NoneType' object has no attribute 'name'".

Am I doing something completely stupid? Any help is much appreciated.


Solution

  • Adding the error message is always helpful.

    I assume that your AttributeError also mentions that you have a NoneType object? If so, when you do not provide a name and raise a ValueError within Student, your Student object dissolves into a None.

    The issue comes when you are call the menu function recursively. The student variable with the None value has not printed at this point. The program is waiting for the user to input a valid name and a house.

    Once that valid name and house are place, the Student object will be initialized appropriately, and its attributes printed. Your program will then move down the call stack, and print the None value from the Student object that originally raised the ValueError.

    Rather than entering a recursive call to main, you can add a while loop with an exit condition. The exit condition would be a non-empty string for the variable name