Home > Blockchain >  Quiting while loop through class method
Quiting while loop through class method

Time:03-22


from dataclasses import dataclass, field
from employee import Employee
import json
import re
# from custom_exception import Input_Exception

@dataclass()
class ResourceManager:
    employee_list: dict = field(default_factory=dict)

    def menu(self):
        print('Menu:')
        print('1 : Show data about employee')
        print('2 : Add new employee')
        print('3 : Remove employee')
        print('4 : Add or remove employee hours')
        print('5 : Save changes into the file')
        print('6 : Load data from the file')
        print('7 : Check employee salary')
        print('0 : Exit program')

    def controls(self):
        switch = {
            "1": self.search_employee,
            "2": self.add_employee,
            "3": self.remove_employee,
            "4": self.change_hours,
            "5": self.save_data,
            "6": self.load_data,
            "7": self.check_salary,
            "x": self.quit,
        }

        choice = input("Wybierz jedną opcję:\n=> ")
        if choice in switch.keys():
            switch[choice]()
        else:
            print("Niepoprawny wybór!")


    def quit(self):
        x = False
        return x

ResourceManage is a class used to represent fairly simple CLI, I used dictionary to implement switch and want to use def quit(self) to exit program.

from resource_manager import ResourceManager
if __name__ == '__main__':
    setup = ResourceManager()
    x = True
    while x:
        setup.menu()
        setup.controls()

CLI Menu where I'm trying to use def quit(self) method to quit while loop by changing global x but it dose not work. I've tried quite few different thing but cant get this to work.

How can I fix that?

CodePudding user response:

In your code there are two x. One x is in the local function quit, the other is the one in global scope. Assigning one won't change the other.

I would suggest you to add a attribute to the ResourceManager that states whether the cli should exit.

This could work like that:


from dataclasses import dataclass, field
from employee import Employee
import json
import re
# from custom_exception import Input_Exception

@dataclass()
class ResourceManager:
    employee_list: dict = field(default_factory=dict)
    x: bool = True

    def menu(self):
        print('Menu:')
        print('1 : Show data about employee')
        print('2 : Add new employee')
        print('3 : Remove employee')
        print('4 : Add or remove employee hours')
        print('5 : Save changes into the file')
        print('6 : Load data from the file')
        print('7 : Check employee salary')
        print('0 : Exit program')

    def controls(self):
        switch = {
            "1": self.search_employee,
            "2": self.add_employee,
            "3": self.remove_employee,
            "4": self.change_hours,
            "5": self.save_data,
            "6": self.load_data,
            "7": self.check_salary,
            "x": self.quit,
        }

        choice = input("Wybierz jedną opcję:\n=> ")
        if choice in switch.keys():
            switch[choice]()
        else:
            print("Niepoprawny wybór!")


    def quit(self):
        self.x = False
        return self.x

The main can now reference the attribute the following:

if __name__ == '__main__':
    setup = ResourceManager()
    while setup.x:
        setup.menu()
        setup.controls()

I hope i could help you?

CodePudding user response:

The x that is assigned True in your quit() function is creating a new local variable that is only visible inside the function. You need to use the global keyword to access or mutate the global variable x from inside your function. Also, note that returning the value of x has no effect since the call inside control() doesn't use the value.

    def quit(self):
        global x 
        x = False

Using a global variable like this is generally an anti-pattern though, so you should consider changing x to be a property of your class and checking it in the main loop.

  • Related