Skip to content

Commit

Permalink
Add Option class
Browse files Browse the repository at this point in the history
  • Loading branch information
wong2 committed Aug 31, 2022
1 parent 5e03169 commit a043d66
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 9 deletions.
10 changes: 10 additions & 0 deletions example/option.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from pick import pick, Option

title = "Please choose your favorite programming language: "
options = [
Option("Java", ".java"),
Option("Python", ".py"),
Option("JavaScript", ".js"),
]
option, index = pick(options, title)
print(f"You choosed {option} at index {index}")
22 changes: 14 additions & 8 deletions src/pick/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import curses
from dataclasses import dataclass, field
from typing import List, Optional, Sequence, Tuple, Union
from typing import Any, List, Optional, Sequence, Tuple, TypeVar, Union, Generic

__all__ = ["Picker", "pick"]
__all__ = ["Picker", "pick", "Option"]


@dataclass
class Option:
label: str
value: Any


KEYS_ENTER = (curses.KEY_ENTER, ord("\n"), ord("\r"))
Expand All @@ -13,13 +19,13 @@
SYMBOL_CIRCLE_FILLED = "◉"
SYMBOL_CIRCLE_EMPTY = "◯"

KEY_T = int
PICK_RETURN_T = Tuple[str, int]
OPTION_T = TypeVar("OPTION_T", str, Option)
PICK_RETURN_T = Tuple[OPTION_T, int]


@dataclass
class Picker:
options: Sequence[str]
class Picker(Generic[OPTION_T]):
options: Sequence[OPTION_T]
title: Optional[str] = None
indicator: str = "*"
default_index: int = 0
Expand Down Expand Up @@ -93,7 +99,7 @@ def get_option_lines(self) -> List[str]:
)
prefix = f"{prefix} {symbol} "

option_as_str = str(option)
option_as_str = option.label if isinstance(option, Option) else option
lines.append(f"{prefix} {option_as_str}")

return lines
Expand Down Expand Up @@ -166,7 +172,7 @@ def start(self):


def pick(
options: Sequence[str],
options: Sequence[OPTION_T],
title: Optional[str] = None,
indicator: str = "*",
default_index: int = 0,
Expand Down
12 changes: 11 additions & 1 deletion tests/test_pick.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from pick import Picker
from pick import Picker, Option


def test_move_up_down():
Expand Down Expand Up @@ -45,3 +45,13 @@ def test_multi_select():
picker.move_down()
picker.mark_index()
assert picker.get_selected() == [("option1", 0), ("option2", 1)]


def test_option():
options = [Option("option1", 101), Option("option2", 102), Option("option3", 103)]
picker = Picker(options)
picker.move_down()
option, index = picker.get_selected()
assert index == 1
assert isinstance(option, Option)
assert option.value == 102

0 comments on commit a043d66

Please sign in to comment.