### Setup Method Implementation Example Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/backend.md Example implementation of the setup method for a curses-based backend. Initializes curses and hides the cursor. ```python def setup(self) -> None: curses.use_default_colors() curses.curs_set(0) # Hide cursor ``` -------------------------------- ### Install Pick from Source Source: https://github.com/aisk/pick/blob/master/_autodocs/index.md Install 'pick' directly from its GitHub repository. This involves cloning the repository and performing an editable installation. ```bash git clone https://github.com/aisk/pick.git cd pick pip install -e . ``` -------------------------------- ### Custom Backend Instance with Logging Source: https://github.com/aisk/pick/blob/master/_autodocs/configuration.md Create a custom backend by subclassing `Backend` and wrapping an existing backend. This example adds logging to the setup and teardown methods. ```python from pick import Picker from pick.backend import Backend class LoggingBackend(Backend): def __init__(self, wrapped_backend): self.backend = wrapped_backend def setup(self): print("Setup called") self.backend.setup() def teardown(self): print("Teardown called") self.backend.teardown() # ... implement other methods by delegating to self.backend picker = Picker( ["A", "B", "C"], backend=LoggingBackend(...) ) ``` -------------------------------- ### Install Pick Source: https://github.com/aisk/pick/blob/master/README.md Install the pick library using pip. For the 'blessed' backend, use the optional extra. ```bash pip install pick ``` ```bash pip install "pick[blessed]" ``` -------------------------------- ### Install and Use Blessed Backend Source: https://github.com/aisk/pick/blob/master/_autodocs/errors.md Demonstrates the correct way to install the 'blessed' package and subsequently use the 'blessed' backend with the pick library. ```python from pick import pick # Install blessed first # pip install pick[blessed] # Then use it result = pick(["A", "B"], backend="blessed") ``` -------------------------------- ### Options with All Fields Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/option.md Demonstrates the usage of all fields within the Option class: label, value, description, and enabled status. This example shows a comprehensive setup for complex menu items. ```python from pick import pick, Option options = [ Option( label="Database: PostgreSQL", value="postgresql", description="Reliable open-source relational database" ), Option( label="Database: MongoDB", value="mongodb", description="Document-oriented NoSQL database" ), Option( label="Other Database (Unavailable)", value="custom", description="Configure your own database", enabled=False ) ] choice, idx = pick(options, title="Select database:") print(f"Chosen value: {choice.value}") ``` -------------------------------- ### Install Pick with Pip Source: https://github.com/aisk/pick/blob/master/_autodocs/index.md Use this command to install the standard version of the 'pick' library from PyPI. ```bash pip install pick ``` -------------------------------- ### setup() Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/curses-backend.md Initializes the curses backend for rendering, enabling color support and hiding the cursor. Falls back to basic initialization if color support fails. ```APIDOC ## setup() -> None ### Description Initialize the curses backend for rendering. Attempts to: 1. Enable default color support with `curses.use_default_colors()` 2. Hide the cursor with `curses.curs_set(0)` Falls back to basic initialization with `curses.initscr()` if color support fails (e.g., on `TERM=vt100` or other limited terminals). ### Method `setup()` ``` -------------------------------- ### Using a Different Backend with pick() Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/pick-function.md Demonstrates how to specify an alternative rendering backend, such as 'blessed', for the `pick` function. Ensure the required backend package is installed (e.g., `pip install pick[blessed]`). ```python from pick import pick options = ["Option A", "Option B"] # Use blessed backend (requires: pip install pick[blessed]) result = pick(options, backend="blessed") ``` -------------------------------- ### Different Backend Example Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/pick-function.md Illustrates how to use alternative rendering backends, such as 'blessed', by specifying the `backend` parameter. ```APIDOC ## Using Different Backend ```python from pick import pick options = ["Option A", "Option B"] # Use blessed backend (requires: pip install pick[blessed]) result = pick(options, backend="blessed") ``` ``` -------------------------------- ### Install Pick with Blessed Support Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/blessed-backend.md Install the 'pick' library with the optional 'blessed' dependency using pip. This enables the Blessed backend. ```bash # Install pick with blessed support pip install "pick[blessed]" # Or add to project dependencies pip install blessed ``` -------------------------------- ### Install Pick with Blessed Backend Source: https://github.com/aisk/pick/blob/master/_autodocs/index.md Install 'pick' with support for the Blessed backend by including the '[blessed]' extra. This enables enhanced terminal capabilities. ```bash pip install "pick[blessed]" ``` -------------------------------- ### CursesBackend Setup Method Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/curses-backend.md Initializes the curses backend, enabling default color support and hiding the cursor. Falls back to basic initialization if color support fails. ```python def setup(self) -> None: # Attempts to: # 1. Enable default color support with `curses.use_default_colors()` # 2. Hide the cursor with `curses.curs_set(0)` # Falls back to basic initialization with `curses.initscr()` if color support fails (e.g., on `TERM=vt100` or other limited terminals). ``` -------------------------------- ### BlessedBackend Setup Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/blessed-backend.md Initializes the blessed backend, entering fullscreen, cbreak mode, and hiding the cursor. All context managers are registered for cleanup in teardown. ```python def setup(self) -> None: pass ``` -------------------------------- ### start() Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/picker.md Launches the picker and runs the event loop. This is the main entry point for displaying and interacting with the menu. It returns the selected option(s) or indicates if the user quit. ```APIDOC ## start() ### Description Launches the picker and runs the event loop. This is the main entry point for displaying and interacting with the menu. ### Method Signature ```python def start(self) -> Union[List[Tuple[OPTION_T, int]], Tuple[OPTION_T, int], None]: ``` ### Returns - Single select: `(selected_option, index)` tuple - Multiselect: List of `(option, index)` tuples - Quit with `quit_keys`: `(None, -1)` for single-select or `[]` for multiselect ### Example ```python from pick import Picker options = ["Python", "JavaScript", "Rust"] picker = Picker(options, title="Choose a language") option, index = picker.start() print(f"Selected: {option} at index {index}") ``` ### Embedded curses context ```python import curses from pick import Picker def main(stdscr): options = ["Option A", "Option B", "Option C"] picker = Picker( options, screen=stdscr, clear_screen=False, position=Picker.Position(y=5, x=0) ) result = picker.start() return result curses.wrapper(main) ``` ``` -------------------------------- ### Picker Initialization with Blessed Backend Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/backend.md Initialize the Picker using the 'blessed' backend. Make sure 'blessed' is installed. ```python from pick import Picker # Use blessed backend picker = Picker(options, backend="blessed") ``` -------------------------------- ### Get Terminal Dimensions Example Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/backend.md Example of how to get and display terminal dimensions using the getmaxyx method. ```python height, width = backend.getmaxyx() print(f"Terminal: {height} rows × {width} columns") ``` -------------------------------- ### Add String to Screen Example Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/backend.md Example of using addnstr to write a limited number of characters to a specific screen location. ```python backend.addnstr(5, 10, "Hello World", 5) # Displays "Hello" at row 5, col 10 ``` -------------------------------- ### ASCII Codes for Regular Characters Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/backend.md These examples show how to get the ASCII codes for regular characters, including space and newline. ```python ord('a') # 97 ord('A') # 65 ord(' ') # 32 (space) ord('\n') # 10 (newline) ``` -------------------------------- ### Start Picker Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/picker.md Launches the picker and runs the event loop. This is the main entry point for displaying and interacting with the menu. Returns the selected option(s) and their index/indices. ```python from pick import Picker, Option options = ["Python", "JavaScript", "Rust"] picker = Picker(options, title="Choose a language") option, index = picker.start() print(f"Selected: {option} at index {index}") ``` -------------------------------- ### Basic Selection Example Source: https://github.com/aisk/pick/blob/master/README.md Demonstrates a simple interactive selection list. The selected option and its index are returned. ```python import pick title = 'Please choose your favorite programming language: ' options = ['Java', 'JavaScript', 'Python', 'PHP', 'C++', 'Erlang', 'Haskell'] option, index = pick(options, title) print(option) print(index) ``` -------------------------------- ### Multi-selection Example Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/pick-function.md Illustrates how to enable and configure multi-selection behavior using the `multiselect` and `min_selection_count` parameters. ```APIDOC ## Multi-selection ```python from pick import pick lans = ["Python", "JavaScript", "Rust", "Go", "Java"] selected = pick( langs, title="Choose 2-3 languages:", multiselect=True, min_selection_count=2 ) print(f"Selected: {selected}") ``` ``` -------------------------------- ### Picker Initialization with Default Backend Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/backend.md Initialize the Picker with the default curses backend. Ensure the 'pick' library is installed. ```python from pick import Picker # Use default curses backend picker = Picker(options) ``` -------------------------------- ### Get Character Input Example Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/backend.md Demonstrates reading a single key press from the user. This call blocks until a key is pressed and returns its integer code. ```python key_code = backend.getch() ``` -------------------------------- ### Option Objects Example Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/pick-function.md Demonstrates using `Option` objects for more complex selections, including values and descriptions. ```APIDOC ## With Option Objects ```python from pick import pick, Option options = [ Option("Python", value="py", description="General-purpose language"), Option("JavaScript", value="js", description="For web development"), Option("Rust", value="rs", description="Systems programming") ] choice, index = pick(options, title="Choose a language:") print(f"Label: {choice.label}, Value: {choice.value}") ``` ``` -------------------------------- ### Define Backend Interface Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/module-exports.md Abstract base class defining the interface for all Pick UI terminal rendering backends. Implementations must provide methods for setup, teardown, clearing, getting screen dimensions, adding strings, getting character input, and refreshing the display. ```python class Backend(ABC): """Abstract base class for pick UI backends.""" pass ``` -------------------------------- ### BlessedBackend Constructor Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/blessed-backend.md Initializes the BlessedBackend. It requires the 'blessed' package to be installed and will raise an ImportError if it's not found. ```APIDOC ## BlessedBackend() ### Description Initializes the BlessedBackend. Raises an `ImportError` if the `blessed` package is not installed. ### Method __init__ ### Parameters None ### Exceptions - `ImportError`: Raised if the `blessed` package is not installed. ``` -------------------------------- ### Multiselect Example Source: https://github.com/aisk/pick/blob/master/README.md Shows how to enable multiselect functionality, allowing users to choose multiple options using the SPACE key. A minimum selection count can be enforced. ```python from pick import pick title = 'Please choose your favorite programming language (press SPACE to mark, ENTER to continue): ' options = ['Java', 'JavaScript', 'Python', 'PHP', 'C++', 'Erlang', 'Haskell'] selected = pick(options, title, multiselect=True, min_selection_count=1) print(selected) ``` -------------------------------- ### BlessedBackend Constructor Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/blessed-backend.md Initializes the BlessedBackend. Raises ImportError if the 'blessed' package is not installed. ```python def __init__(self) -> None: pass ``` -------------------------------- ### Basic Pick with Blessed Backend Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/blessed-backend.md Use this snippet for a simple selection from a list using the Blessed backend. Ensure 'pick' is installed. ```python from pick import pick options = ["Option 1", "Option 2", "Option 3"] result = pick(options, backend="blessed") ``` -------------------------------- ### Refresh Display Example Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/backend.md Example of calling the refresh method to make changes visible after drawing operations. ```python backend.refresh() ``` -------------------------------- ### Basic Selection Example Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/pick-function.md Demonstrates a simple use case of the pick() function to select a single item from a list of strings. ```APIDOC ## Basic Selection ```python from pick import pick languages = ["Python", "JavaScript", "Rust", "Go"] choice, index = pick(languages, "Choose a language:") print(f"Selected: {choice}") ``` ``` -------------------------------- ### Using Blessed Backend for Picker Source: https://github.com/aisk/pick/blob/master/_autodocs/configuration.md Configure the Picker to use the 'blessed' backend for enhanced terminal rendering. Ensure 'pick[blessed]' is installed. ```python from pick import pick options = ["Option 1", "Option 2", "Option 3"] # Requires: pip install pick[blessed] result = pick( options, backend="blessed", title="Choose an option" ) ``` -------------------------------- ### Quit Keys Example Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/pick-function.md Shows how to define specific key codes that will trigger an early exit from the selection process. ```APIDOC ## With Quit Keys ```python from pick import pick KEY_ESCAPE = 27 KEY_CTRL_C = 3 options = ["Option 1", "Option 2", "Option 3"] result = pick( options, quit_keys=(KEY_ESCAPE, KEY_CTRL_C) ) if result == (None, -1): print("Cancelled") else: option, index = result print(f"Selected: {option}") ``` ``` -------------------------------- ### Blessed Backend Installation Error Handling Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/blessed-backend.md Handles ImportError if the 'blessed' library is not installed, providing instructions for installation. This snippet demonstrates how to gracefully manage the absence of the optional dependency. ```python from pick import BlessedBackend try: backend = BlessedBackend() except ImportError as e: print(e) # Output: blessed is required for BlessedBackend. # Install with: pip install pick[blessed] ``` -------------------------------- ### Use Valid Backend Names with Picker Source: https://github.com/aisk/pick/blob/master/_autodocs/errors.md Shows examples of correctly initializing a Picker with valid backend names ('curses', 'blessed') or a custom Backend instance, contrasting with an invalid name that would raise a ValueError. ```python from pick import Picker # Invalid backend name raises ValueError # picker = Picker(["A", "B"], backend="invalid") # Valid options picker = Picker(["A", "B"], backend="curses") # ✓ Correct picker = Picker(["A", "B"], backend="blessed") # ✓ Correct picker = Picker(["A", "B"], backend=MyBackend()) # ✓ Correct ``` -------------------------------- ### Custom Blessed Backend Instance Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/blessed-backend.md Create and pass a custom BlessedBackend instance to the Picker for fine-grained control. Requires 'blessed' to be installed. ```python from pick import Picker from pick.blessed_backend import BlessedBackend try: backend = BlessedBackend() picker = Picker(["A", "B"], backend=backend) result = picker.start() except ImportError: print("blessed is not installed. Install with: pip install pick[blessed]") ``` -------------------------------- ### Import ASCII Codes for Regular Keys Source: https://github.com/aisk/pick/blob/master/_autodocs/types.md Shows how to get ASCII codes for regular keys like Space, Newline, Carriage Return, and specific letters. ```python ord(' ') # 32 - Space bar ord('\n') # 10 - Newline (alternative Enter) ord('\r') # 13 - Carriage return (alternative Enter) ord('k') # 107 - Letter K (vim-style up) ord('j') # 106 - Letter J (vim-style down) ``` -------------------------------- ### Custom Indicator Example Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/pick-function.md Shows how to customize the indicator character used for selections in the pick() function. ```APIDOC ## With Custom Indicator ```python from pick import pick options = ["Red", "Green", "Blue"] color, idx = pick(options, title="Pick a color", indicator="=>") print(f"You picked {color}") ``` ``` -------------------------------- ### Start Picker with Curses Backend Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/picker.md Launches the picker within an embedded curses context, allowing for custom screen handling and positioning. Useful for integrating the picker into larger curses applications. ```python import curses from pick import Picker def main(stdscr): options = ["Option A", "Option B", "Option C"] picker = Picker( options, screen=stdscr, clear_screen=False, position=Picker.Position(y=5, x=0) ) result = picker.start() return result curses.wrapper(main) ``` -------------------------------- ### BlessedBackend Teardown Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/blessed-backend.md Cleans up the blessed backend, exiting fullscreen, disabling cbreak mode, and showing the cursor. Safe to call even if setup() was not invoked. ```python def teardown(self) -> None: pass ``` -------------------------------- ### Embedded in Curses Application Example Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/pick-function.md Demonstrates how to embed the pick() function within an existing curses application, controlling its position and screen clearing. ```APIDOC ## Embedded in Curses Application ```python import curses from pick import pick, Position def main(stdscr): stdscr.addstr("Menu:\n") options = ["Choice 1", "Choice 2", "Choice 3"] choice, idx = pick( options, title="Select:", screen=stdscr, clear_screen=False, position=Position(y=2, x=0) ) stdscr.addstr(f"\nYou chose: {choice}\n") stdscr.refresh() stdscr.getch() curses.wrapper(main) ``` ``` -------------------------------- ### Type Hints for IDE Autocompletion Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/module-exports.md Illustrates how type hints are used for classes and functions in the 'pick' module to enable IDE autocompletion. Shows examples for Picker with string options and Picker with Option objects. ```python from pick import Picker, Option # IDE knows return type is (str, int) picker: Picker[str] = Picker(["A", "B"]) result: tuple[str, int] = picker.start() # IDE knows return type is Option picker: Picker[Option] = Picker([Option("A")]) result_opt: tuple[Option, int] = picker.start() ``` -------------------------------- ### BlessedBackend.teardown() Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/blessed-backend.md Cleans up the blessed backend, restoring the terminal to its previous state by exiting fullscreen mode, disabling cbreak, and showing the cursor. This method is safe to call even if `setup()` was not invoked. ```APIDOC ## teardown() ### Description Cleans up the blessed backend and restores the terminal to its original state. This involves exiting fullscreen mode, disabling cbreak mode, and showing the cursor. It is safe to call this method at any time, even if `setup()` was not previously called. ### Method teardown ### Parameters None ### Returns None ``` -------------------------------- ### Large Option List with Default Selection Source: https://github.com/aisk/pick/blob/master/_autodocs/configuration.md Configure the picker to start with a specific option pre-selected using `default_index`. A custom indicator is also applied. ```python from pick import pick languages = [ "Python", "JavaScript", "TypeScript", "Rust", "Go", "Java", "C++", "C#", "Ruby", "PHP", "Swift", "Kotlin", "Scala", "Haskell", "Clojure", "Erlang", "Elixir" ] # Start with JavaScript selected (index 1) result = pick( languages, title="Choose a language:", default_index=1, indicator="→" ) ``` -------------------------------- ### Typed Picker Usage Example Source: https://github.com/aisk/pick/blob/master/_autodocs/types.md Demonstrates type-safe instantiation of the `Picker` class with strings. Shows a type error when attempting to use `Option` objects with a `Picker` expecting strings. ```python # Typed correctly picker: Picker[str] = Picker(["A", "B"]) result: str # Type checker knows result is a string # Type error - picker expects strings not Options picker: Picker[str] = Picker([Option("A")]) # ❌ Type error ``` -------------------------------- ### BlessedBackend.setup() Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/blessed-backend.md Initializes the blessed backend by entering fullscreen mode, enabling cbreak mode, and hiding the cursor. All configurations are managed via context managers for automatic cleanup. ```APIDOC ## setup() ### Description Initializes the blessed backend for rendering. This method configures the terminal by entering fullscreen mode, enabling cbreak mode, and hiding the cursor. All changes are managed using context managers for automatic cleanup in `teardown()`. ### Method setup ### Parameters None ### Returns None ``` -------------------------------- ### Type-Safe Single-Select Picker Source: https://github.com/aisk/pick/blob/master/_autodocs/README.md Demonstrates the usage of a type-safe single-select picker with string options. The picker is initialized with a list of strings and started to get a result. ```python # Type-safe single-select picker: Picker[str] = Picker(["A", "B"]) result: tuple[str, int] = picker.start() ``` -------------------------------- ### Using CursesBackend Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/backend.md Demonstrates the basic usage of the CursesBackend for terminal output and input. Ensure the curses module is available on your system. ```python from pick import CursesBackend backend = CursesBackend() backend.setup() try: height, width = backend.getmaxyx() backend.addnstr(0, 0, "Hello", width - 2) backend.refresh() key = backend.getch() finally: backend.teardown() ``` -------------------------------- ### Initialize Picker with Default Values Source: https://github.com/aisk/pick/blob/master/_autodocs/configuration.md Demonstrates initializing the Picker class with all default parameters. The 'options' parameter is the only required one. ```python from pick import Picker, Position # All defaults picker = Picker( options=options, # Only required parameter title=None, indicator="*", default_index=0, multiselect=False, min_selection_count=0, screen=None, position=Position(0, 0), clear_screen=True, quit_keys=None, backend="curses" ) ``` -------------------------------- ### Creating a Custom Backend Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/backend.md Illustrates how to create a custom backend by inheriting from the base Backend class and implementing its abstract methods. This allows for custom terminal interaction logic. ```python from pick import Backend class MyBackend(Backend): def __init__(self): self.buffer = [] def setup(self) -> None: print("Initializing my backend...") def teardown(self) -> None: print("Cleaning up...") def clear(self) -> None: self.buffer.clear() def getmaxyx(self) -> tuple[int, int]: return (24, 80) # Default terminal size def addnstr(self, y: int, x: int, s: str, n: int) -> None: self.buffer.append((y, x, s[:n])) def getch(self) -> int: return ord(input("Key: ")) def refresh(self) -> None: for y, x, s in self.buffer: print(f"[{y},{x}] {s}") ``` ```python from pick import Picker picker = Picker(["Option 1", "Option 2"], backend=MyBackend()) result = picker.start() ``` -------------------------------- ### Using BlessedBackend Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/backend.md Shows how to use the BlessedBackend, an alternative implementation requiring the 'blessed' library. This backend provides similar functionality to CursesBackend. ```python from pick import BlessedBackend backend = BlessedBackend() # Raises ImportError if blessed not installed backend.setup() try: # Use like CursesBackend key = backend.getch() finally: backend.teardown() ``` -------------------------------- ### BlessedBackend Get Terminal Dimensions Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/blessed-backend.md Retrieves the current terminal dimensions (height and width) using the blessed Terminal object. ```python def getmaxyx(self) -> Tuple[int, int]: pass ``` -------------------------------- ### Basic Option with Value Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/option.md Demonstrates creating a list of Option objects, each with a label and a distinct value, and then using them with the pick function. Shows how to access the label and value of the selected option. ```python from pick import pick, Option options = [ Option("Python", value="py"), Option("JavaScript", value="js"), Option("Rust", value="rs") ] choice, index = pick(options) print(f"Label: {choice.label}, Value: {choice.value}") # Output: Label: Python, Value: py ``` -------------------------------- ### Picker Initialization with Custom Backend Instance Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/backend.md Initialize the Picker with a custom backend instance. Your custom backend must inherit from the base backend class. ```python from pick import Picker from myapp import MyCustomBackend picker = Picker(options, backend=MyCustomBackend()) ``` -------------------------------- ### Get Formatted Option Lines Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/picker.md Formats all options for display, including selection indicators and symbols. Useful for custom rendering or debugging. ```python picker = Picker(["Option 1", "Option 2"], indicator="=>") lines = picker.get_option_lines() # Returns: ["=> Option 1", " Option 2"] ``` -------------------------------- ### Example Usage of Multiselect Symbols Source: https://github.com/aisk/pick/blob/master/_autodocs/types.md Illustrates how the SYMBOL_CIRCLE_FILLED and SYMBOL_CIRCLE_EMPTY constants are used to show selected and unselected states in multiselect mode. ```python from pick import SYMBOL_CIRCLE_FILLED, SYMBOL_CIRCLE_EMPTY # When multiselect=True and item is selected: "(x)" # When multiselect=True and item is not selected: "( )" ``` -------------------------------- ### pick() Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/module-exports.md Creates a `Picker` instance and runs the selection interface. It supports both single and multi-select modes and returns the selected option(s) and their indices, or `None`/`[]` if the user quits. ```APIDOC ## pick() ### Description Creates a `Picker` and runs it. Supports single and multi-select modes. ### Method `pick` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (Sequence[OPTION_T]) - Required - The list of options to choose from. - **title** (Optional[str]) - Optional - A title to display above the options. - **indicator** (str) - Optional - The character used to indicate selection (default: "*"). - **default_index** (int) - Optional - The index of the initially selected option (default: 0). - **multiselect** (bool) - Optional - Whether to enable multi-select mode (default: False). - **min_selection_count** (int) - Optional - The minimum number of selections required in multi-select mode (default: 0). - **screen** (Optional[curses.window]) - Optional - A curses window object for rendering. - **position** (Position) - Optional - The starting position (y, x) for the picker (default: Position(0, 0)). - **clear_screen** (bool) - Optional - Whether to clear the screen before rendering (default: True). - **quit_keys** (Optional[Union[Container[int], Iterable[int]]]) - Optional - Keys that will quit the picker. - **backend** (Union[str, Backend]) - Optional - The rendering backend to use (default: "curses"). ### Returns - Single-select: `(option, index)` or `(None, -1)` if quit. - Multiselect: `[(option, index), ...]` or `[]` if quit. ### Example ```python from pick import pick options = ["A", "B", "C"] selected_option, index = pick(options, title="Select an option") print(f"Selected: {selected_option} at index {index}") ``` ``` -------------------------------- ### Using ord() for Regular Characters Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/curses-backend.md Illustrates how to use the built-in ord() function to get the integer Unicode code point for regular characters, such as 'a' or a space. ```python ord('a') # 97 ord(' ') # 32 ``` -------------------------------- ### Basic Selection with pick() Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/pick-function.md Demonstrates the most basic usage of the `pick` function to select a single item from a list of strings. Ensure `pick` is imported. ```python from pick import pick languages = ["Python", "JavaScript", "Rust", "Go"] choice, index = pick(languages, "Choose a language:") print(f"Selected: {choice}") ``` -------------------------------- ### Backend Implementations Source: https://github.com/aisk/pick/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Details on different backend implementations for rendering the picker, including Curses, Blessed, and custom options. ```APIDOC ## Backends: Backend, CursesBackend, BlessedBackend ### Description Defines the interface for rendering the picker and provides default implementations. ### Abstract Base Class #### `Backend` ##### Description Abstract base class for all backend implementations. ##### Methods - **`display(options, selection, index, cursor)`**: Abstract method to display options. - **`process_input(key)`**: Abstract method to process user input. - **`clear()`**: Abstract method to clear the screen. - **`move(row, col)`**: Abstract method to move the cursor. ### Concrete Backends #### `CursesBackend` ##### Description Default backend implementation using the curses library. ##### Initialization - **`CursesBackend()`**: Initializes the curses backend. ##### Methods - Implements all abstract methods from `Backend`. #### `BlessedBackend` ##### Description Optional backend implementation using the blessed library. ##### Initialization - **`BlessedBackend()`**: Initializes the blessed backend. ##### Methods - Implements all abstract methods from `Backend`. ### Custom Implementation Guide Refer to `src/pick/backend.py` for the abstract interface and `src/pick/curses_backend.py` and `src/pick/blessed_backend.py` for examples. ### Terminal Integration - Embedded in curses apps - Position control - Clear screen control - Quit key handling ``` -------------------------------- ### Proper Initialization of CursesBackend Source: https://github.com/aisk/pick/blob/master/_autodocs/errors.md Ensures `_screen` is set before calling methods on `CursesBackend` to prevent `AssertionError`. ```python import curses from pick.curses_backend import CursesBackend def use_backend_directly(stdscr): backend = CursesBackend(screen=stdscr) # After this, _screen is set backend.setup() # Safe to call methods backend.getch() curses.wrapper(use_backend_directly) ``` -------------------------------- ### Get Selected Options Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/picker.md Retrieves the currently selected option(s). For single-select pickers, it returns a tuple of the option and its index. For multiselect pickers, it returns a list of such tuples. ```python picker = Picker(["A", "B", "C"], multiselect=True) picker.mark_index() picker.move_down() picker.mark_index() selected = picker.get_selected() # [("A", 0), ("B", 1)] ``` -------------------------------- ### CursesBackend Constructor Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/curses-backend.md Initializes the CursesBackend. It can optionally take an existing curses window object. ```APIDOC ## Constructor CursesBackend ### Description Initializes the CursesBackend. It can optionally take an existing curses window object. ### Parameters #### Parameters - **screen** (Optional[curses.window]) - Optional - None - Existing curses window object. If `None`, one is provided by `curses.wrapper()`. ``` -------------------------------- ### Valid Picker Configurations Source: https://github.com/aisk/pick/blob/master/_autodocs/errors.md Demonstrates several valid configurations for the Picker that should not raise any exceptions during initialization. This includes basic option lists, setting a default index, using enabled/disabled options, and configuring multiselect with a minimum count. ```python from pick import Picker, Option # These should all succeed Picker(["A", "B", "C"]) Picker(["A"], default_index=0) Picker([Option("A", enabled=True), Option("B", enabled=False)]) Picker(["A", "B", "C"], multiselect=True, min_selection_count=1) ``` -------------------------------- ### Custom Quit Keys for Selection Source: https://github.com/aisk/pick/blob/master/_autodocs/configuration.md Define custom key bindings to quit the selection process. This example uses ESC, CTRL+C, and 'q' as quit keys. ```python import curses from pick import pick KEY_ESCAPE = 27 KEY_CTRL_C = 3 options = ["Option A", "Option B", "Option C"] result = pick( options, quit_keys=(KEY_ESCAPE, KEY_CTRL_C, ord('q')), title="Press ESC, CTRL+C, or Q to quit" ) if result == (None, -1): print("User quit the selection") else: print(f"Selected: {result[0]}") ``` -------------------------------- ### Pick with Option Descriptions Source: https://github.com/aisk/pick/blob/master/_autodocs/index.md Allows displaying descriptions alongside options for better user guidance. Requires using the `Option` class. ```python from pick import pick, Option options = [ Option("Python", description="General-purpose programming language"), Option("JavaScript", description="For web development"), ] result = pick(options) ``` -------------------------------- ### Multi-selection with pick() Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/pick-function.md Illustrates how to enable multi-selection using `multiselect=True` and set a minimum number of selections with `min_selection_count`. The return value is a list of selections. ```python from pick import pick langs = ["Python", "JavaScript", "Rust", "Go", "Java"] selected = pick( langs, title="Choose 2-3 languages:", multiselect=True, min_selection_count=2 ) print(f"Selected: {selected}") ``` -------------------------------- ### Basic Picker Initialization Source: https://github.com/aisk/pick/blob/master/_autodocs/configuration.md Initialize a Picker with a list of options, a title, and a custom indicator. This is for single selection. ```python from pick import Picker picker = Picker( options=["Python", "JavaScript", "Rust"], title="Choose your language:", indicator=">" ) result = picker.start() ``` -------------------------------- ### Fallback to Curses Backend on ImportError Source: https://github.com/aisk/pick/blob/master/_autodocs/errors.md Illustrates a fallback pattern where the code attempts to use the 'blessed' backend but defaults to the 'curses' backend if an ImportError occurs due to 'blessed' not being installed. ```python from pick import pick try: backend = "blessed" except ImportError: backend = "curses" # Fallback to default result = pick(["A", "B"], backend=backend) ``` -------------------------------- ### Multi-selection with Constraints Source: https://github.com/aisk/pick/blob/master/_autodocs/index.md Shows how to configure the pick library for multi-selection, allowing users to choose a specific number of items. It returns a list of selected items and their indices. ```python from pick import pick options = ["Python", "JavaScript", "Rust", "Go"] selected = pick( options, title="Choose 2-3 languages:", multiselect=True, min_selection_count=2 ) for option, index in selected: print(f"Selected {option} at index {index}") ``` -------------------------------- ### Blessed Backend Implementation Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/module-exports.md A concrete backend implementation utilizing the 'blessed' library for terminal control. This backend raises an ImportError if 'blessed' is not installed and manages terminal contexts using an ExitStack. ```python class BlessedBackend(Backend): """Backend that uses the blessed library (optional dependency).""" def __init__(self) -> None: """Initialize the BlessedBackend. Raises: ImportError: If the 'blessed' library is not installed. """ self._term: blessed.Terminal self._ctx: Optional[contextlib.ExitStack] ``` -------------------------------- ### Pick with Custom Backend Source: https://github.com/aisk/pick/blob/master/_autodocs/index.md Allows using a custom backend implementation for the picker. Requires subclassing `pick.backend.Backend` and implementing abstract methods. ```python from pick import Picker from pick.backend import Backend class MyBackend(Backend): # Implement abstract methods ... picker = Picker(options, backend=MyBackend()) result = picker.start() ``` -------------------------------- ### getch() Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/curses-backend.md Reads a single key press from the user. Blocks until a key is pressed. Asserts that the screen object is initialized. ```APIDOC ## getch() -> int ### Description Read a single key press. **Returns:** Key code (curses constants or ASCII values) **Assertion:** `self._screen` must not be `None` Blocks until a key is pressed. ### Method `getch()` ``` -------------------------------- ### BlessedBackend Get Key Press Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/blessed-backend.md Reads a single key press from the user, blocking until a key is detected. Maps blessed key sequences to curses constants or returns ASCII values for regular characters. ```python def getch(self) -> int: pass ``` -------------------------------- ### CursesBackend Constructor Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/curses-backend.md Initializes the CursesBackend. Accepts an optional curses window object; otherwise, one is provided by curses.wrapper(). ```python def __init__(self, screen: Optional[curses.window] = None) -> None: ``` -------------------------------- ### Type Hinting Picker with Strings Source: https://github.com/aisk/pick/blob/master/_autodocs/index.md Demonstrates how to use type hints for the Picker class when dealing with string options. This enables IDE autocompletion and static type checking. ```python from pick import Picker # Typed for strings picker: Picker[str] = Picker(["A", "B"]) ``` -------------------------------- ### Options with Descriptions Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/option.md Illustrates how to use the 'description' field within Option objects to provide additional context for each menu item. These descriptions are displayed alongside the options in the picker interface. ```python from pick import pick, Option options = [ Option( "Python", description="High-level, general-purpose language with simple syntax" ), Option( "JavaScript", description="Event-driven language designed for web browsers" ), Option( "Rust", description="Systems language focused on memory safety without garbage collection" ) ] selected, _ = pick(options, title="Choose a language:") ``` -------------------------------- ### Equivalent Imports in Pick Module Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/module-exports.md Demonstrates equivalent import statements, showing that public symbols from submodules are re-exported in the main 'pick' module. Use the main module for canonical imports. ```python from pick import Backend from pick.backend import Backend from pick import CursesBackend from pick.curses_backend import CursesBackend from pick import BlessedBackend from pick.blessed_backend import BlessedBackend ``` -------------------------------- ### Pick with Picker Class and Blessed Backend Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/blessed-backend.md Instantiate the Picker class directly for more control, specifying the Blessed backend. This is useful for custom configurations. ```python from pick import Picker options = ["Python", "JavaScript", "Rust"] picker = Picker(options, backend="blessed") result = picker.start() ``` -------------------------------- ### Minimal Import of pick Function Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/module-exports.md Use this for a quick import of the main 'pick' function when only its basic functionality is needed. ```python from pick import pick # Now available: pick() function result = pick(options) ``` -------------------------------- ### Utilities and Types Source: https://github.com/aisk/pick/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Documentation for utility functions, type aliases, and constants used within the Pick library. ```APIDOC ## Utilities: Position, type aliases, constants ### Description Provides helper types and constants for internal use and advanced configuration. ### Type Aliases #### `Position` ##### Description Represents a (row, column) coordinate pair. ##### Type - **tuple[int, int]** ### Constants - **`DEFAULT_QUIT_KEYS`**: A set of default keys that will quit the picker. - **`DEFAULT_INDICATOR`**: The default indicator for selected options. ### Source File References - `src/pick/__init__.py` - `src/pick/backend.py` - `src/pick/curses_backend.py` - `src/pick/blessed_backend.py` ``` -------------------------------- ### Type Hinting Picker with Option Objects Source: https://github.com/aisk/pick/blob/master/_autodocs/index.md Illustrates how to use type hints for the Picker class when options are represented by Option objects. This enhances IDE support and static analysis. ```python from pick import Option picker: Picker[Option] = Picker([Option("A")]) ``` -------------------------------- ### Picker Constructor Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/picker.md Initializes a new Picker instance to manage an interactive selection menu. Supports various configurations for display, selection behavior, and rendering. ```APIDOC ## Picker Constructor ### Description Initializes a new Picker instance to manage an interactive selection menu. Supports various configurations for display, selection behavior, and rendering. ### Signature ```python Picker( options: Sequence[OPTION_T], title: Optional[str] = None, indicator: str = "*", default_index: int = 0, multiselect: bool = False, min_selection_count: int = 0, screen: Optional[curses.window] = None, position: Position = Position(0, 0), clear_screen: bool = True, quit_keys: Optional[Union[Container[int], Iterable[int]]] = None, backend: Union[str, Backend] = "curses" ) ``` ### Parameters #### Positional Parameters - **options** (Sequence[OPTION_T]) - Required - List of options to select from. Can be strings or `Option` objects. #### Optional Parameters - **title** (Optional[str]) - Optional - Display title shown above the options list. Supports newlines and auto-wrapping. - **indicator** (str) - Optional - Character(s) to display next to the current selection. Defaults to "*". - **default_index** (int) - Optional - Initial selected option index (0-based). Defaults to `0`. - **multiselect** (bool) - Optional - If `True`, allow selecting multiple options with SPACE key. Defaults to `False`. - **min_selection_count** (int) - Optional - Minimum items that must be selected before allowing confirmation in multiselect mode. Defaults to `0`. - **screen** (Optional[curses.window]) - Optional - Existing curses window for embedding in a running curses application. Defaults to `None`. - **position** (Position) - Optional - Starting position for rendering (y, x coordinates). Defaults to `Position(0, 0)`. - **clear_screen** (bool) - Optional - Clear the screen before drawing. Set to `False` when embedded in an existing curses app. Defaults to `True`. - **quit_keys** (Optional[Union[Container[int], Iterable[int]]]) - Optional - Key codes that trigger early exit. Returns `(None, -1)` for single-select or empty list for multiselect. Defaults to `None`. - **backend** (Union[str, Backend]) - Optional - Rendering backend: `"curses"` or `"blessed"`, or a custom `Backend` instance. Defaults to `"curses"`. ### Exceptions - **ValueError**: `options` is empty - **ValueError**: `default_index` >= length of options - **ValueError**: `multiselect=True` and `min_selection_count` > length of options - **ValueError**: All options have `enabled=False` ``` -------------------------------- ### Full API Import from pick Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/module-exports.md Import all available components from the 'pick' library at once. This is useful when you need access to multiple classes, functions, and constants. ```python from pick import ( Picker, # Class pick, # Function Option, # Class Position, # Named tuple Backend, # ABC CursesBackend, # Class BlessedBackend, # Class SYMBOL_CIRCLE_FILLED, SYMBOL_CIRCLE_EMPTY, ) ``` -------------------------------- ### Mixed String and Option Lists Source: https://github.com/aisk/pick/blob/master/_autodocs/api-reference/option.md Illustrates creating a Picker with a list containing both simple strings and Option objects. Note that this mixed usage is not type-safe and is generally not recommended. ```python from pick import Picker mixed_options = [ "Simple String", Option("Structured Option", value="struct_val") ] picker = Picker(mixed_options) # type: ignore (mixing not type-safe) ``` -------------------------------- ### Basic Selection with pick() Source: https://github.com/aisk/pick/blob/master/_autodocs/README.md Use this for simple interactive selection from a list of options. It returns the selected option and its index, or (None, -1) if the user quits. ```python from pick import pick options = ["A", "B", "C"] result = pick(options) # (option, index) or (None, -1) if quit ``` -------------------------------- ### Pick Module Structure Source: https://github.com/aisk/pick/blob/master/_autodocs/index.md Provides a visual representation of the pick library's directory and file structure. This helps understand the organization of different components. ```text pick/ ├── __init__.py # Picker, pick(), Option, Position, symbols ├── backend.py # Backend ABC ├── curses_backend.py # CursesBackend implementation └── blessed_backend.py # BlessedBackend implementation ```