Skip to content

ui.ui_helper

DefaultUIHelper

DefaultUIHelper(
    *args,
    print_func: Optional[_PrintFunc] = None,
    input_func: Optional[_PrintFunc] = None,
    **kwargs,
)

Bases: _UiHelperBase

Default implementation of the UI helper for user interaction.

This class provides a concrete implementation of the UI helper interface using standard console input/output for user interactions.

Example
helper = DefaultUIHelper()

# Get user choice from list
options = ["Option A", "Option B", "Option C"]
choice = helper.prompt_pick_from_list(options, "Choose an option:")

# Ask yes/no question
proceed = helper.prompt_yes_no_question("Continue with operation?")

# Get text input
name = helper.prompt_text("Enter your name: ")

# Get numeric input
value = helper.prompt_float("Enter a number: ")

Initializes the UI helper with optional custom print and input functions.

Parameters:

Name Type Description Default
print_func Optional[_PrintFunc]

Custom function for printing messages

None
input_func Optional[_PrintFunc]

Custom function for receiving input

None
Example
# Default UI helper
helper = DefaultUIHelper()

# Custom print/input functions
def custom_print(msg):
    logging.info(f"UI: {msg}")

def custom_input(prompt):
    return input(f"[CUSTOM] {prompt}")

helper = DefaultUIHelper(
    print_func=custom_print,
    input_func=custom_input
)
Source code in src/clabe/ui/ui_helper.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def __init__(
    self, *args, print_func: Optional[_PrintFunc] = None, input_func: Optional[_PrintFunc] = None, **kwargs
):
    """
    Initializes the UI helper with optional custom print and input functions.

    Args:
        print_func: Custom function for printing messages
        input_func: Custom function for receiving input

    Example:
        ```python
        # Default UI helper
        helper = DefaultUIHelper()

        # Custom print/input functions
        def custom_print(msg):
            logging.info(f"UI: {msg}")

        def custom_input(prompt):
            return input(f"[CUSTOM] {prompt}")

        helper = DefaultUIHelper(
            print_func=custom_print,
            input_func=custom_input
        )
        ```
    """
    self._print = print_func if print_func is not None else _DEFAULT_PRINT_FUNC
    self._input = input_func if input_func is not None else _DEFAULT_INPUT_FUNC

prompt_pick_from_list

prompt_pick_from_list(
    value: List[str],
    prompt: str,
    allow_0_as_none: bool = True,
    **kwargs,
) -> Optional[str]

Prompts the user to pick an item from a list.

Displays a numbered list of options and prompts the user to select one by entering the corresponding number.

Parameters:

Name Type Description Default
value List[str]

The list of items to choose from

required
prompt str

The prompt message

required
allow_0_as_none bool

Whether to allow 0 as a choice for None

True

Returns:

Type Description
Optional[str]

Optional[str]: The selected item or None

Example
helper = DefaultUIHelper()
files = ["file1.txt", "file2.txt", "file3.txt"]
selected = helper.prompt_pick_from_list(files, "Choose a file:")

# With None option disabled
selected = helper.prompt_pick_from_list(
    files, "Must choose a file:", allow_0_as_none=False
)
Source code in src/clabe/ui/ui_helper.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def prompt_pick_from_list(
    self, value: List[str], prompt: str, allow_0_as_none: bool = True, **kwargs
) -> Optional[str]:
    """
    Prompts the user to pick an item from a list.

    Displays a numbered list of options and prompts the user to select
    one by entering the corresponding number.

    Args:
        value: The list of items to choose from
        prompt: The prompt message
        allow_0_as_none: Whether to allow 0 as a choice for None

    Returns:
        Optional[str]: The selected item or None

    Example:
        ```python
        helper = DefaultUIHelper()
        files = ["file1.txt", "file2.txt", "file3.txt"]
        selected = helper.prompt_pick_from_list(files, "Choose a file:")

        # With None option disabled
        selected = helper.prompt_pick_from_list(
            files, "Must choose a file:", allow_0_as_none=False
        )
        ```
    """
    while True:
        try:
            self.print(prompt)
            if allow_0_as_none:
                self.print("0: None")
            for i, item in enumerate(value):
                self.print(f"{i + 1}: {item}")
            choice = int(input("Choice: "))
            if choice < 0 or choice >= len(value) + 1:
                raise ValueError
            if choice == 0:
                if allow_0_as_none:
                    return None
                else:
                    raise ValueError
            return value[choice - 1]
        except ValueError as e:
            logger.error("Invalid choice. Try again. %s", e)

prompt_yes_no_question

prompt_yes_no_question(prompt: str) -> bool

Prompts the user with a yes/no question.

Continues prompting until a valid yes/no response is received.

Parameters:

Name Type Description Default
prompt str

The question to ask

required

Returns:

Name Type Description
bool bool

True for yes, False for no

Example
helper = DefaultUIHelper()

if helper.prompt_yes_no_question("Save changes?"):
    save_data()

proceed = helper.prompt_yes_no_question("Delete all files?")
if proceed:
    delete_files()
Source code in src/clabe/ui/ui_helper.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
def prompt_yes_no_question(self, prompt: str) -> bool:
    """
    Prompts the user with a yes/no question.

    Continues prompting until a valid yes/no response is received.

    Args:
        prompt: The question to ask

    Returns:
        bool: True for yes, False for no

    Example:
        ```python
        helper = DefaultUIHelper()

        if helper.prompt_yes_no_question("Save changes?"):
            save_data()

        proceed = helper.prompt_yes_no_question("Delete all files?")
        if proceed:
            delete_files()
        ```
    """
    while True:
        reply = input(prompt + " (Y\\N): ").upper()
        if reply == "Y" or reply == "1":
            return True
        elif reply == "N" or reply == "0":
            return False
        else:
            self.print("Invalid input. Please enter 'Y' or 'N'.")

