Is there a better way to define multiple boolean variables?
Question:
I have multiple Boolean variables in my code and now they are defined like this:
self.paused, self.show_difficulty, self.resizable, self.high_score_saved,
self.show_high_scores, self.show_game_modes =
False, False, True, False, False, False
And I thought of refactoring the code like this to improve readability.
ui_options = {
"paused": False,
"show_difficulty": False,
"resizable": False,
"high_score_saved": False,
"show_high_scores": False,
"show_game_modes": False
}
Is there a better way to do it?
Answers:
To group values like this, I’d recommend using a dataclass over a dictionary. This means you can still have named attributes rather than needing to do string lookups. This will allow auto-completes and static analyzers to work with your code.
from dataclasses import dataclass
@dataclass
class UIOptions:
paused: bool = False
show_difficulty: bool = False
resizable: bool = False
high_score_saved: bool = False
show_high_scores: bool = False
show_game_modes: bool = False
ui_options = UIOptions()
I have multiple Boolean variables in my code and now they are defined like this:
self.paused, self.show_difficulty, self.resizable, self.high_score_saved,
self.show_high_scores, self.show_game_modes =
False, False, True, False, False, False
And I thought of refactoring the code like this to improve readability.
ui_options = {
"paused": False,
"show_difficulty": False,
"resizable": False,
"high_score_saved": False,
"show_high_scores": False,
"show_game_modes": False
}
Is there a better way to do it?
To group values like this, I’d recommend using a dataclass over a dictionary. This means you can still have named attributes rather than needing to do string lookups. This will allow auto-completes and static analyzers to work with your code.
from dataclasses import dataclass
@dataclass
class UIOptions:
paused: bool = False
show_difficulty: bool = False
resizable: bool = False
high_score_saved: bool = False
show_high_scores: bool = False
show_game_modes: bool = False
ui_options = UIOptions()