-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.py
More file actions
57 lines (47 loc) · 2.31 KB
/
Copy pathdata.py
File metadata and controls
57 lines (47 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
from typing import Callable, Any
from colored import colored_input, error_message
def check_input_for_number(value:str) -> float|int|None:
"""
Check if the input of the user is either an integer or a float value
and returning it as the representing type
if its not a integer or a float value it will return None
Returns:
int | float: the converted value in the representing type if valid
None: in any case of the input not being a integer or float value
"""
if "." in value:
possible_float_value = value.replace(".", "")
if possible_float_value.isdigit():
return float(value)
if value.isdigit():
return int(value)
return None
def request_data_from_user(prompt:str, error_case:Callable, validation_func:Callable) -> Any:
"""
Request a user to input some value by using the input function with the given prompt
then validate it with the given Callable validation_func and return its return value
if its not None
If its none call the Callable error_case with the user input as argument and restart
Args:
prompt(str): the prompt that will be shown to the user
error_case(Callable): this will be called with the invalid input
if the validation_func returns None
validation_func(Callable): this will be called to check the input
return None to set it as invalid
Returns:
(Any): the return is guarantied to be valid as long as the validation function is correct
Exceptions:
TypeError: if you pass a not callable object to error_case or validation_func
"""
if not callable(error_cass):
raise TypeError(f"while requesting prompt '{prompt}' an invalid capable was given: error_case: {error_case}")
if not callable(validation_func):
raise TypeError(f"while requesting prompt '{prompt}' an invalid capable was given: validation_func: {validation_func}")
check_result = None
while check_result is None:
user_input = colored_input(prompt)
check_result = validation_func(user_input)
if check_result is None:
error_message(error_case(user_input))
continue
return check_result