prompt_text

prompt_text(prompt: str) -> str

Prompts the user for text input.

Simple text input prompt that returns the user's input as a string.

Parameters:

Name Type Description Default
prompt str

The prompt message

required

Returns:

Name Type Description
str str

The user input

Example
helper = DefaultUIHelper()

name = helper.prompt_text("Enter your name: ")
description = helper.prompt_text("Enter description: ")
path = helper.prompt_text("Enter file path: ")
Source code in src/clabe/ui/ui_helper.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
def prompt_text(self, prompt: str) -> str:
    """
    Prompts the user for text input.

    Simple text input prompt that returns the user's input as a string.

    Args:
        prompt: The prompt message

    Returns:
        str: The user input

    Example:
        ```python
        helper = DefaultUIHelper()

        name = helper.prompt_text("Enter your name: ")
        description = helper.prompt_text("Enter description: ")
        path = helper.prompt_text("Enter file path: ")
        ```
    """
    notes = str(input(prompt))
    return notes

prompt_float

prompt_float(prompt: str) -> float

Prompts the user for a float input.

Continues prompting until a valid float value is entered.

Parameters:

Name Type Description Default
prompt str

The prompt message

required

Returns:

Name Type Description
float float

The parsed user input

Example
helper = DefaultUIHelper()

temperature = helper.prompt_float("Enter temperature: ")
weight = helper.prompt_float("Enter weight in kg: ")
price = helper.prompt_float("Enter price: $")
Source code in src/clabe/ui/ui_helper.py
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def prompt_float(self, prompt: str) -> float:
    """
    Prompts the user for a float input.

    Continues prompting until a valid float value is entered.

    Args:
        prompt: The prompt message

    Returns:
        float: The parsed user input

    Example:
        ```python
        helper = DefaultUIHelper()

        temperature = helper.prompt_float("Enter temperature: ")
        weight = helper.prompt_float("Enter weight in kg: ")
        price = helper.prompt_float("Enter price: $")
        ```
    """
    while True:
        try:
            value = float(input(prompt))
            return value
        except ValueError:
            self.print("Invalid input. Please enter a valid float.")

print

print(message: str) -> Any

Prints a message using the configured print function.

Parameters:

Name Type Description Default
message str

The message to print

required

Returns:

Name Type Description
Any Any

The result of the print function

Example
helper = DefaultUIHelper()
helper.print("Hello, world!")
helper.print("Status: Processing...")
Source code in src/clabe/ui/ui_helper.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def print(self, message: str) -> Any:
    """
    Prints a message using the configured print function.

    Args:
        message: The message to print

    Returns:
        Any: The result of the print function

    Example:
        ```python
        helper = DefaultUIHelper()
        helper.print("Hello, world!")
        helper.print("Status: Processing...")
        ```
    """
    return self._print(message)

input

input(prompt: str) -> str

Prompts the user for input using the configured input function.

Parameters:

Name Type Description Default
prompt str

The prompt message

required

Returns:

Name Type Description
str str

The user input

Example
helper = DefaultUIHelper()
name = helper.input("Enter your name: ")
password = helper.input("Enter password: ")
Source code in src/clabe/ui/ui_helper.py
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def input(self, prompt: str) -> str:
    """
    Prompts the user for input using the configured input function.

    Args:
        prompt: The prompt message

    Returns:
        str: The user input

    Example:
        ```python
        helper = DefaultUIHelper()
        name = helper.input("Enter your name: ")
        password = helper.input("Enter password: ")
        ```
    """
    return self._input(prompt)

prompt_field_from_input

prompt_field_from_input(
    model: Type[_TModel],
    field_name: str,
    default: Optional[_T] = None,
) -> Optional[_T]

Prompts the user to input a value for a specific field in a model.

Uses the model's field information to prompt for input and validates the entered value against the field's type annotation.

Parameters:

Name Type Description Default
model Type[_TModel]

The model containing the field

required
field_name str

The name of the field

required
default Optional[_T]

The default value if no input is provided

None

Returns:

Type Description
Optional[_T]

Optional[_T]: The validated input value or the default value

Example
from pydantic import BaseModel, Field

class UserModel(BaseModel):
    name: str = Field(description="User's full name")
    age: int = Field(description="User's age in years")

# Prompt for name field
name = prompt_field_from_input(UserModel, "name", "Anonymous")

# Prompt for age field
age = prompt_field_from_input(UserModel, "age", 18)
Source code in src/clabe/ui/ui_helper.py
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
def prompt_field_from_input(model: Type[_TModel], field_name: str, default: Optional[_T] = None) -> Optional[_T]:
    """
    Prompts the user to input a value for a specific field in a model.

    Uses the model's field information to prompt for input and validates the
    entered value against the field's type annotation.

    Args:
        model: The model containing the field
        field_name: The name of the field
        default: The default value if no input is provided

    Returns:
        Optional[_T]: The validated input value or the default value

    Example:
        ```python
        from pydantic import BaseModel, Field

        class UserModel(BaseModel):
            name: str = Field(description="User's full name")
            age: int = Field(description="User's age in years")

        # Prompt for name field
        name = prompt_field_from_input(UserModel, "name", "Anonymous")

        # Prompt for age field
        age = prompt_field_from_input(UserModel, "age", 18)
        ```
    """
    _field = model.model_fields[field_name]
    _type_adaptor: TypeAdapter = TypeAdapter(_field.annotation)
    value: Optional[_T] | str
    _in = input(f"Enter {field_name} ({_field.description}): ")
    value = _in if _in != "" else default
    return _type_adaptor.validate_python(value)