prototools package¶
Submodules¶
prototools.canvas module¶
- class prototools.canvas.Canvas(width=40, height=20, bg=None)¶
Bases:
object
Canvas Implementation for draw in terminal
- Atributes:
w (int): Width of the canvas. h (int): Height of the canvas. bg (str): Background of the canvas.
- Parameters
width (int) –
height (int) –
bg (Optional[str]) –
- Return type
None
- card(x, y, w, h, rounded=False)¶
- Parameters
x (int) –
y (int) –
w (int) –
h (int) –
rounded (bool) –
- Return type
None
- clear_canvas()¶
- Return type
None
- draw_figure(figure, char='*')¶
Draws a figure.
- Parameters
figure (object) – A figure.
char (str) –
- Return type
None
- listcard(x, y, list_, rounded=False)¶
- Parameters
x (int) –
y (int) –
list_ (List[str]) –
rounded (bool) –
- Return type
None
- set_defaults(rounded=False)¶
- Parameters
rounded (bool) –
- Return type
None
- set_dimensions(width, height, space=None)¶
- Parameters
width (int) –
height (int) –
space (Optional[int]) –
- Return type
None
- show()¶
- Return type
None
- textcard(x, y, text, rounded=False)¶
Draws a card with text inside.
- Parameters
x (int) – x coordinate of the card.
y (int) – y coordinate of the card.
text (str) – Text to be written inside the card.
rounded (bool, optional) – If True, draws a rounded card. Defaults to False.
- Return type
None
Example
>>> c = Canvas() >>> c.textcard(1, 1, "Prototools", rounded=True) >>> c.show() ╭─────────────╮ │ Prototools │ ╰─────────────╯
- umlcard(x, y, name, attributes, methods, rounded=False)¶
Draws a UML card.
- Parameters
x (int) – The x coordinate of the top left corner of the card.
y (int) – The y coordinate of the top left corner of the card.
name (str) – The name of the class.
attributes (List[str]) – A list of attributes.
methods (List[str]) – A list of methods.
rounded (Optional[bool]) – Whether to draw a rounded card.
- Return type
None
Example
>>> c = Canvas() >>> c.umlcard(0, 0, "Person", ["name"], ["walk", "run"]) >>> c.show() ┌─────────┐ │ Person │ ├─────────┤ │ name │ ├─────────┤ │ walk │ │ run │ └─────────┘
- write_at(x, y, text)¶
- Parameters
x (int) –
y (int) –
text (str) –
- Return type
None
- class prototools.canvas.Circle(x: int, y: int, color: Callable, r: int)¶
Bases:
prototools.canvas.FigureDataclass
- Parameters
x (int) –
y (int) –
color (Callable) –
r (int) –
- Return type
None
- get_pos()¶
- Return type
List[Tuple[int, int]]
- r: int¶
- class prototools.canvas.Figure(x, y, color=None)¶
Bases:
object
- Parameters
x (int) –
y (int) –
color (Optional[Callable]) –
- Return type
None
- change_color(color)¶
- Parameters
color (Callable) –
- Return type
None
- get_pos()¶
- Return type
List[Tuple[int, int]]
- move(dx, dy)¶
- Parameters
dx (int) –
dy (int) –
- Return type
None
- class prototools.canvas.FigureDataclass(x: int, y: int, color: Callable)¶
Bases:
object
- Parameters
x (int) –
y (int) –
color (Callable) –
- Return type
None
- change_color(color)¶
- Parameters
color (Callable) –
- Return type
None
- color: Callable¶
- get_pos()¶
- Return type
List[Tuple[int, int]]
- move(dx, dy)¶
- Parameters
dx (int) –
dy (int) –
- Return type
None
- x: int¶
- y: int¶
- class prototools.canvas.Rectangle(x: int, y: int, color: Callable, width: int, height: int)¶
Bases:
prototools.canvas.FigureDataclass
- Parameters
x (int) –
y (int) –
color (Callable) –
width (int) –
height (int) –
- Return type
None
- get_pos()¶
- Return type
List[Tuple[int, int]]
- height: int¶
- width: int¶
- class prototools.canvas.ScreenCanvas¶
Bases:
object
- Return type
None
- add_figures(figures)¶
- Parameters
figures (List[prototools.canvas.FigureDataclass]) –
- Return type
None
- clear_canvas()¶
- clear_screen()¶
- keyboard_press(figure, event)¶
- Parameters
figure (prototools.canvas.FigureDataclass) –
event (str) –
- Return type
None
- move(figure)¶
- Return type
None
- refresh()¶
- class prototools.canvas.Triangle(x: int, y: int, color: Callable, side: int)¶
Bases:
prototools.canvas.FigureDataclass
- Parameters
x (int) –
y (int) –
color (Callable) –
side (int) –
- Return type
None
- get_pos()¶
- Return type
List[Tuple[int, int]]
- side: int¶
- prototools.canvas.get_max(sequence, fallback=0)¶
- Parameters
sequence (List[int]) –
fallback (Any) –
- Return type
int
prototools.colorize module¶
- prototools.colorize.black(text)¶
- prototools.colorize.blue(text)¶
- prototools.colorize.create_colors(opts=(), **kwargs)¶
- prototools.colorize.cyan(text)¶
- prototools.colorize.green(text)¶
- prototools.colorize.magenta(text)¶
- prototools.colorize.red(text)¶
- prototools.colorize.white(text)¶
- prototools.colorize.yellow(text)¶
prototools.components module¶
- class prototools.components.Border(type='light')¶
Bases:
object
Menu border.
- Parameters
type (str) – Type of border (ascii, light, heavy, double), defaults to light.
- Return type
None
- type¶
Type of border.
- Type
str
- top_left¶
Top left corner of the menu.
- Type
str
- top_right¶
Top right corner of the menu.
- Type
str
- bottom_left¶
Bottom left corner of the menu.
- Type
str
- bottom_right¶
Bottom right corner of the menu.
- Type
str
- vertical¶
Vertical line (VL).
- Type
str
- vertical_left¶
VL with a protruding inner line to the R.
- Type
str
- vertical_right¶
VL with a protruding inner line to the L.
- Type
str
- horizontal¶
Horizontal line (HL).
- Type
str
- horizontal_bottom¶
HL with an upward inner line.
- Type
str
- horizontal_top¶
HL with an downward inner line.
- Type
str
- intersection¶
Intersection border.
- Type
str
Example
>>> border = Border() >>> border.top_left ┌ >>> border = Border("ascii") >>> border.top_left + >>> border = Border("double") >>> border.set_style("heavy") >>> border.type heavy
- set_style(type)¶
Set the type of the border.
- Parameters
type (str) – Type of border (ascii, light, heavy, double).
- Return type
None
Example
>>> border = Border() >>> border.set_style("ascii") >>> border.type ascii
- class prototools.components.Box(style=None, max_dimension=None, color=None, title=None, title_align=None, subtitle=None, subtitle_align=None, text=None, text_align='left', textnl=None, textnl_align='left')¶
Bases:
prototools.components.Component
Optional box section.
- Parameters
style (Style, optional) – Style of the component.
max_dimension (Dimension, optional) – Maximum dimension.
color (Color, optional) – Color of the component.
title (str, optional) – Title of the header.
subtitle (str, optional) – Subtitle of the header.
subtitle_align (str, optional) – Subtitle alignment.
text (str, optional) – Text to be displayed.
text_align (str, optional) – Text alignment.
textnl (str, optional) – Text displayed in newlines.
textnl_align (str, optional) – Text in newlines alignment.
title_align (Optional[str]) –
- Return type
None
Example
>>> t = "Prototools" >>> s = "... faster development" >>> box = Box(title=t, subtitle=s, subtitle_align="right") >>> render(box) ┌─────────────────────────────────────────────────┐ │ │ │ Prototools │ │ │ │ ... faster development │ │ │ └─────────────────────────────────────────────────┘
- generate()¶
Generate the component.
- Return type
Generator[str, str, None]
- class prototools.components.Component(style=None, max_dimension=None, color=None)¶
Bases:
object
Base class for menu components.
- Parameters
- Raises
TypeError – If style is not an instance of Style.
- Return type
None
Example
>>> component = Component()
- property border: str¶
Border of this component.
- generate()¶
Generate the component.
- Yields
str – Next string of characters for drawing this component.
- Return type
Generator[str, str, None]
Note
Each subclass implements generate():
Subclass_A.generate() Subclass_B.generate() Subclass_C.generate()
- property margin: int¶
Margin of this component.
- property max_dimension: prototools.components.Dimension¶
Max dimension of this component.
- property padding: int¶
Padding of this component.
- property style: prototools.components.Style¶
Style of this component.
- class prototools.components.Dimension(width=0, height=0, dimension=None)¶
Bases:
object
Width and height of a component.
- Parameters
width (int) – Width of the component, in columns.
height (int) – Height of the component, in rows.
dimension (Dimension, optional) – An existing Dimension from which to duplicate the height and width.
- Return type
None
Example
>>> dimension = Dimension(40, 20) >>> dimension.width 40 >>> dimension.height 20 >>> other_dimension = Dimension() >>> other_dimension 0x0 >>> new_dimension = Dimension(dimension=dimension) >>> new_dimension 40x20
Bases:
prototools.components.Component
Menu footer section.
- Parameters
- Return type
None
Example
>>> footer = Footer() >>> render(footer) │ │ └─────────────────────────────────────────────────┘
Generate the component.
- Yields
str – Next string of characters for drawing this component.
- Return type
Generator[str, str, None]
Note
Each subclass implements generate():
Subclass_A.generate() Subclass_B.generate() Subclass_C.generate()
- class prototools.components.Header(style=None, max_dimension=None, color=None, title=None, title_align=None, subtitle=None, subtitle_align=None, show_bottom=False)¶
Bases:
prototools.components.Component
Menu header section.
- Parameters
style (Style, optional) – Style of the component.
max_dimension (Dimension, optional) – Maximum dimension.
color (Color, optional) – Color of the component.
title (str, optional) – Title of the header.
subtitle (str, optional) – Subtitle of the header.
subtitle_align (str, optional) – Subtitle alignment.
show_bottom (bool) – If True shows the bottom border, defaults to False.
title_align (Optional[str]) –
- Return type
None
Example
>>> header = Header(title='Prototools') >>> render(header) ┌─────────────────────────────────────────────────┐ │ │ │ ProtoTools │ │ │
- generate()¶
Generate the component.
- Return type
Generator[str, str, None]
- class prototools.components.Items(style=None, max_dimension=None, color=None, items=None, items_align='left')¶
Bases:
prototools.components.Component
Menu section for displayin the menu items.
- Parameters
- Return type
None
Example
>>> options = [Item('Accounts'), Item('Transactions')] >>> items = Items(items=options) >>> render(items) │ │ │ 1 - Accounts │ │ 2 - Transactions │ │ │
- generate()¶
Generate the component.
- Return type
Generator[str, str, None]
- property items: str¶
- property items_bottom: str¶
Return a list of the names of all items that should show a bottom border.
- property items_top: str¶
Return a list of the names of all items that should show a top border.
- show_item_bottom(text, flag)¶
Set a flag that will show a bottom border for an item with the specified text.
- Parameters
text (str) – Text property of the item.
flag (bool) – Boolean specifying if the border should be shown.
- Return type
None
- show_item_top(text, flag)¶
Set a flag that will show a top border for an item with the specified text.
- Parameters
text (str) – Text property of the item.
flag (bool) – Boolean specifying if the border should be shown.
- Return type
None
- class prototools.components.Margin¶
Bases:
object
Menu margin.
- Return type
None
- top¶
Top margin.
- Type
int
- left¶
Left margin.
- Type
int
- bottom¶
Bottom margin.
- Type
int
- right¶
Right margin.
- Type
int
Examples
>>> margin = Margin() >>> margin.right 2 >>> margin.top 1
- bottom¶
- left¶
- right¶
- set_defaults()¶
- Return type
None
- top¶
- class prototools.components.Padding¶
Bases:
object
Menu padding.
- Return type
None
- top¶
Top padding.
- Type
int
- left¶
Left padding.
- Type
int
- bottom¶
Bottom padding.
- Type
int
- right¶
Right padding.
- Type
int
Examples
>>> padding = Padding() >>> padding.left 2 >>> padding.bottom 1
- bottom¶
- left¶
- right¶
- set_defaults()¶
- Return type
None
- top¶
- class prototools.components.Prompt(style=None, max_dimension=None, color=None, prompt='')¶
Bases:
prototools.components.Component
Menu prompt for user input.
- Parameters
- Return type
None
Note
The prompt >>> is generated in a newline.
Example
Script:
prompt = Prompt() render(prompt)
Output:
>>>
- generate()¶
Generate the component.
- Return type
Generator[str, str, None]
- property prompt: str¶
- class prototools.components.Screen¶
Bases:
object
Representation of a console screen.
- Return type
None
- width¶
Screen width in columns.
- Type
int
- height¶
Screen height in rows.
- Type
int
Example
>>> screen = Screen()
- static clear()¶
Clear the screen.
- Return type
None
- static flush()¶
Flush any buffered standard output to screen.
- Return type
None
- input(prompt='')¶
Prompt the user for input.
- Parameters
prompt (str) – Message to display as the prompt.
- Returns
User’s input.
- Return type
str
- static printf(*args)¶
Print the arguments to the screen.
- Parameters
*args – Variable length argument list.
args (Any) –
- Return type
None
- static println(*args)¶
Print the arguments to the screen, including an appended newline character.
- Parameters
*args – Variable length argument list.
args (Any) –
- Return type
None
- class prototools.components.Style(margin=None, padding=None, border_type=None)¶
Bases:
object
Specify all menu styling (margins, paddings and borders).
- Parameters
- Return type
None
Example
>>> style = Style() >>> style.margin.left 2 >>> style.border.type light >>> style.paddin.bottom 1
- class prototools.components.Text(style=None, max_dimension=None, color=None, text=None, text_align='left', show_top=False, show_bottom=False)¶
Bases:
prototools.components.Component
Menu text block section.
- Parameters
style (Style, optional) – Style of the component.
max_dimension (Dimension, optional) – Maximum dimension.
color (Color, optional) – Color of the component.
text (str, optional) – Text to be displayed.
text_align (str, optional) – Text alignment.
show_top (bool) – If True shows the top border, defaults to False.
show_bottom (bool) – If True shows the bottom border, defaults to False.
- Return type
None
Example
>>> message = 'This is a text section...' >>> text = Text(text=message) >>> render(text) │ │ │ This is a text section... │ │ │
- generate()¶
Generate the component.
- Return type
Generator[str, str, None]
prototools.config module¶
prototools.constants module¶
prototools.decorators module¶
- class prototools.decorators.Counter(function)¶
Bases:
object
Count the number of calls that a function does.
Examples
Scripts:
@Counter def update(): print("Updated!") update() update() update()
Output:
Call 1 of 'update' Updated! Call 2 of 'update' Updated! Call 3 of 'update' Updated!
- Parameters
function (prototools.decorators.F) –
- Return type
None
- prototools.decorators.banner(title, width=<class 'int'>, style=None)¶
Print a banner.
- Parameters
Title (str) – Title of the banner.
width (int) – Ancho del banner.
style (str, optional) – Border style.
title (str) –
Example
Script:
@banner("ProtoTools", 12) def mensaje(): return None mensaje()
Output:
══════════════════ ProtoTools ══════════════════
- prototools.decorators.debug(function)¶
Print the decorated function signature and its return value.
Example
Script:
@debug def say_hi(name): return f"Hi {name}!" say_hi("ProtoTools")
Output:
Calling: say_hi('ProtoTools') 'say_hi' returned 'Hi ProtoTools!'
- Parameters
function (prototools.decorators.F) –
- Return type
prototools.decorators.F
- prototools.decorators.handle_error(_function=None, *, message='Error:')¶
Handles exceptions.
- Parameters
message (str) – Custom message.
_function (Optional[prototools.decorators.F]) –
Example
Script:
@handle_error def f(n): print(int(n)) @handle_error(message="E>") def g(n): print(int(n)) f("s") g("s")
Output:
Error: invalid literal for int() with base 10: 's' E> invalid literal for int() with base 10: 's'
- prototools.decorators.inject(f, _function=None, *, values=None, after=True)¶
Inject a function into another function.
- Parameters
f (Callable) – The function to inject.
values (List[Any]) – Function’s arguments.
after (bool) – If True, inject after the function; otherwise, inject before the function.
_function (Optional[prototools.decorators.F]) –
Example
Script:
def f(s): print(s) @inject(f, values=("Ending",)) @inject(f, values=("Starting",), after=False) def g(n): print(n**2) g(2)
Output:
Starting 4 Ending
- prototools.decorators.obsolete(message)¶
Decorate an obsolote function and sends a warning message.
Example
Script:
@obsolete("use 'g()' instead") def f(): return "version 1.0" print(f())
Output:
DeprecationWarning: Function 'f' is obsolete!, use 'g()' instead
- Parameters
message (str) –
- Return type
None
- prototools.decorators.register(function)¶
Register a function as a plug-in.
Example
Script:
from prototools.decorators import PLUGINS, register @register def f(): pass print(PLUGINS)
OUTPUT:
{'f': <function f at 0x00000258176C64C8>}
- Parameters
function (prototools.decorators.F) –
- Return type
prototools.decorators.F
- prototools.decorators.repeat(_function=None, *, n=2)¶
Repeat ‘n’ times the decorated function.
- Parameters
n (int) – Number of repetitions.
_function (Optional[prototools.decorators.F]) –
Example
Script:
@repeat(4) def say_hi(name): print(f"Hi {name}!") say_hi("ProtoTools")
Output:
Hi ProtoTools! Hi ProtoTools! Hi ProtoTools! Hi ProtoTools!
- prototools.decorators.retry(_function=None, *, tries=3, default=None)¶
Retry a function if it raises an exception.
- Parameters
tries (int) – Number of tries.
defualt (Any, optional) – Default value.
_function (Optional[prototools.decorators.F]) –
default (Optional[Any]) –
Example
Script:
from random import randint @retry(tries=3, default=0) def f(): rnd = randint(1, 10) if rnd > 5: return rnd else: raise ValueError("Random number is less than 5") print(f())
Output:
Retrying (1): Random number is less than 5 Retrying (2): Random number is less than 5 8
- prototools.decorators.singleton(cls)¶
Make a class a Singleton class (only one instance).
Example
Script:
@singleton class T: pass
>>> a = T() >>> b = T() >>> id(a) 2031647265608 >>> id(b) 2031647265608 >>> a is b True
- prototools.decorators.slow_down(_function=None, *, seconds=1)¶
Sleep ‘n’ seconds before calling the function.
Example
Script:
@slow_down(seconds=2) def f(n): if n < 1: prin("End!") else: print(n) f(n-1) f(3)
Output:
3 2 1 End!
- Parameters
_function (Optional[prototools.decorators.F]) –
seconds (int) –
- prototools.decorators.timer(_function=None, *, fg=None, bg=None)¶
Print the runtime of the decorated function.
- Parameters
fg (str, optional) – Foreground color.
bg (str, optional) – Background color.
_function (Optional[prototools.decorators.F]) –
Example
Script:
@timer def f(n): for _ in range(n): sum([x**2 for x in range(10_000)]) f(10)
Output:
Finished 'f' in 0.028945 secs
prototools.exp module¶
- class prototools.exp.Maybe(value=None, containes_value=True)¶
Bases:
object
Example
>>> from prototools.exp import Maybe >>> f = lambda x: x + 3 >>> r = Maybe(2)|f|f >>> print(r) 8
- bind(func)¶
- get()¶
- prototools.exp.retrieve_argname(var)¶
Retrieve the name of the argument passed to the function.
- Parameters
var (object) – The argument passed to the function.
- Returns
The name of the argument.
- Return type
str
Example
>>> def foo(a): n = retrieve_argname(a) ... return f"{n}'s value is {a}" ... >>> x = 42 >>> foo(x) 'x's value is 42
- prototools.exp.retrive_varname(var)¶
- prototools.exp.return_names(name=None)¶
prototools.gui module¶
- prototools.gui.messagebox(caption=None, text=None, flags=None)¶
- Parameters
caption (Optional[str]) –
text (Optional[str]) –
flags (Optional[int]) –
- Return type
None
prototools.inputs module¶
- prototools.inputs.bool_input(prompt='', true_value=None, false_value=None, sensitive=False, default=None, blank=False, strip=None, timeout=None, limit=None, function=None, validation=None, lang='en')¶
Prompts the user to enter a True/False response.
- Parameters
prompt (str, optional) – Prompts the user to enter input.
true_value (bool, optional) – Value of affirmative response. Defaults ‘yes’.
no_value (bool, optional) – Value of negative response. Defaults ‘no’.
sensitive (bool, optional) – If True, then the exact case of the option must be entered.
default (Any, optional) – Default value to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
lang (str) – Establish the language.
false_value (Optional[str]) –
- Returns
Boolean value.
- Return type
bool
>>> s = bool_input() yes yes is not a valid yes/no response t >>> s True
- prototools.inputs.choice_input(choices, sensitive=False, prompt='_default', default=None, blank=False, strip=None, timeout=None, limit=None, function=None, validation=None, lang='en')¶
Prompt the user to enter one of the provieded choices.
- Parameters
choices (Sequence[str]) – Sequence of strings, one of which the user must enter.
sensitive (bool, optional) – If True, then the exact case of the option must be entered.
prompt (str, optional) – Prompts the user to enter input.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
lang (str) – Establish the language.
default (Optional[Any]) –
- Raises
Exception – If value is not one of the values in choices.
- Returns
The selected choice as a string.
- Return type
str
>>> options = ("a", "b", "c") >>> s = choice_input(options) Select one of: a, b, c 1 1 is not a valid choice Select one of: a, b, c a >>> s 'a'
- prototools.inputs.custom_input(prefix='', suffix='')¶
Custom input with a prefix string and a suffix string. User’s input is located in between prefix and suffix.
- Parameters
prefix (str) – Prefix word before user input.
suffix (str) – Suffix word after user input.
- Returns
User input.
- Return type
str
>>> s = custom_input("Age: ", " years old.") Age: __ years old. Age: 18 years old. >>> s 18
- prototools.inputs.date_input(prompt='', formats=None, default=None, blank=False, strip=None, timeout=None, limit=None, function=None, validation=None, lang='en')¶
Prompt the user to enter a date.
- Parameters
prompt (str, optional) – Prompts the user to enter input.
formats (Union[str, Sequence[str]], optional) – Date formats.
default (Any, optional) – Default value to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
lang (str) – Establish the language.
- Returns
The date.
- Return type
str
>>> s = date_input() 12-12-2021 12-12-2021 is not a valid date 12/12/2021 >>> s 2021/12/12 >>> type(s) <class 'datetime.date'>
- prototools.inputs.date_input_dmy(prompt='', formats=None, to_str=True, default=None, blank=False, strip=None, timeout=None, limit=None, function=None, validation=None, lang='en')¶
Prompt the user to enter a date.
- Parameters
prompt (str, optional) – Prompts the user to enter input.
formats (Union[str, Sequence[str]], optional) – Date formats.
to_str (bool, optional) – If True, the date is returned as a string.
default (Any, optional) – Default value to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
lang (str) – Establish the language.
- Returns
The date.
- Return type
str
>>> s = date_input() 12-12-2021 12-12-2021 is not a valid date 12/12/2021 >>> s 2021/12/12 >>> type(s) <class 'datetime.date'>
- prototools.inputs.day_input()¶
- prototools.inputs.email_input(prompt='', default=None, blank=False, strip=None, timeout=None, limit=None, allow_regex=None, block_regex=None, function=None, validation=None, lang='en')¶
Prompt the user to enter an email.
- Parameters
prompt (str, optional) – Prompts the user to enter input.
default (Any, optional) – Default value to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
allow_regex (Sequence, optional) – Regex to allow.
block_regex (Sequence, optional) – Regex to block.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
lang (str) – Establish the language.
- Returns
The email.
- Return type
str
>>> email = email_input() john@doe.com >>> email john@doe.com >>> email = email_input() ayudaenpython ayudaenpython is not a valid email ayudaen@python.com >>> email ayudaen@python
- prototools.inputs.float_input(prompt='', default=None, blank=False, strip=None, timeout=None, limit=None, function=None, validation=None, min=None, max=None, lt=None, gt=None, lang='en')¶
Prompt the user to enter a floating point number.
- Parameters
prompt (str, optional) – Prompts the user to enter input.
default (Any, optional) – Default value to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
min (Union[int, float, None]) – Minimum valur (inclusive).
max (Union[int, float, None]) – Maximum value (inclusive).
lt (Union[int, float, None]) – Minimum value (exclusive).
gt (Union[int, float, None]) – Maximum value (exclusive).
lang (str) – Establish the language.
- Raises
Exception – If value is not a float.
- Returns
The number as a float.
- Return type
int
>>> from prototools.inputs import float_input >>> number = float_input() 6 >>> number 6.0 >>> type(number) <class 'float'>
- prototools.inputs.int_input(prompt='', default=None, blank=False, strip=None, timeout=None, limit=None, function=None, validation=None, min=None, max=None, lt=None, gt=None, lang='en')¶
Prompt the user to enter an integer number.
- Parameters
prompt (str, optional) – Prompts the user to enter input.
default (Any, optional) – Default value to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
min (Union[int, float, None]) – Minimum valur (inclusive).
max (Union[int, float, None]) – Maximum value (inclusive).
lt (Union[int, float, None]) – Minimum value (exclusive).
gt (Union[int, float, None]) – Maximum value (exclusive).
lang (str) – Establish the language.
- Raises
Exception – If value is not an int.
- Returns
The number as an int.
- Return type
int
>>> from prototools.inputs import int_input >>> number = int_input() 6.0 >>> number 6 >>> type(number) <class 'int'>
Prompt the user to enter one of the provieded choices. Also displays a small menu with bulleted, numbered, or lettered options.
- Parameters
choices (Sequence[str]) – Sequence of strings, one of which the user must enter.
numbers (bool, optional) – If True, it will also accept a number as a choice.
letters (bool, optional) – If True, it will also accept a letter as a choice.
sensitive (bool, optional) – If True, then the exact case of the option must be entered.
prompt (str, optional) – Prompts the user to enter input.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
lang (str) – Establish the language.
default (Optional[Any]) –
- Raises
Exception – If value is not one of the values in choices.
- Returns
The selected choice as a string.
- Return type
str
>>> options = ("a", "b", "c") >>> s = menu_input(options) Select one of the following: * a * b * c 1 1 is not a valid choice Select one of the following: * a * b * c a >>> s 'a'
- prototools.inputs.month_input()¶
- prototools.inputs.password_input(prompt='')¶
Prompts the user to enter a password. Mask characters will be displayed instead of the actual characters.
- Parameters
prompt (str) –
- prototools.inputs.str_input(prompt='', default=None, blank=False, strip=None, timeout=None, limit=None, function=None, validation=None, lang='en')¶
Prompt the user to enter any string.
- Parameters
prompt (str, optional) – Prompts the user to enter input.
default (Any, optional) – Default value to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
lang (str) – Establish the language.
- Raises
Exception – If value is not an str.
- Returns
The string.
- Return type
str
>>> s = str_input("Enter a string: ") Enter a string: prototools >>> s 'prototools'
- prototools.inputs.time_input(prompt='', formats=('%H:%M:%S', '%H:%M', '%X'), default=None, blank=False, strip=None, timeout=None, limit=None, function=None, validation=None, lang='en')¶
Prompt the user to enter a time.
- Parameters
prompt (str, optional) – Prompts the user to enter input.
formats (Union[str, Sequence[str]], optional) – Time formats.
default (Any, optional) – Default value to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
lang (str) – Establish the language.
- Returns
The time.
- Return type
str
>>> s = time_input() 1200 1200 is not a valid time 12:00 >>> s 12:00:00 >>> type(s) <class 'datetime.time'>
- prototools.inputs.yes_no_input(prompt='', yes_value=None, no_value=None, sensitive=False, default=None, blank=False, strip=None, timeout=None, limit=None, function=None, validation=None, lang='en')¶
Prompt the user to enter a yes/no response.
- Parameters
prompt (str, optional) – Prompts the user to enter input.
yes_value (bool, optional) – Value of affirmative response. Defaults ‘yes’.
no_value (bool, optional) – Value of negative response. Defaults ‘no’.
sensitive (bool, optional) – If True, then the exact case of the option must be entered.
default (Any, optional) – Default value to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
lang (str) – Establish the language.
- Raises
Exception – If value is not a yes or no response.
- Returns
The yes_val or no_val argument, not value.
- Return type
str
>>> s = yes_no_input("Do you like this?") Do you like this? Yeah Yeah is not a valid yes/no response Do you like Python? yes >>> s 'yes'
prototools.keyboard module¶
- class prototools.keyboard.Keyboard¶
Bases:
object
Keys pressed by the user.
- BACKSPACE = (8, 127)¶
- DOWN = b'P'¶
- ENTER = 13¶
- ESC = 27¶
- LEFT = b'K'¶
- RIGHT = b'M'¶
- SPECIAL_KEYS = (224, 0)¶
- UP = b'H'¶
- classmethod action(key_pressed)¶
Action done by the user.
- bBACKSPACE = b'\x08\x7f'¶
- bENTER = b'\r'¶
- prototools.keyboard.arrow_movement(event, f)¶
Moves an object with the arrow keys.
- Parameters
event (str) – Keyboard event.
f (Callable) – Function to be called.
- Returns
True if the movement was done, False otherwise.
- Return type
bool
- prototools.keyboard.arrow_position(position, size, event)¶
Returns the position of the element selected.
- Parameters
position (int) – Current position.
size (int) – Size of the items (menu).
event (str) – Keyboard event.
- Returns
Position of the menu item.
- Return type
int
- prototools.keyboard.isShiftCharacter(character)¶
Returns True if the character is a keyboard key that would require the shift key to be held down, such as uppercase letters or the symbols on the keyboard’s number row.
- Parameters
character (str) –
- Return type
str
- prototools.keyboard.move_arrow(function, pressed=None, clear=False)¶
- Parameters
function (Callable) –
pressed (Optional[str]) –
clear (bool) –
- prototools.keyboard.press(keys, presses=1, interval=0.0, _pause=True)¶
Performs a keyboard key press down, followed by a release.
- Parameters
key (str, list) – The key to be pressed. Valid names are listed in KEYBOARD_KEYS. Can also be a list of such strings.
presses (integer, optional) – The number of press repetitions. 1 by default, for just one press.
interval (float, optional) – How many seconds between each press. 0.0 by default, for no pause between presses.
pause (float, optional) – How many seconds in the end of function process.
- Returns
None
- prototools.keyboard.typewrite(message, interval=0.0, _pause=True)¶
Performs a keyboard key press down, followed by a release, for each of the characters in message. The message argument can also be list of strings, in which case any valid keyboard name can be used. Since this performs a sequence of keyboard presses and does not hold down keys, it cannot be used to perform keyboard shortcuts.
- Parameters
message (str, list) – If a string, then the characters to be pressed. If a list, then the key names of the keys to press in order. The valid names are listed in KEYBOARD_KEYS.
interval (float, optional) – Seconds in between each press. 0.0 by default, for no pause in between presses.
- Return type
None
prototools.letters module¶
prototools.protodb module¶
- class prototools.protodb.ProtoDB(filename)¶
Bases:
object
Simple and lightweight json database
- Parameters
filename (str) –
- Return type
None
- add(obj, id=None)¶
- Parameters
obj (object) –
id (Optional[str]) –
- Return type
None
- delete(key)¶
- Parameters
key (str) –
- Return type
None
- filename¶
- get(key)¶
- Parameters
key (str) –
- Return type
Union[Dict[str, Union[Dict[str, JSON], List[JSON], int, str, float, bool, Type[None]]], List[Union[Dict[str, JSON], List[JSON], int, str, float, bool, Type[None]]], int, str, float, bool, Type[None]]
- get_all()¶
- Return type
List[Union[Dict[str, Union[Dict[str, JSON], List[JSON], int, str, float, bool, Type[None]]], List[Union[Dict[str, JSON], List[JSON], int, str, float, bool, Type[None]]], int, str, float, bool, Type[None]]]
- get_data()¶
- search(key)¶
- Parameters
key (str) –
- Return type
Generator
prototools.protosql module¶
- class prototools.protosql.ProtoSqlite(name=None, lang=None, check=None)¶
Bases:
object
Simple SqLite wrapper
- Parameters
name (Optional[str]) –
lang (Optional[str]) –
check (Optional[bool]) –
- Return type
None
- name¶
The name of the database.
- Type
str
- lang¶
The language to translate to.
- Type
str
- check¶
Whether to check if the thread is the same as the one that created the database.
- Type
bool
- add(table, data)¶
- Parameters
table (str) –
data (dict) –
- Return type
None
- check¶
- close()¶
- Return type
None
- conn¶
- create_table(table, columns=None, pk=None)¶
- Parameters
table (str) –
pk (Optional[str]) –
- cursor¶
- delete(table, col, pk)¶
- Parameters
table (str) –
col (str) –
pk (str) –
- execute(sql)¶
- Parameters
sql (str) –
- Return type
None
- get(table, columns, limit=None)¶
- Parameters
table (str) –
columns (str) –
limit (Optional[int]) –
- get_all(table)¶
- Parameters
table (str) –
- Return type
List[Tuple[Any, …]]
- get_last(table, index=None, value=None)¶
- Parameters
table (str) –
index (Optional[Any]) –
value (Optional[Any]) –
- Return type
list
- get_pk(table)¶
- Parameters
table (str) –
- Return type
str
- lang¶
- name¶
- open(name)¶
- Parameters
name (str) –
- Return type
None
- query(sql)¶
- Parameters
sql (str) –
- Return type
None
- select(table, q)¶
- Parameters
table (str) –
q (str) –
- static summary(rows)¶
- Parameters
rows (Any) –
- Return type
Any
- static to_csv(data, filename='output.csv')¶
- Parameters
filename (str) –
- static to_json(data, filename='output.json')¶
- Parameters
filename (str) –
- static to_txt(data, filename='output.txt')¶
- Parameters
filename (str) –
- update(table, columns, condition)¶
- Parameters
table (str) –
columns (str) –
condition (str) –
- Return type
None
- update_(table, columns, condition)¶
- Parameters
table (str) –
columns (str) –
condition (str) –
- Return type
None
- prototools.protosql.cols(class_)¶
Helper function to get the columns of a class.
- Parameters
class_ (object) –
- Return type
dict
- prototools.protosql.execute(function, function_condition, message, expression=<function <lambda>>, condition=False, alt_function=None, alt_message='')¶
- prototools.protosql.get_data(obj)¶
Get the attributes and values of an object.
- Parameters
obj (object) –
- Return type
dict
- prototools.protosql.get_q(obj)¶
prototools.tabulate module¶
- prototools.tabulate.show_cols(data, chars=None, fg=None, bg=None)¶
Prints columns representing the data.
- Parameters
data (List[float]) – Data to be shown.
chars (str, optional) – Character to be used. Defaults to ‘Full Block’
fg (Callable, optional) – Foreground color. Defaults to None.
bg (Callable, optional) – Background color. Defaults to None.
- Return type
str
>>> data = [4, 3, 0, 2, 1] >>> print(show_cols(data)) █ ░ ░ ░ ░ █ █ ░ ░ ░ █ █ ░ █ ░ █ █ ░ █ █
- prototools.tabulate.tabulate(data, headers=None, headless=False, inner=False, style=None, border_type=None, align=None, color=None, title=None)¶
Display data in a table.
- Parameters
data (Sequence) – Data to be shown.
headers (List[str], optional) – Optional header of the table.
headless (bool, optional) – If True, the data has no header. If False, the first row of the data becomes the header. Defaults False.
inner (bool, optional) – If True, the inner border is shown. Defaults False.
style (Tuple[int, ...], optional) – Tuple of int representing the padding left, padding right, margin left and margin right.
border_type (str, optional) – Type of the border.
align (str, optional) – Alignment can be left, center or right.
color (Optional[Callable[[str], str]]) –
title (Optional[str]) –
- Returns
Data ready to be printed.
- Return type
str
TODO: add example
- prototools.tabulate.to_list(d, return_head=False)¶
Convert a dictionary to a list.
- Parameters
d (Dict[Any]) – Dictionary to convert.
- Returns
List of the dictionary.
- Return type
List[Any]
prototools.utils module¶
- class prototools.utils.RangeDict¶
Bases:
dict
Custom range.
Example
Script:
from prototools import RangeDict table = RangeDict({ (1, 4): "a", (5, 8): "b", (9, 12): "c", }) print(table[3]) # a print(table[6]) # b print(table[11]) # c
- prototools.utils.ask_to_finish(prompt='_default', yes='_default', input_prompt='> ', lang='en')¶
Ask the user to finish a loop.
- Parameters
prompt (str, optional) – Prompt the user to finish or not the loop.
yes (str, optional) – Value of affirmative response.
lang (str, optional) – Establish the language.
input_prompt (Optional[str]) –
- Returns
True if the user wants to continue, False otherwise.
- Return type
bool
- prototools.utils.chunker(sequence, size)¶
Simple chunker.
- Returns
A generator.
- Return type
Generator
Example
>>> list(chunker(list(range(10)), 3)) [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
- prototools.utils.clear_screen()¶
Clear the screen.
- Return type
None
- prototools.utils.compose(*functions)¶
Compose functions.
- Parameters
functions (ComposableFunction) – Bunch of functions.
- Returns
Composed function.
- Return type
Callable
Example
>>> def f(x): ... return x * 2 >>> def g(x): ... return x + 1 >>> h = compose(f, g) >>> h(3) 7 >>> h(4) 9
- prototools.utils.create_f(name, args, body)¶
Create a function.
- Parameters
name (str) – Name of the function.
args (Any) – Arguments.
unique (str) – Body of the function.
body (str) –
- Returns
Function.
- Return type
Callable
Example
Script:
t = ''' for i in range(3): r = (x + y) * i print(f"({x} + {y}) * {i} = {r}") ''' f = create_f("g", "x=2 y=3", t) f()
Output:
(2 + 3) * 0 = 0 (2 + 3) * 1 = 5 (2 + 3) * 2 = 10
- prototools.utils.flatten(list_of_lists)¶
Return an iterator flattening one level of nesting in a list of lists.
Example
>>> list(flatten([[0, 1], [2, 3]])) [0, 1, 2, 3]
- prototools.utils.get_data(filename, mode='lines', encoding='utf-8')¶
Get data.
- Parameters
filename (str) – The name of the file to read.
mode (str, optional) – The mode to read the file. Options are: - “lines” (default): Returns a list of lines. - “text”: Returns the entire content as a single string. - “json”: Returns the parsed JSON data.
encoding (str, optional) – The encoding used to read the file. Default is “utf-8”.
- Returns
The file content based on the selected mode.
- Return type
Union[List[str], str, Any]
- Raises
ValueError – If the specified mode is not supported.
Example
>>> # Reading lines from a text file >>> lines = get_data("data.txt") >>> print(lines) ['line 1', 'line 2', 'line 3']
>>> # Reading the entire content as a single string >>> text = get_data("data.txt", mode="text") >>> print(text) 'line 1\nline 2\nline 3'
>>> # Reading and parsing a JSON file >>> data = get_data("data.json", mode="json") >>> print(data) {'key1': 'value1', 'key2': 'value2'}
- prototools.utils.grouper(iterable, n, fillvalue=None)¶
Collect data into fixed-length chunks or blocks.
Example
>>> list(grouper('ABCDEFG', 3, 'x')) [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'x', 'x')]
- prototools.utils.hide_cursor()¶
Hide console cursor.
- Return type
None
- prototools.utils.main_loop(function, args=None, kwargs=None, validation=None, custom_function=None, lang='en')¶
Call a function until validation is False.
- Parameters
function (Callable) – Function to iterate.
args (Optional[List[Any]]) – Arguments to pass to function.
kwargs (Optional[Dict[Any, None]]) – Keyword arguments to pass to function.
validation (Callable) – If False, ends the loop.
custom_function (Callable) – Function that determines if the loop should continue. If False, ends the loop.
lang (Optional[str]) –
- Returns
Result of function.
- Return type
Union[Any, None]
- prototools.utils.make_grid(iterable, group, function=<class 'str'>, reversed=True)¶
Generates a grid.
- Parameters
iterable (Iterable[Any]) – Iterable.
function (Callable) – Function to apply to each element.
group (int) – Group size.
reversed (bool, optional) – If True, the grid is reversed. Defaults to False.
- Returns
Grid.
- Return type
List[List[Any]]
Example
>>> make_grid(range(1, 10), 3) [('7', '8', '9'), ('4', '5', '6'), ('1', '2', '3')]
- prototools.utils.matrix(i, j, rng=None, char=None, rnd=False, precision=None)¶
Create a matrix.
- Parameters
i (int) – Number of rows.
j (int) – Number of columns.
rng (Tuple[int, int], optional) – Range of the matrix.
char (str, optional) – Character to fill the matrix.
rnd (bool, optional) – Randomize the matrix.
precision (int, optional) – Number of decimals.
- Returns
Matrix.
- Return type
List[List[float]]
Example
>>> matrix(3, 3) [[1, 1, 1], [0, 1, 0], [1, 0, 0]]
- prototools.utils.matrix_panel(text, fg=None, bg=None)¶
Example
>>> matrix_panel("ABC") ░░██████░░░░████████░░░░░░████████░░ ██░░░░░░██░░██░░░░░░██░░██░░░░░░░░░░ ██░░░░░░██░░██░░░░░░██░░██░░░░░░░░░░ ██░░░░░░██░░████████░░░░██░░░░░░░░░░ ██████████░░██░░░░░░██░░██░░░░░░░░░░ ██░░░░░░██░░██░░░░░░██░░██░░░░░░░░░░ ██░░░░░░██░░████████░░░░░░████████░░
- Parameters
text (str) –
fg (Optional[str]) –
bg (Optional[str]) –
- Return type
None
- prototools.utils.mvc_launcher(mode, model, cli, gui, web, name=None, url='http://127.0.0.1:5000/')¶
A simple MVC Launcher.
- Parameters
mode (str) – Mode.
model (object) – Model.
cli (Tuple[object, object]) – CLI controller, CLI view.
gui (Tuple[object, object]) – GUI controller, GUI view.
web (Tuple[object, object]) – Web controller, Web view.
name (str, optional) – Name of the application. Defaults to None.
url (str, optional) – URL. Defaults to “http://127.0.0.1:5000/”.
- Return type
None
- prototools.utils.mvc_setup(mode, cli, gui, web, web_name='WEB', cli_name='CLI', gui_name='GUI')¶
Setup the MVC architecture.
- Parameters
mode (str) – Mode.
cli (Tuple[object, object]) –
gui (Tuple[object, object]) – GUI.
web (Tuple[object, object]) – WEB.
web_name (str, optional) – WEB name.
cli_name (str, optional) – CLI name.
gui_name (str, optional) – GUI name.
- Return type
Tuple[bool, Optional[object], Optional[object]]
- prototools.utils.pairs(iterable)¶
s -> (s0, s1), (s1, s2), (s2, s3), …
Example
>>> list(pairs([1, 2, 3, 4])) [(1, 2), (2, 3), (3, 4)]
- prototools.utils.partition(pred, iterable)¶
Use a predicate to partition entries into false entries and true entries
- prototools.utils.print_chars(line_length=32, max_char=131072)¶
Print all chars in the terminal, to help you find that cool one to put in your customized spinner or bar. Also useful to determine if your terminal do support them.
- Parameters
line_length (int) – the desired characters per line
max_char (int) – the last character in the unicode table to show this goes up to 0x10ffff, but after the default value it seems to return only question marks, increase it if would like to see more.
- Return type
None
- prototools.utils.progress_bar(count, total, width=40, prefix='', spinbar=False, ss=<itertools.cycle object>)¶
Display a progress bar.
- Parameters
count (int) – Current count.
total (int) – Total count.
width (int, optional) – Width of the progress bar.
prefix (str, optional) – Prefix of the progress bar.
spinbar (bool, optional) – Display a spinner.
- Return type
None
- prototools.utils.progressbar(iterable, width=40, prefix='', spinvar=True, spinvar_color=None, bg=None, fg=None, per=True, units=True)¶
Display a progress bar.
- Parameters
iterable (Iterable) – Iterable to iterate.
width (int, optional) – Width of the progress bar.
prefix (str, optional) – Prefix of the progress bar.
spinvar (bool, optional) – Display a spinner.
per (bool, optional) – Display the percentage.
units (bool, optional) – Display the units.
spinvar_color (Optional[Callable]) –
bg (Optional[Callable]) –
fg (Optional[Callable]) –
- Return type
Generator
Example
>>> for _ in progressbar(range(50)): ... [x for x in range(1_000_000)] ████████████████████████████████░░░░░░░░| 41/50 [82]% ▃▁▃
- prototools.utils.random() x in the interval [0, 1). ¶
- prototools.utils.secret_message(message='prototools 0.1.22')¶
Generates code that has a secret message when executed. To used it, copy the generated code and execute it in another file.
- Parameters
message (str, optional) – Secret message.
- Returns
Code.
- Return type
str
Example
>>> secret_message("Hello World!")
Output:
import random random.seed(69420) print(''.join(chr(random.randrange(256) ^ c) for c in bytes.fromhex( 'EA8760D97CD68CB754E490D68D376C1997BBF9BD363BCE05CD85' ) if random.randrange(2)) )
- prototools.utils.show_cursor()¶
Show console cursor.
- Return type
None
- prototools.utils.show_matrix(m, width=4, style=None, borderless=False, index=False, neg_index=False, sep=1, color=None)¶
Prints a matrix.
- Parameters
m (List[List[float]]) – Matrix to be shown.
width (int, optional) – Width of the matrix. Defaults to 4.
style (str, optional) – Style of the matrix. Defaults to None.
borderless (bool, optional) – Show the matrix without borders. Defaults to False.
index (bool, optional) – Show the index of the matrix. Defaults to False.
neg_index (bool, optional) – Show the negative index of the matrix.
sep (int, optional) – Separation between the columns. Defaults to 1.
color (Callable, optional) – Color of the matrix. Defaults to None.
- Return type
None
>>> matrix = [[1, 2, 3], [4, 5, 6]] >>> show_matrix(matrix) ┌────┬────┬────┐ │ 1 │ 2 │ 3 │ ├────┼────┼────┤ │ 4 │ 5 │ 6 │ └────┴────┴────┘ >>> show_matrix(matrix, borderless=True, width=1) 1 2 3 4 5 6
- prototools.utils.strip_ansi(string)¶
Strips ansi string.
- Parameters
string (str) –
- prototools.utils.strip_ansi_width(string)¶
Gets ansi string widht.
- Parameters
s (str) – String of characters.
string (str) –
- Returns
Width of string (stripped ansi).
- Return type
int
- prototools.utils.strip_string(value, strip)¶
Strips a string, the argument defines the behaviour.
- Parameters
value (str) – String of characters to be stripped.
strip (Union[None, str, bool]) – If None, whitespace is stripped; if is a string, the characters in the string are stripped; if False, nothing is stripped.
- Returns
Stripped version of value.
- Return type
str
- prototools.utils.tail(n, iterable)¶
Return an iterator over the last n items of iterable.
Example
>>> t = tail(3, 'ABCDEFG') >>> list(t) ['E', 'F', 'G']
- prototools.utils.terminal_size()¶
Returns the width of the terminal.
- Returns
Terminal’s widht.
- Return type
int
- prototools.utils.text_align(text, width=80, style=None, align='right')¶
Similar to Python rjust, ljust and center methods.
- Parameters
text (str) – Text.
width (int) – Width.
style (str, optional) – Border style.
align (str, optional) – Alignment of the text.
- Return type
None
Example
>>> text_align("Test") ======= Test =======
- prototools.utils.textbox(text, width=80, style=None, align='center', bcolor=None, ml=0, light=True)¶
Draw a box with a text in it.
- Parameters
text (str) – Text.
width (int) – Width.
style (str, optional) – Border style.
align (str, optional) – Alignment of the text.
bcolor (str, optional) – Border color.
ml (int, optional) – Margin left.
light (bool, optional) – Adds padding top and bottom.
- Returns
Box.
- Return type
str
Example
>>> textbox(green("ProtoTools"), width=30, bcolor="red") ┌────────────────────────────┐ │ ProtoTools │ └────────────────────────────┘
- prototools.utils.time_functions(functions, args=(), kwargs=None, number=1000000, lang='en')¶
Time the execution of multiple functions.
- Parameters
functions (Union[List[Callable], Dict[str, Callable]]) – Functions to be timed. Can be a list of functions or a dictionary with function names as keys.
args (Optional[Tuple[Any, ...]]) – Positional arguments to pass to the functions.
kwargs (Optional[Dict[str, Any]]) – Keyword arguments to pass to the functions.
setup (str, optional) – Setup code for necessary imports. Defaults to an empty string.
globals (dict, optional) – Global namespace. Defaults to None.
number (int, optional) – Number of iterations for timing. Defaults to 1,000,000.
lang (str, optional) – Language for the output. Defaults to “en”.
- Return type
None
Example
>>> def f(n): ... return [x for x in range(n)] >>> def g(n): ... r = [] ... for x in range(n): ... r.append(x) ... return r >>> time_functions([f, g], args=(100,))
- Output:
‘f’ took 0.255712 secs ‘g’ took 0.421514 secs
- prototools.utils.time_functions_custom(functions, args, setup=None, globals=None, number=1000000, lang='en')¶
Time functions.
- Parameters
functions (Any) – Tuple or Dictionary of functions to be timed.
args (Tuple[Any]) – Tuple of arguments.
setup (str, optional) – Setup code to import needed modules.
globals (Callable, optional) – Current globla namespace.
number (int, optional) – Number of iterations.
lang (str, optional) – Establish the language.
- Return type
None
Example
Script:
def f(n): return [x for x in range(n)] def g(n): r = [] for x in range(n): r.append(x) return r if __name__ == "__main__": fs = {"f": f, "g": g} time_functions_custom(fs, args=(100), globals=globals())
Output:
'f' took 2.2157 secs 'g' took 6.7192 secs
- prototools.utils.time_functions_globals(functions, args=(), kwargs=None, setup='', globals=None, number=1000000, lang='en')¶
Time the execution of multiple functions.
- Parameters
functions (Union[List[Callable], Dict[str, Callable]]) – Functions to be timed. Can be a list of functions or a dictionary with function names as keys.
args (Optional[Tuple[Any, ...]]) – Positional arguments to pass to the functions.
kwargs (Optional[Dict[str, Any]]) – Keyword arguments to pass to the functions.
setup (str, optional) – Setup code for necessary imports. Defaults to an empty string.
globals (dict, optional) – Global namespace. Defaults to None.
number (int, optional) – Number of iterations for timing. Defaults to 1,000,000.
lang (str, optional) – Language for the output. Defaults to “en”.
- Return type
None
Example
>>> def f(n): ... return [x for x in range(n)] >>> def g(n): ... r = [] ... for x in range(n): ... r.append(x) ... return r >>> time_functions_globals([f, g], args=(100,), globals=globals())
- Output:
‘f’ took 0.255712 secs ‘g’ took 0.421514 secs
- prototools.utils.write_letters(text)¶
Example
>>> write_letters("Hello World!") _____ _ _ _ | _ | ___ ___ | |_ ___ | |_ ___ ___ | | ___ | __|| _|| . || _|| . || _|| . || . || ||_ -| |__| |_| |___||_| |___||_| |___||___||_||___|
- Parameters
text (str) –
- Return type
None
- prototools.utils.write_letters_custom(text, n, color)¶
- Parameters
text (str) –
n (int) –
color (Callable) –
- Return type
None
prototools.validators module¶
- exception prototools.validators.RetryLimitExecption¶
Bases:
prototools.validators.ValidatorsException
Exception raised when the user has failed to enter a valid input within the limited number of tries given.
- exception prototools.validators.TimeoutException¶
Bases:
prototools.validators.ValidatorsException
Exception raised when the user has failed to enter a valid input before the timeout period.
- exception prototools.validators.ValidationException¶
Bases:
prototools.validators.ValidatorsException
Exception raised when a validation function is called and the input fails validation.
- exception prototools.validators.ValidatorsException¶
Bases:
Exception
Base class for exceptions.
- prototools.validators.validate_bool(value, blank=False, strip=None, true_value='True', false_value='False', sensitive=False, exc_msg=None, lang='en')¶
Validate a yes/no response.
- Parameters
value (str, optional) – The value being validated.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
true_value (bool, optional) – Value of True. Defaults ‘True’.
false_value (bool, optional) – Value of False. Defaults ‘False’.
sensitive (bool, optional) – If True, then the exact case of the option must be entered.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not a “True” or “False” response.
- Returns
The true_value or false_value argument, not value.
- Return type
str
- prototools.validators.validate_choice(value, choices, blank=False, strip=None, numbers=False, letters=False, sensitive=False, exc_msg=None, lang='en')¶
Validate a choice.
- Parameters
value (str, optional) – The value being validated.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
choices (Sequence[Any]) – Sequence of choices.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
numbers (bool, optional) – If True, it will also accept a number as a choice.
letters (bool, optional) – If True, it will also accept a letter as a choice.
sensitive (bool, optional) – If True, then the exact case of the option must be entered.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not one of the values in choices.
- Returns
The selected choice.
- Return type
str
- prototools.validators.validate_date(value, formats=('%Y/%m/%d', '%y/%m/%d', '%m/%d/%Y', '%m/%d/%y', '%x'), blank=False, strip=None, exc_msg=None, lang='en')¶
Validate a date.
- Parameters
value (str, optional) – The value being validated.
formats (Union[str, Sequence[str]]) – The formats to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not a valid date.
- Returns
The value argument, not value.
- Return type
str
- prototools.validators.validate_datetime(value, formats=('%Y/%m/%d %H:%M:%S', '%y/%m/%d %H:%M:%S', '%m/%d/%Y %H:%M:%S', '%m/%d/%y %H:%M:%S', '%x %H:%M:%S', '%Y/%m/%d %H:%M', '%y/%m/%d %H:%M', '%m/%d/%Y %H:%M', '%m/%d/%y %H:%M', '%x %H:%M', '%Y/%m/%d %H:%M:%S', '%y/%m/%d %H:%M:%S', '%m/%d/%Y %H:%M:%S', '%m/%d/%y %H:%M:%S', '%x %H:%M:%S'), blank=False, strip=None, exc_msg=None, lang='en')¶
Validate a datetime.
- Parameters
value (str, optional) – The value being validated.
formats (Union[str, Sequence[str]]) – The formats to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not a valid datetime.
- Returns
The value argument, not value.
- Return type
str
- prototools.validators.validate_email(value, blank=False, strip=None, allow_regex=None, block_regex=None, exc_msg=None, lang='en')¶
Validate an email address.
- Parameters
value (str, optional) – The value being validated.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
allow_regex (Optional[Sequence], optional) – If not None, the value is only allowed to match one of the regexes.
block_regex (Optional[Sequence], optional) – If not None, the value is only allowed to match none of the regexes.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not a valid email address.
- Returns
The value argument, not value.
- Return type
str
- prototools.validators.validate_float(value, blank=False, strip=None, min=None, max=None, lt=None, gt=None, exc_msg=None, lang='en')¶
Validate a float.
- Parameters
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
number_type (str) – One of ‘num’, ‘int’, or ‘float’ to validate against, where ‘num’ means int or float.
min (Union[int, float, None]) – Minimum valur (inclusive).
max (Union[int, float, None]) – Maximum value (inclusive).
lt (Union[int, float, None]) – Minimum value (exclusive).
gt (Union[int, float, None]) – Maximum value (exclusive).
exc_msg (str, optional) – Custom message for exceptions. Defaults to None.
lang (str) – Establish the language.
value (str) –
- Raises
Exception – If value is not a float.
- Returns
Value.
- Return type
float
- prototools.validators.validate_int(value, blank=False, strip=None, min=None, max=None, lt=None, gt=None, exc_msg=None, lang='en')¶
Validate an integer.
- Parameters
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
number_type (str) – One of ‘num’, ‘int’, or ‘float’ to validate against, where ‘num’ means int or float.
min (Union[int, float, None]) – Minimum valur (inclusive).
max (Union[int, float, None]) – Maximum value (inclusive).
lt (Union[int, float, None]) – Minimum value (exclusive).
gt (Union[int, float, None]) – Maximum value (exclusive).
exc_msg (str, optional) – Custom message for exceptions. Defaults to None.
lang (str) – Establish the language.
value (str) –
- Raises
Exception – If value is not an int.
- Returns
Value.
- Return type
int
- prototools.validators.validate_name()¶
- prototools.validators.validate_number(value, blank=False, strip=None, n_type='num', min=None, max=None, lt=None, gt=None, exc_msg=None, lang='en')¶
Validate a number.
- Parameters
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
n_type (str) – One of ‘num’, ‘int’, or ‘float’ to validate against, where ‘num’ means int or float.
min (Union[int, float, None]) – Minimum valur (inclusive).
max (Union[int, float, None]) – Maximum value (inclusive).
lt (Union[int, float, None]) – Minimum value (exclusive).
gt (Union[int, float, None]) – Maximum value (exclusive).
exc_msg (str) – Custom message for exceptions. Defaults to None.
lang (str) – Establish the language.
value (str) –
- Raises
ValidatorsException – If value is not a float or int.
- Returns
Value.
- Return type
Union[int, float, str]
- prototools.validators.validate_phone()¶
- prototools.validators.validate_regex(value, regex, flags=0, blank=False, strip=None, allow_regex=None, block_regex=None, exc_msg=None, lang='en')¶
Validate a string using a regular expression.
- Parameters
value (str, optional) – The value being validated.
regex (Union[str, Pattern]) – The regex to use.
flags (int, optional) – The flags to use in re.compile().
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
allow_regex (Optional[Sequence], optional) – If not None, the value is only allowed to match one of the regexes.
block_regex (Optional[Sequence], optional) – If not None, the value is only allowed to match none of the regexes.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not a valid string.
- Returns
The value argument, not value.
- Return type
str
- prototools.validators.validate_roman(value, blank=False, strip=None, allow_regex=None, block_regex=None, exc_msg=None, lang='en')¶
Validate a roman numeral string.
- Parameters
value (str, optional) – The value being validated.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
allow_regex (Optional[Sequence], optional) – If not None, the value is only allowed to match one of the regexes.
block_regex (Optional[Sequence], optional) – If not None, the value is only allowed to match none of the regexes.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not a valid roman numeral string.
- Returns
The value argument, not value.
- Return type
str
- prototools.validators.validate_str(value, blank=False, strip=None, exc_msg=None, lang='en')¶
Validate a str.
- Parameters
value (str, optional) –
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not an str.
- Returns
Value.
- Return type
str
- prototools.validators.validate_time(value, formats=('%H:%M:%S', '%H:%M', '%X'), blank=False, strip=None, exc_msg=None, lang='en')¶
Validate a time.
- Parameters
value (str, optional) – The value being validated.
formats (Union[str, Sequence[str]]) – The formats to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not a valid time.
- Returns
The value argument, not value.
- Return type
str
- prototools.validators.validate_url(value, blank=False, strip=None, allow_regex=None, block_regex=None, exc_msg=None, lang='en')¶
Validate a URL.
- Parameters
value (str, optional) – The value being validated.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
allow_regex (Optional[Sequence], optional) – If not None, the value is only allowed to match one of the regexes.
block_regex (Optional[Sequence], optional) – If not None, the value is only allowed to match none of the regexes.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not a valid URL.
- Returns
The value argument, not value.
- Return type
str
- prototools.validators.validate_yes_no(value, blank=False, strip=None, yes_value='yes', no_value='no', sensitive=False, exc_msg=None, lang='en')¶
Validate a yes/no response.
- Parameters
value (str, optional) – The value being validated.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
yes_value (bool, optional) – Value of affirmative response. Defaults ‘yes’.
no_value (bool, optional) – Value of negative response. Defaults ‘no’.
sensitive (bool, optional) – If True, then the exact case of the option must be entered.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not a yes or no response.
- Returns
The yes_val or no_val argument, not value.
- Return type
str
Module contents¶
- class prototools.Box(style=None, max_dimension=None, color=None, title=None, title_align=None, subtitle=None, subtitle_align=None, text=None, text_align='left', textnl=None, textnl_align='left')¶
Bases:
prototools.components.Component
Optional box section.
- Parameters
style (Style, optional) – Style of the component.
max_dimension (Dimension, optional) – Maximum dimension.
color (Color, optional) – Color of the component.
title (str, optional) – Title of the header.
subtitle (str, optional) – Subtitle of the header.
subtitle_align (str, optional) – Subtitle alignment.
text (str, optional) – Text to be displayed.
text_align (str, optional) – Text alignment.
textnl (str, optional) – Text displayed in newlines.
textnl_align (str, optional) – Text in newlines alignment.
title_align (Optional[str]) –
- Return type
None
Example
>>> t = "Prototools" >>> s = "... faster development" >>> box = Box(title=t, subtitle=s, subtitle_align="right") >>> render(box) ┌─────────────────────────────────────────────────┐ │ │ │ Prototools │ │ │ │ ... faster development │ │ │ └─────────────────────────────────────────────────┘
- generate()¶
Generate the component.
- Return type
Generator[str, str, None]
- class prototools.Canvas(width=40, height=20, bg=None)¶
Bases:
object
Canvas Implementation for draw in terminal
- Atributes:
w (int): Width of the canvas. h (int): Height of the canvas. bg (str): Background of the canvas.
- Parameters
width (int) –
height (int) –
bg (Optional[str]) –
- Return type
None
- card(x, y, w, h, rounded=False)¶
- Parameters
x (int) –
y (int) –
w (int) –
h (int) –
rounded (bool) –
- Return type
None
- clear_canvas()¶
- Return type
None
- draw_figure(figure, char='*')¶
Draws a figure.
- Parameters
figure (object) – A figure.
char (str) –
- Return type
None
- listcard(x, y, list_, rounded=False)¶
- Parameters
x (int) –
y (int) –
list_ (List[str]) –
rounded (bool) –
- Return type
None
- set_defaults(rounded=False)¶
- Parameters
rounded (bool) –
- Return type
None
- set_dimensions(width, height, space=None)¶
- Parameters
width (int) –
height (int) –
space (Optional[int]) –
- Return type
None
- show()¶
- Return type
None
- textcard(x, y, text, rounded=False)¶
Draws a card with text inside.
- Parameters
x (int) – x coordinate of the card.
y (int) – y coordinate of the card.
text (str) – Text to be written inside the card.
rounded (bool, optional) – If True, draws a rounded card. Defaults to False.
- Return type
None
Example
>>> c = Canvas() >>> c.textcard(1, 1, "Prototools", rounded=True) >>> c.show() ╭─────────────╮ │ Prototools │ ╰─────────────╯
- umlcard(x, y, name, attributes, methods, rounded=False)¶
Draws a UML card.
- Parameters
x (int) – The x coordinate of the top left corner of the card.
y (int) – The y coordinate of the top left corner of the card.
name (str) – The name of the class.
attributes (List[str]) – A list of attributes.
methods (List[str]) – A list of methods.
rounded (Optional[bool]) – Whether to draw a rounded card.
- Return type
None
Example
>>> c = Canvas() >>> c.umlcard(0, 0, "Person", ["name"], ["walk", "run"]) >>> c.show() ┌─────────┐ │ Person │ ├─────────┤ │ name │ ├─────────┤ │ walk │ │ run │ └─────────┘
- write_at(x, y, text)¶
- Parameters
x (int) –
y (int) –
text (str) –
- Return type
None
- class prototools.Circle(x: int, y: int, color: Callable, r: int)¶
Bases:
prototools.canvas.FigureDataclass
- Parameters
x (int) –
y (int) –
color (Callable) –
r (int) –
- Return type
None
- color: Callable¶
- get_pos()¶
- Return type
List[Tuple[int, int]]
- r: int¶
- x: int¶
- y: int¶
- class prototools.Counter(function)¶
Bases:
object
Count the number of calls that a function does.
Examples
Scripts:
@Counter def update(): print("Updated!") update() update() update()
Output:
Call 1 of 'update' Updated! Call 2 of 'update' Updated! Call 3 of 'update' Updated!
- Parameters
function (prototools.decorators.F) –
- Return type
None
- class prototools.Dimension(width=0, height=0, dimension=None)¶
Bases:
object
Width and height of a component.
- Parameters
width (int) – Width of the component, in columns.
height (int) – Height of the component, in rows.
dimension (Dimension, optional) – An existing Dimension from which to duplicate the height and width.
- Return type
None
Example
>>> dimension = Dimension(40, 20) >>> dimension.width 40 >>> dimension.height 20 >>> other_dimension = Dimension() >>> other_dimension 0x0 >>> new_dimension = Dimension(dimension=dimension) >>> new_dimension 40x20
- class prototools.Exit(text='Exit', menu=None, color=None)¶
Bases:
prototools.menu.Item
Used to exit the current menu.
- Parameters
text (str) – Text to be shown, defaults ‘Exit’.
menu (Menu, optional) – Menu to which this item belongs.
color (Callable, optional) – Returns a colored string.
- Return type
None
- show(index)¶
Override this method to display appropriate Exit or Return.
- Parameters
index (int) –
- Return type
str
- class prototools.Figure(x, y, color=None)¶
Bases:
object
- Parameters
x (int) –
y (int) –
color (Optional[Callable]) –
- Return type
None
- change_color(color)¶
- Parameters
color (Callable) –
- Return type
None
- get_pos()¶
- Return type
List[Tuple[int, int]]
- move(dx, dy)¶
- Parameters
dx (int) –
dy (int) –
- Return type
None
- class prototools.FigureDataclass(x: int, y: int, color: Callable)¶
Bases:
object
- Parameters
x (int) –
y (int) –
color (Callable) –
- Return type
None
- change_color(color)¶
- Parameters
color (Callable) –
- Return type
None
- color: Callable¶
- get_pos()¶
- Return type
List[Tuple[int, int]]
- move(dx, dy)¶
- Parameters
dx (int) –
dy (int) –
- Return type
None
- x: int¶
- y: int¶
- class prototools.FunctionItem(text, function, args=None, kwargs=None, menu=None, should_exit=False)¶
Bases:
prototools.menu.ExternalItem
A menu item to call a function.
- Parameters
text (str) – The text shown for this menu item.
function (Callable) – The function to be called.
args (List[Any]) – An optional list of arguments to be passed to the function.
kwargs (Dict[Any]) – An optional dictionary of keyword arguments to be passed to the function.
menu (Menu) – The menu to which this item belongs.
should_exit (bool) – Wheter the menu should exit once this item’s action is done.
- Return type
None
- action()¶
This class overrides this method.
- Return type
None
- clean_up()¶
This class overrides this method.
- Return type
None
- get_return()¶
The return value from the function call.
- Return type
Any
- class prototools.Maybe(value=None, containes_value=True)¶
Bases:
object
Example
>>> from prototools.exp import Maybe >>> f = lambda x: x + 3 >>> r = Maybe(2)|f|f >>> print(r) 8
- bind(func)¶
- get()¶
- class prototools.Menu(title='Menu', subtitle=None, prologue_text=None, epilogue_text=None, screen=None, builder=None, show_exit_option=True, exit_option_text='Exit', exit_option_color=None, arrow_keys=False)¶
Bases:
object
Menu that allows the user to select an option.
- Parameters
title (str) – Title of the menu, defaults to “Menu”.
subtitle (str, optional) – Subtitle of the menu.
prologue_text (str, optional) – Text to include in the prologue section of the menu.
epilogue_text (str, optional) – Text to include in the epilogue section of the menu.
show_exit_option (bool) – Specifies wheter this menu should show an exit item by default. Defaults to True.
exit_option_text (str) – Text for the Exit menu item. Defaults to ‘Exit’.
arrow_keys (bool) – Let the user use arrow keys for navigate the menu.
screen (Optional[prototools.components.Screen]) –
builder (Optional[prototools.menu.Builder]) –
exit_option_color (Optional[Callable]) –
- Return type
None
- items¶
The list of Items that the menu will display.
- Type
list
- current_option¶
The currently highlighted menu option.
- Type
int
- selected_option¶
The option that the user has most recently selected.
- Type
int
Example
Script:
from prototools import Menu from prototools.menu import Item menu = Menu() menu.add_item(Item("Item 1")) menu.add_item(Item("Item 2")) menu.run()
Output:
┌─────────────────────────────────────────────────────────┐ │ │ │ Menu │ │ │ │ │ │ 1 - Item 1 │ │ 2 - Item 2 │ │ 3 - Exit │ │ │ │ │ └─────────────────────────────────────────────────────────┘ >
- add_exit()¶
Add the exit item if necessary.
- Returns
True if the exit item was added, False otherwise.
- Return type
bool
- add_item(item)¶
Add an item to the end of the menu before the exit item.
- Parameters
item (Item) – Item to be added.
- Return type
None
- add_items(items)¶
Add items to the end of the menu before the exit item.
- Parameters
items (list) – Items to be added.
- Return type
None
- add_option(text, function, args)¶
Add an option to the menu.
- Parameters
text (str) –
function (Callable) –
args (Any) –
- Return type
None
- add_options(*args)¶
Add the options with their funcionality to the menu.
- Return type
None
- clear_screen()¶
Clear the screen belonging to this menu.
- Return type
None
- property current_item¶
The item corresponding to the menu option that is currently highlighted, or None.
- draw()¶
Refresh the screen and redraw the menu. Should be called whenever something changes that needs to be redraw.
- Return type
None
- exit()¶
Signal the menu to exit, then block until it’s done cleaning up.
- Return type
None
- get_epilogue_text()¶
Get the epilogue text
- Return type
str
- get_input()¶
Can be overriden to change the input method.
- Return type
str
- get_prologue_text()¶
Get the prologue text
- Return type
str
- get_prompt()¶
- Return type
str
- get_subtitle()¶
Get the subtitle
- Return type
str
- get_title()¶
Get the title
- Return type
str
- is_alive()¶
Check the thread condition.
- Returns
True if the thread is still alive; False otherwise.
- Return type
bool
- is_running()¶
Check if the menu has been started and is not paused.
- Returns
- True if the menu is started and hasn’t been paused;
False otherwise.
- Return type
bool
- is_selected_item_exit()¶
- Return type
bool
- join(timeout=None)¶
Should be called at some point after Menu.start() to block until the menu exits.
- Parameters
timeout (int, optional) – How long to wait before timing out.
- Return type
None
- pause()¶
Temporarily pause the menu until resume is called.
- Return type
None
- process_user_input()¶
Get the user input and decides what to do with it.
- Return type
int
- remove_exit()¶
Remove the exit item if necessary.
- Returns
True if the exit item was removed, False otherwise.
- Return type
bool
- remove_item(item)¶
Remove the specified item from the menu.
- Parameters
item (Item) – Item to be removed.
- Returns
True if the item was removed, False otherwise.
- Return type
bool
- resume()¶
Set the currently active menu to this one and resumes it.
- Return type
None
- run(show_exit_option=None)¶
Call start and then inmediately joins.
- Parameters
show_exit_option (bool, optional) – Specify wheter the exit item should be shown, defaults to the value set in the initializer.
- Return type
None
- select()¶
Select the current item and run it.
- Return type
None
- property selected_item¶
The item in items that the user most recently selected, or None.
- set_dimension(width, height)¶
- Parameters
width (int) –
height (int) –
- Return type
None
- set_item_color(color)¶
- Parameters
color (Callable) –
- Return type
None
- set_margins(margins)¶
- Parameters
margins (Tuple[int, int, int, int]) –
- Return type
None
- set_paddings(paddings)¶
- Parameters
paddings (Tuple[int, int, int, int]) –
- Return type
None
- set_prompt(prompt)¶
- Parameters
prompt (str) –
- Return type
None
- set_separators(flag)¶
- Parameters
flag (bool) –
- Return type
None
- set_style(border_style)¶
- Parameters
border_style (str) –
- Return type
None
- set_subtitle_align(align)¶
- Parameters
align (str) –
- Return type
None
- settings(dimension=None, style=None, color=None, options_color=None, separators=None, subtitle_align=None, margins=None, paddings=None, items_paddings=None, footer_padding=None, header_bottom=None)¶
- Parameters
dimension (Optional[Tuple[int, int]]) –
style (Optional[str]) –
color (Optional[Callable]) –
options_color (Optional[Callable]) –
separators (Optional[bool]) –
subtitle_align (Optional[str]) –
margins (Optional[Tuple[int, int, int, int]]) –
paddings (Optional[Tuple[int, int, int, int]]) –
items_paddings (Optional[Tuple[int, int, int, int]]) –
footer_padding (Optional[int]) –
header_bottom (Optional[bool]) –
- Return type
None
- show_header_bottom(flag)¶
- Parameters
flag (bool) –
- Return type
None
- start(show_exit_option=None)¶
Start the menu in a new thread and allow the user to interact with it. The thread is a daemon, so Menu.join() should be called if there is a possibility that the main thread will exit before the menu is done.
- Parameters
show_exit_option (bool, optional) – Specify wheter the exit item should be shown, defaults to the value set in the initializer.
- Return type
None
- wait_for_start(timeout=None)¶
Block until the menu is started.
- Parameters
timeout (int, optional) – How long to wait before timing out.
- Returns
- False if timeout is given and operation times out;
True otherwise.
- Return type
bool
- class prototools.ProtoDB(filename)¶
Bases:
object
Simple and lightweight json database
- Parameters
filename (str) –
- Return type
None
- add(obj, id=None)¶
- Parameters
obj (object) –
id (Optional[str]) –
- Return type
None
- delete(key)¶
- Parameters
key (str) –
- Return type
None
- filename¶
- get(key)¶
- Parameters
key (str) –
- Return type
Union[Dict[str, Union[Dict[str, JSON], List[JSON], int, str, float, bool, Type[None]]], List[Union[Dict[str, JSON], List[JSON], int, str, float, bool, Type[None]]], int, str, float, bool, Type[None]]
- get_all()¶
- Return type
List[Union[Dict[str, Union[Dict[str, JSON], List[JSON], int, str, float, bool, Type[None]]], List[Union[Dict[str, JSON], List[JSON], int, str, float, bool, Type[None]]], int, str, float, bool, Type[None]]]
- get_data()¶
- search(key)¶
- Parameters
key (str) –
- Return type
Generator
- class prototools.ProtoMySQL(**kwargs)¶
Bases:
object
Simple MySQL wrapper
- Return type
None
- add(table, data)¶
- close()¶
- commit()¶
- connect()¶
- delete(table, columns)¶
- get_all(table)¶
- insert(table, data)¶
- query(sql, params=None)¶
Run a raw query
- select(table, q)¶
- update(table, columns, condition)¶
- update_(table, columns, condition)¶
- class prototools.ProtoSqlite(name=None, lang=None, check=None)¶
Bases:
object
Simple SqLite wrapper
- Parameters
name (Optional[str]) –
lang (Optional[str]) –
check (Optional[bool]) –
- Return type
None
- name¶
The name of the database.
- Type
str
- lang¶
The language to translate to.
- Type
str
- check¶
Whether to check if the thread is the same as the one that created the database.
- Type
bool
- add(table, data)¶
- Parameters
table (str) –
data (dict) –
- Return type
None
- check¶
- close()¶
- Return type
None
- conn¶
- create_table(table, columns=None, pk=None)¶
- Parameters
table (str) –
pk (Optional[str]) –
- cursor¶
- delete(table, col, pk)¶
- Parameters
table (str) –
col (str) –
pk (str) –
- execute(sql)¶
- Parameters
sql (str) –
- Return type
None
- get(table, columns, limit=None)¶
- Parameters
table (str) –
columns (str) –
limit (Optional[int]) –
- get_all(table)¶
- Parameters
table (str) –
- Return type
List[Tuple[Any, …]]
- get_last(table, index=None, value=None)¶
- Parameters
table (str) –
index (Optional[Any]) –
value (Optional[Any]) –
- Return type
list
- get_pk(table)¶
- Parameters
table (str) –
- Return type
str
- lang¶
- name¶
- open(name)¶
- Parameters
name (str) –
- Return type
None
- query(sql)¶
- Parameters
sql (str) –
- Return type
None
- select(table, q)¶
- Parameters
table (str) –
q (str) –
- static summary(rows)¶
- Parameters
rows (Any) –
- Return type
Any
- static to_csv(data, filename='output.csv')¶
- Parameters
filename (str) –
- static to_json(data, filename='output.json')¶
- Parameters
filename (str) –
- static to_txt(data, filename='output.txt')¶
- Parameters
filename (str) –
- update(table, columns, condition)¶
- Parameters
table (str) –
columns (str) –
condition (str) –
- Return type
None
- update_(table, columns, condition)¶
- Parameters
table (str) –
columns (str) –
condition (str) –
- Return type
None
- class prototools.RangeDict¶
Bases:
dict
Custom range.
Example
Script:
from prototools import RangeDict table = RangeDict({ (1, 4): "a", (5, 8): "b", (9, 12): "c", }) print(table[3]) # a print(table[6]) # b print(table[11]) # c
- class prototools.Rectangle(x: int, y: int, color: Callable, width: int, height: int)¶
Bases:
prototools.canvas.FigureDataclass
- Parameters
x (int) –
y (int) –
color (Callable) –
width (int) –
height (int) –
- Return type
None
- color: Callable¶
- get_pos()¶
- Return type
List[Tuple[int, int]]
- height: int¶
- width: int¶
- x: int¶
- y: int¶
- class prototools.Screen¶
Bases:
object
Representation of a console screen.
- Return type
None
- width¶
Screen width in columns.
- Type
int
- height¶
Screen height in rows.
- Type
int
Example
>>> screen = Screen()
- static clear()¶
Clear the screen.
- Return type
None
- static flush()¶
Flush any buffered standard output to screen.
- Return type
None
- input(prompt='')¶
Prompt the user for input.
- Parameters
prompt (str) – Message to display as the prompt.
- Returns
User’s input.
- Return type
str
- static printf(*args)¶
Print the arguments to the screen.
- Parameters
*args – Variable length argument list.
args (Any) –
- Return type
None
- static println(*args)¶
Print the arguments to the screen, including an appended newline character.
- Parameters
*args – Variable length argument list.
args (Any) –
- Return type
None
- class prototools.ScreenCanvas¶
Bases:
object
- Return type
None
- add_figures(figures)¶
- Parameters
figures (List[prototools.canvas.FigureDataclass]) –
- Return type
None
- clear_canvas()¶
- clear_screen()¶
- keyboard_press(figure, event)¶
- Parameters
figure (prototools.canvas.FigureDataclass) –
event (str) –
- Return type
None
- move(figure)¶
- Return type
None
- refresh()¶
- class prototools.Style(margin=None, padding=None, border_type=None)¶
Bases:
object
Specify all menu styling (margins, paddings and borders).
- Parameters
- Return type
None
Example
>>> style = Style() >>> style.margin.left 2 >>> style.border.type light >>> style.paddin.bottom 1
Bases:
prototools.menu.Item
A menu item to open a submenu.
- Parameters
- Return type
None
This class overrides this method
- Return type
None
This class overrides this method
- Return type
None
Return the value in the submenu
- Return type
Any
Unwrap the submenu variable in case it’s a reference to a method
- Return type
Any
Set the menu of this item.
Should be used instead of directly accessing the menu attribute for this class.
- Parameters
menu (Menu) – The menu.
- Return type
None
This class overrides this method
- Return type
None
- class prototools.Triangle(x: int, y: int, color: Callable, side: int)¶
Bases:
prototools.canvas.FigureDataclass
- Parameters
x (int) –
y (int) –
color (Callable) –
side (int) –
- Return type
None
- color: Callable¶
- get_pos()¶
- Return type
List[Tuple[int, int]]
- side: int¶
- x: int¶
- y: int¶
- prototools.ask_to_finish(prompt='_default', yes='_default', input_prompt='> ', lang='en')¶
Ask the user to finish a loop.
- Parameters
prompt (str, optional) – Prompt the user to finish or not the loop.
yes (str, optional) – Value of affirmative response.
lang (str, optional) – Establish the language.
input_prompt (Optional[str]) –
- Returns
True if the user wants to continue, False otherwise.
- Return type
bool
- prototools.banner(title, width=<class 'int'>, style=None)¶
Print a banner.
- Parameters
Title (str) – Title of the banner.
width (int) – Ancho del banner.
style (str, optional) – Border style.
title (str) –
Example
Script:
@banner("ProtoTools", 12) def mensaje(): return None mensaje()
Output:
══════════════════ ProtoTools ══════════════════
- prototools.black(text)¶
- prototools.blue(text)¶
- prototools.bool_input(prompt='', true_value=None, false_value=None, sensitive=False, default=None, blank=False, strip=None, timeout=None, limit=None, function=None, validation=None, lang='en')¶
Prompts the user to enter a True/False response.
- Parameters
prompt (str, optional) – Prompts the user to enter input.
true_value (bool, optional) – Value of affirmative response. Defaults ‘yes’.
no_value (bool, optional) – Value of negative response. Defaults ‘no’.
sensitive (bool, optional) – If True, then the exact case of the option must be entered.
default (Any, optional) – Default value to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
lang (str) – Establish the language.
false_value (Optional[str]) –
- Returns
Boolean value.
- Return type
bool
>>> s = bool_input() yes yes is not a valid yes/no response t >>> s True
- prototools.build_tree(root, curr_index, include_index=False, delimiter='-')¶
- Parameters
root (Optional[prototools.tree.Node]) –
curr_index (int) –
include_index (bool) –
delimiter (str) –
- Return type
Tuple[List[str], int, int, int]
- prototools.choice_input(choices, sensitive=False, prompt='_default', default=None, blank=False, strip=None, timeout=None, limit=None, function=None, validation=None, lang='en')¶
Prompt the user to enter one of the provieded choices.
- Parameters
choices (Sequence[str]) – Sequence of strings, one of which the user must enter.
sensitive (bool, optional) – If True, then the exact case of the option must be entered.
prompt (str, optional) – Prompts the user to enter input.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
lang (str) – Establish the language.
default (Optional[Any]) –
- Raises
Exception – If value is not one of the values in choices.
- Returns
The selected choice as a string.
- Return type
str
>>> options = ("a", "b", "c") >>> s = choice_input(options) Select one of: a, b, c 1 1 is not a valid choice Select one of: a, b, c a >>> s 'a'
- prototools.chunker(sequence, size)¶
Simple chunker.
- Returns
A generator.
- Return type
Generator
Example
>>> list(chunker(list(range(10)), 3)) [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
- prototools.clear_screen()¶
Clear the screen.
- Return type
None
- prototools.compose(*functions)¶
Compose functions.
- Parameters
functions (ComposableFunction) – Bunch of functions.
- Returns
Composed function.
- Return type
Callable
Example
>>> def f(x): ... return x * 2 >>> def g(x): ... return x + 1 >>> h = compose(f, g) >>> h(3) 7 >>> h(4) 9
- prototools.create_colors(opts=(), **kwargs)¶
- prototools.create_f(name, args, body)¶
Create a function.
- Parameters
name (str) – Name of the function.
args (Any) – Arguments.
unique (str) – Body of the function.
body (str) –
- Returns
Function.
- Return type
Callable
Example
Script:
t = ''' for i in range(3): r = (x + y) * i print(f"({x} + {y}) * {i} = {r}") ''' f = create_f("g", "x=2 y=3", t) f()
Output:
(2 + 3) * 0 = 0 (2 + 3) * 1 = 5 (2 + 3) * 2 = 10
- prototools.custom_input(prefix='', suffix='')¶
Custom input with a prefix string and a suffix string. User’s input is located in between prefix and suffix.
- Parameters
prefix (str) – Prefix word before user input.
suffix (str) – Suffix word after user input.
- Returns
User input.
- Return type
str
>>> s = custom_input("Age: ", " years old.") Age: __ years old. Age: 18 years old. >>> s 18
- prototools.cyan(text)¶
- prototools.date_input(prompt='', formats=None, default=None, blank=False, strip=None, timeout=None, limit=None, function=None, validation=None, lang='en')¶
Prompt the user to enter a date.
- Parameters
prompt (str, optional) – Prompts the user to enter input.
formats (Union[str, Sequence[str]], optional) – Date formats.
default (Any, optional) – Default value to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
lang (str) – Establish the language.
- Returns
The date.
- Return type
str
>>> s = date_input() 12-12-2021 12-12-2021 is not a valid date 12/12/2021 >>> s 2021/12/12 >>> type(s) <class 'datetime.date'>
- prototools.date_input_dmy(prompt='', formats=None, to_str=True, default=None, blank=False, strip=None, timeout=None, limit=None, function=None, validation=None, lang='en')¶
Prompt the user to enter a date.
- Parameters
prompt (str, optional) – Prompts the user to enter input.
formats (Union[str, Sequence[str]], optional) – Date formats.
to_str (bool, optional) – If True, the date is returned as a string.
default (Any, optional) – Default value to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
lang (str) – Establish the language.
- Returns
The date.
- Return type
str
>>> s = date_input() 12-12-2021 12-12-2021 is not a valid date 12/12/2021 >>> s 2021/12/12 >>> type(s) <class 'datetime.date'>
- prototools.debug(function)¶
Print the decorated function signature and its return value.
Example
Script:
@debug def say_hi(name): return f"Hi {name}!" say_hi("ProtoTools")
Output:
Calling: say_hi('ProtoTools') 'say_hi' returned 'Hi ProtoTools!'
- Parameters
function (prototools.decorators.F) –
- Return type
prototools.decorators.F
- prototools.email_input(prompt='', default=None, blank=False, strip=None, timeout=None, limit=None, allow_regex=None, block_regex=None, function=None, validation=None, lang='en')¶
Prompt the user to enter an email.
- Parameters
prompt (str, optional) – Prompts the user to enter input.
default (Any, optional) – Default value to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
allow_regex (Sequence, optional) – Regex to allow.
block_regex (Sequence, optional) – Regex to block.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
lang (str) – Establish the language.
- Returns
The email.
- Return type
str
>>> email = email_input() john@doe.com >>> email john@doe.com >>> email = email_input() ayudaenpython ayudaenpython is not a valid email ayudaen@python.com >>> email ayudaen@python
- prototools.flatten(list_of_lists)¶
Return an iterator flattening one level of nesting in a list of lists.
Example
>>> list(flatten([[0, 1], [2, 3]])) [0, 1, 2, 3]
- prototools.float_input(prompt='', default=None, blank=False, strip=None, timeout=None, limit=None, function=None, validation=None, min=None, max=None, lt=None, gt=None, lang='en')¶
Prompt the user to enter a floating point number.
- Parameters
prompt (str, optional) – Prompts the user to enter input.
default (Any, optional) – Default value to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
min (Union[int, float, None]) – Minimum valur (inclusive).
max (Union[int, float, None]) – Maximum value (inclusive).
lt (Union[int, float, None]) – Minimum value (exclusive).
gt (Union[int, float, None]) – Maximum value (exclusive).
lang (str) – Establish the language.
- Raises
Exception – If value is not a float.
- Returns
The number as a float.
- Return type
int
>>> from prototools.inputs import float_input >>> number = float_input() 6 >>> number 6.0 >>> type(number) <class 'float'>
- prototools.get_data(filename, mode='lines', encoding='utf-8')¶
Get data.
- Parameters
filename (str) – The name of the file to read.
mode (str, optional) – The mode to read the file. Options are: - “lines” (default): Returns a list of lines. - “text”: Returns the entire content as a single string. - “json”: Returns the parsed JSON data.
encoding (str, optional) – The encoding used to read the file. Default is “utf-8”.
- Returns
The file content based on the selected mode.
- Return type
Union[List[str], str, Any]
- Raises
ValueError – If the specified mode is not supported.
Example
>>> # Reading lines from a text file >>> lines = get_data("data.txt") >>> print(lines) ['line 1', 'line 2', 'line 3']
>>> # Reading the entire content as a single string >>> text = get_data("data.txt", mode="text") >>> print(text) 'line 1\nline 2\nline 3'
>>> # Reading and parsing a JSON file >>> data = get_data("data.json", mode="json") >>> print(data) {'key1': 'value1', 'key2': 'value2'}
- prototools.green(text)¶
- prototools.grouper(iterable, n, fillvalue=None)¶
Collect data into fixed-length chunks or blocks.
Example
>>> list(grouper('ABCDEFG', 3, 'x')) [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'x', 'x')]
- prototools.handle_error(_function=None, *, message='Error:')¶
Handles exceptions.
- Parameters
message (str) – Custom message.
_function (Optional[prototools.decorators.F]) –
Example
Script:
@handle_error def f(n): print(int(n)) @handle_error(message="E>") def g(n): print(int(n)) f("s") g("s")
Output:
Error: invalid literal for int() with base 10: 's' E> invalid literal for int() with base 10: 's'
- prototools.hide_cursor()¶
Hide console cursor.
- Return type
None
- prototools.inject(f, _function=None, *, values=None, after=True)¶
Inject a function into another function.
- Parameters
f (Callable) – The function to inject.
values (List[Any]) – Function’s arguments.
after (bool) – If True, inject after the function; otherwise, inject before the function.
_function (Optional[prototools.decorators.F]) –
Example
Script:
def f(s): print(s) @inject(f, values=("Ending",)) @inject(f, values=("Starting",), after=False) def g(n): print(n**2) g(2)
Output:
Starting 4 Ending
- prototools.int_input(prompt='', default=None, blank=False, strip=None, timeout=None, limit=None, function=None, validation=None, min=None, max=None, lt=None, gt=None, lang='en')¶
Prompt the user to enter an integer number.
- Parameters
prompt (str, optional) – Prompts the user to enter input.
default (Any, optional) – Default value to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
min (Union[int, float, None]) – Minimum valur (inclusive).
max (Union[int, float, None]) – Maximum value (inclusive).
lt (Union[int, float, None]) – Minimum value (exclusive).
gt (Union[int, float, None]) – Maximum value (exclusive).
lang (str) – Establish the language.
- Raises
Exception – If value is not an int.
- Returns
The number as an int.
- Return type
int
>>> from prototools.inputs import int_input >>> number = int_input() 6.0 >>> number 6 >>> type(number) <class 'int'>
- prototools.magenta(text)¶
- prototools.main_loop(function, args=None, kwargs=None, validation=None, custom_function=None, lang='en')¶
Call a function until validation is False.
- Parameters
function (Callable) – Function to iterate.
args (Optional[List[Any]]) – Arguments to pass to function.
kwargs (Optional[Dict[Any, None]]) – Keyword arguments to pass to function.
validation (Callable) – If False, ends the loop.
custom_function (Callable) – Function that determines if the loop should continue. If False, ends the loop.
lang (Optional[str]) –
- Returns
Result of function.
- Return type
Union[Any, None]
- prototools.make_grid(iterable, group, function=<class 'str'>, reversed=True)¶
Generates a grid.
- Parameters
iterable (Iterable[Any]) – Iterable.
function (Callable) – Function to apply to each element.
group (int) – Group size.
reversed (bool, optional) – If True, the grid is reversed. Defaults to False.
- Returns
Grid.
- Return type
List[List[Any]]
Example
>>> make_grid(range(1, 10), 3) [('7', '8', '9'), ('4', '5', '6'), ('1', '2', '3')]
- prototools.matrix(i, j, rng=None, char=None, rnd=False, precision=None)¶
Create a matrix.
- Parameters
i (int) – Number of rows.
j (int) – Number of columns.
rng (Tuple[int, int], optional) – Range of the matrix.
char (str, optional) – Character to fill the matrix.
rnd (bool, optional) – Randomize the matrix.
precision (int, optional) – Number of decimals.
- Returns
Matrix.
- Return type
List[List[float]]
Example
>>> matrix(3, 3) [[1, 1, 1], [0, 1, 0], [1, 0, 0]]
- prototools.matrix_panel(text, fg=None, bg=None)¶
Example
>>> matrix_panel("ABC") ░░██████░░░░████████░░░░░░████████░░ ██░░░░░░██░░██░░░░░░██░░██░░░░░░░░░░ ██░░░░░░██░░██░░░░░░██░░██░░░░░░░░░░ ██░░░░░░██░░████████░░░░██░░░░░░░░░░ ██████████░░██░░░░░░██░░██░░░░░░░░░░ ██░░░░░░██░░██░░░░░░██░░██░░░░░░░░░░ ██░░░░░░██░░████████░░░░░░████████░░
- Parameters
text (str) –
fg (Optional[str]) –
bg (Optional[str]) –
- Return type
None
Prompt the user to enter one of the provieded choices. Also displays a small menu with bulleted, numbered, or lettered options.
- Parameters
choices (Sequence[str]) – Sequence of strings, one of which the user must enter.
numbers (bool, optional) – If True, it will also accept a number as a choice.
letters (bool, optional) – If True, it will also accept a letter as a choice.
sensitive (bool, optional) – If True, then the exact case of the option must be entered.
prompt (str, optional) – Prompts the user to enter input.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
lang (str) – Establish the language.
default (Optional[Any]) –
- Raises
Exception – If value is not one of the values in choices.
- Returns
The selected choice as a string.
- Return type
str
>>> options = ("a", "b", "c") >>> s = menu_input(options) Select one of the following: * a * b * c 1 1 is not a valid choice Select one of the following: * a * b * c a >>> s 'a'
- prototools.mvc_launcher(mode, model, cli, gui, web, name=None, url='http://127.0.0.1:5000/')¶
A simple MVC Launcher.
- Parameters
mode (str) – Mode.
model (object) – Model.
cli (Tuple[object, object]) – CLI controller, CLI view.
gui (Tuple[object, object]) – GUI controller, GUI view.
web (Tuple[object, object]) – Web controller, Web view.
name (str, optional) – Name of the application. Defaults to None.
url (str, optional) – URL. Defaults to “http://127.0.0.1:5000/”.
- Return type
None
- prototools.mvc_setup(mode, cli, gui, web, web_name='WEB', cli_name='CLI', gui_name='GUI')¶
Setup the MVC architecture.
- Parameters
mode (str) – Mode.
cli (Tuple[object, object]) –
gui (Tuple[object, object]) – GUI.
web (Tuple[object, object]) – WEB.
web_name (str, optional) – WEB name.
cli_name (str, optional) – CLI name.
gui_name (str, optional) – GUI name.
- Return type
Tuple[bool, Optional[object], Optional[object]]
- prototools.obsolete(message)¶
Decorate an obsolote function and sends a warning message.
Example
Script:
@obsolete("use 'g()' instead") def f(): return "version 1.0" print(f())
Output:
DeprecationWarning: Function 'f' is obsolete!, use 'g()' instead
- Parameters
message (str) –
- Return type
None
- prototools.partition(pred, iterable)¶
Use a predicate to partition entries into false entries and true entries
- prototools.password_input(prompt='')¶
Prompts the user to enter a password. Mask characters will be displayed instead of the actual characters.
- Parameters
prompt (str) –
- prototools.print_chars(line_length=32, max_char=131072)¶
Print all chars in the terminal, to help you find that cool one to put in your customized spinner or bar. Also useful to determine if your terminal do support them.
- Parameters
line_length (int) – the desired characters per line
max_char (int) – the last character in the unicode table to show this goes up to 0x10ffff, but after the default value it seems to return only question marks, increase it if would like to see more.
- Return type
None
- prototools.progress_bar(count, total, width=40, prefix='', spinbar=False, ss=<itertools.cycle object>)¶
Display a progress bar.
- Parameters
count (int) – Current count.
total (int) – Total count.
width (int, optional) – Width of the progress bar.
prefix (str, optional) – Prefix of the progress bar.
spinbar (bool, optional) – Display a spinner.
- Return type
None
- prototools.progressbar(iterable, width=40, prefix='', spinvar=True, spinvar_color=None, bg=None, fg=None, per=True, units=True)¶
Display a progress bar.
- Parameters
iterable (Iterable) – Iterable to iterate.
width (int, optional) – Width of the progress bar.
prefix (str, optional) – Prefix of the progress bar.
spinvar (bool, optional) – Display a spinner.
per (bool, optional) – Display the percentage.
units (bool, optional) – Display the units.
spinvar_color (Optional[Callable]) –
bg (Optional[Callable]) –
fg (Optional[Callable]) –
- Return type
Generator
Example
>>> for _ in progressbar(range(50)): ... [x for x in range(1_000_000)] ████████████████████████████████░░░░░░░░| 41/50 [82]% ▃▁▃
- prototools.red(text)¶
- prototools.register(function)¶
Register a function as a plug-in.
Example
Script:
from prototools.decorators import PLUGINS, register @register def f(): pass print(PLUGINS)
OUTPUT:
{'f': <function f at 0x00000258176C64C8>}
- Parameters
function (prototools.decorators.F) –
- Return type
prototools.decorators.F
- prototools.render(component)¶
Render a component.
- Parameters
component (Component) – Component to be rendered.
- Return type
None
- prototools.repeat(_function=None, *, n=2)¶
Repeat ‘n’ times the decorated function.
- Parameters
n (int) – Number of repetitions.
_function (Optional[prototools.decorators.F]) –
Example
Script:
@repeat(4) def say_hi(name): print(f"Hi {name}!") say_hi("ProtoTools")
Output:
Hi ProtoTools! Hi ProtoTools! Hi ProtoTools! Hi ProtoTools!
- prototools.retrieve_argname(var)¶
Retrieve the name of the argument passed to the function.
- Parameters
var (object) – The argument passed to the function.
- Returns
The name of the argument.
- Return type
str
Example
>>> def foo(a): n = retrieve_argname(a) ... return f"{n}'s value is {a}" ... >>> x = 42 >>> foo(x) 'x's value is 42
- prototools.retrive_varname(var)¶
- prototools.retry(_function=None, *, tries=3, default=None)¶
Retry a function if it raises an exception.
- Parameters
tries (int) – Number of tries.
defualt (Any, optional) – Default value.
_function (Optional[prototools.decorators.F]) –
default (Optional[Any]) –
Example
Script:
from random import randint @retry(tries=3, default=0) def f(): rnd = randint(1, 10) if rnd > 5: return rnd else: raise ValueError("Random number is less than 5") print(f())
Output:
Retrying (1): Random number is less than 5 Retrying (2): Random number is less than 5 8
- prototools.return_names(name=None)¶
- prototools.secret_message(message='prototools 0.1.22')¶
Generates code that has a secret message when executed. To used it, copy the generated code and execute it in another file.
- Parameters
message (str, optional) – Secret message.
- Returns
Code.
- Return type
str
Example
>>> secret_message("Hello World!")
Output:
import random random.seed(69420) print(''.join(chr(random.randrange(256) ^ c) for c in bytes.fromhex( 'EA8760D97CD68CB754E490D68D376C1997BBF9BD363BCE05CD85' ) if random.randrange(2)) )
- prototools.show_cols(data, chars=None, fg=None, bg=None)¶
Prints columns representing the data.
- Parameters
data (List[float]) – Data to be shown.
chars (str, optional) – Character to be used. Defaults to ‘Full Block’
fg (Callable, optional) – Foreground color. Defaults to None.
bg (Callable, optional) – Background color. Defaults to None.
- Return type
str
>>> data = [4, 3, 0, 2, 1] >>> print(show_cols(data)) █ ░ ░ ░ ░ █ █ ░ ░ ░ █ █ ░ █ ░ █ █ ░ █ █
- prototools.show_cursor()¶
Show console cursor.
- Return type
None
- prototools.show_matrix(m, width=4, style=None, borderless=False, index=False, neg_index=False, sep=1, color=None)¶
Prints a matrix.
- Parameters
m (List[List[float]]) – Matrix to be shown.
width (int, optional) – Width of the matrix. Defaults to 4.
style (str, optional) – Style of the matrix. Defaults to None.
borderless (bool, optional) – Show the matrix without borders. Defaults to False.
index (bool, optional) – Show the index of the matrix. Defaults to False.
neg_index (bool, optional) – Show the negative index of the matrix.
sep (int, optional) – Separation between the columns. Defaults to 1.
color (Callable, optional) – Color of the matrix. Defaults to None.
- Return type
None
>>> matrix = [[1, 2, 3], [4, 5, 6]] >>> show_matrix(matrix) ┌────┬────┬────┐ │ 1 │ 2 │ 3 │ ├────┼────┼────┤ │ 4 │ 5 │ 6 │ └────┴────┴────┘ >>> show_matrix(matrix, borderless=True, width=1) 1 2 3 4 5 6
- prototools.singleton(cls)¶
Make a class a Singleton class (only one instance).
Example
Script:
@singleton class T: pass
>>> a = T() >>> b = T() >>> id(a) 2031647265608 >>> id(b) 2031647265608 >>> a is b True
- prototools.slow_down(_function=None, *, seconds=1)¶
Sleep ‘n’ seconds before calling the function.
Example
Script:
@slow_down(seconds=2) def f(n): if n < 1: prin("End!") else: print(n) f(n-1) f(3)
Output:
3 2 1 End!
- Parameters
_function (Optional[prototools.decorators.F]) –
seconds (int) –
- prototools.str_input(prompt='', default=None, blank=False, strip=None, timeout=None, limit=None, function=None, validation=None, lang='en')¶
Prompt the user to enter any string.
- Parameters
prompt (str, optional) – Prompts the user to enter input.
default (Any, optional) – Default value to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
lang (str) – Establish the language.
- Raises
Exception – If value is not an str.
- Returns
The string.
- Return type
str
>>> s = str_input("Enter a string: ") Enter a string: prototools >>> s 'prototools'
- prototools.strip_ansi(string)¶
Strips ansi string.
- Parameters
string (str) –
- prototools.strip_ansi_width(string)¶
Gets ansi string widht.
- Parameters
s (str) – String of characters.
string (str) –
- Returns
Width of string (stripped ansi).
- Return type
int
- prototools.strip_string(value, strip)¶
Strips a string, the argument defines the behaviour.
- Parameters
value (str) – String of characters to be stripped.
strip (Union[None, str, bool]) – If None, whitespace is stripped; if is a string, the characters in the string are stripped; if False, nothing is stripped.
- Returns
Stripped version of value.
- Return type
str
- prototools.tabulate(data, headers=None, headless=False, inner=False, style=None, border_type=None, align=None, color=None, title=None)¶
Display data in a table.
- Parameters
data (Sequence) – Data to be shown.
headers (List[str], optional) – Optional header of the table.
headless (bool, optional) – If True, the data has no header. If False, the first row of the data becomes the header. Defaults False.
inner (bool, optional) – If True, the inner border is shown. Defaults False.
style (Tuple[int, ...], optional) – Tuple of int representing the padding left, padding right, margin left and margin right.
border_type (str, optional) – Type of the border.
align (str, optional) – Alignment can be left, center or right.
color (Optional[Callable[[str], str]]) –
title (Optional[str]) –
- Returns
Data ready to be printed.
- Return type
str
TODO: add example
- prototools.tail(n, iterable)¶
Return an iterator over the last n items of iterable.
Example
>>> t = tail(3, 'ABCDEFG') >>> list(t) ['E', 'F', 'G']
- prototools.terminal_size()¶
Returns the width of the terminal.
- Returns
Terminal’s widht.
- Return type
int
- prototools.text_align(text, width=80, style=None, align='right')¶
Similar to Python rjust, ljust and center methods.
- Parameters
text (str) – Text.
width (int) – Width.
style (str, optional) – Border style.
align (str, optional) – Alignment of the text.
- Return type
None
Example
>>> text_align("Test") ======= Test =======
- prototools.textbox(text, width=80, style=None, align='center', bcolor=None, ml=0, light=True)¶
Draw a box with a text in it.
- Parameters
text (str) – Text.
width (int) – Width.
style (str, optional) – Border style.
align (str, optional) – Alignment of the text.
bcolor (str, optional) – Border color.
ml (int, optional) – Margin left.
light (bool, optional) – Adds padding top and bottom.
- Returns
Box.
- Return type
str
Example
>>> textbox(green("ProtoTools"), width=30, bcolor="red") ┌────────────────────────────┐ │ ProtoTools │ └────────────────────────────┘
- prototools.time_functions(functions, args=(), kwargs=None, number=1000000, lang='en')¶
Time the execution of multiple functions.
- Parameters
functions (Union[List[Callable], Dict[str, Callable]]) – Functions to be timed. Can be a list of functions or a dictionary with function names as keys.
args (Optional[Tuple[Any, ...]]) – Positional arguments to pass to the functions.
kwargs (Optional[Dict[str, Any]]) – Keyword arguments to pass to the functions.
setup (str, optional) – Setup code for necessary imports. Defaults to an empty string.
globals (dict, optional) – Global namespace. Defaults to None.
number (int, optional) – Number of iterations for timing. Defaults to 1,000,000.
lang (str, optional) – Language for the output. Defaults to “en”.
- Return type
None
Example
>>> def f(n): ... return [x for x in range(n)] >>> def g(n): ... r = [] ... for x in range(n): ... r.append(x) ... return r >>> time_functions([f, g], args=(100,))
- Output:
‘f’ took 0.255712 secs ‘g’ took 0.421514 secs
- prototools.time_functions_custom(functions, args, setup=None, globals=None, number=1000000, lang='en')¶
Time functions.
- Parameters
functions (Any) – Tuple or Dictionary of functions to be timed.
args (Tuple[Any]) – Tuple of arguments.
setup (str, optional) – Setup code to import needed modules.
globals (Callable, optional) – Current globla namespace.
number (int, optional) – Number of iterations.
lang (str, optional) – Establish the language.
- Return type
None
Example
Script:
def f(n): return [x for x in range(n)] def g(n): r = [] for x in range(n): r.append(x) return r if __name__ == "__main__": fs = {"f": f, "g": g} time_functions_custom(fs, args=(100), globals=globals())
Output:
'f' took 2.2157 secs 'g' took 6.7192 secs
- prototools.time_functions_globals(functions, args=(), kwargs=None, setup='', globals=None, number=1000000, lang='en')¶
Time the execution of multiple functions.
- Parameters
functions (Union[List[Callable], Dict[str, Callable]]) – Functions to be timed. Can be a list of functions or a dictionary with function names as keys.
args (Optional[Tuple[Any, ...]]) – Positional arguments to pass to the functions.
kwargs (Optional[Dict[str, Any]]) – Keyword arguments to pass to the functions.
setup (str, optional) – Setup code for necessary imports. Defaults to an empty string.
globals (dict, optional) – Global namespace. Defaults to None.
number (int, optional) – Number of iterations for timing. Defaults to 1,000,000.
lang (str, optional) – Language for the output. Defaults to “en”.
- Return type
None
Example
>>> def f(n): ... return [x for x in range(n)] >>> def g(n): ... r = [] ... for x in range(n): ... r.append(x) ... return r >>> time_functions_globals([f, g], args=(100,), globals=globals())
- Output:
‘f’ took 0.255712 secs ‘g’ took 0.421514 secs
- prototools.time_input(prompt='', formats=('%H:%M:%S', '%H:%M', '%X'), default=None, blank=False, strip=None, timeout=None, limit=None, function=None, validation=None, lang='en')¶
Prompt the user to enter a time.
- Parameters
prompt (str, optional) – Prompts the user to enter input.
formats (Union[str, Sequence[str]], optional) – Time formats.
default (Any, optional) – Default value to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
lang (str) – Establish the language.
- Returns
The time.
- Return type
str
>>> s = time_input() 1200 1200 is not a valid time 12:00 >>> s 12:00:00 >>> type(s) <class 'datetime.time'>
- prototools.timer(_function=None, *, fg=None, bg=None)¶
Print the runtime of the decorated function.
- Parameters
fg (str, optional) – Foreground color.
bg (str, optional) – Background color.
_function (Optional[prototools.decorators.F]) –
Example
Script:
@timer def f(n): for _ in range(n): sum([x**2 for x in range(10_000)]) f(10)
Output:
Finished 'f' in 0.028945 secs
- prototools.validate_bool(value, blank=False, strip=None, true_value='True', false_value='False', sensitive=False, exc_msg=None, lang='en')¶
Validate a yes/no response.
- Parameters
value (str, optional) – The value being validated.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
true_value (bool, optional) – Value of True. Defaults ‘True’.
false_value (bool, optional) – Value of False. Defaults ‘False’.
sensitive (bool, optional) – If True, then the exact case of the option must be entered.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not a “True” or “False” response.
- Returns
The true_value or false_value argument, not value.
- Return type
str
- prototools.validate_choice(value, choices, blank=False, strip=None, numbers=False, letters=False, sensitive=False, exc_msg=None, lang='en')¶
Validate a choice.
- Parameters
value (str, optional) – The value being validated.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
choices (Sequence[Any]) – Sequence of choices.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
numbers (bool, optional) – If True, it will also accept a number as a choice.
letters (bool, optional) – If True, it will also accept a letter as a choice.
sensitive (bool, optional) – If True, then the exact case of the option must be entered.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not one of the values in choices.
- Returns
The selected choice.
- Return type
str
- prototools.validate_date(value, formats=('%Y/%m/%d', '%y/%m/%d', '%m/%d/%Y', '%m/%d/%y', '%x'), blank=False, strip=None, exc_msg=None, lang='en')¶
Validate a date.
- Parameters
value (str, optional) – The value being validated.
formats (Union[str, Sequence[str]]) – The formats to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not a valid date.
- Returns
The value argument, not value.
- Return type
str
- prototools.validate_datetime(value, formats=('%Y/%m/%d %H:%M:%S', '%y/%m/%d %H:%M:%S', '%m/%d/%Y %H:%M:%S', '%m/%d/%y %H:%M:%S', '%x %H:%M:%S', '%Y/%m/%d %H:%M', '%y/%m/%d %H:%M', '%m/%d/%Y %H:%M', '%m/%d/%y %H:%M', '%x %H:%M', '%Y/%m/%d %H:%M:%S', '%y/%m/%d %H:%M:%S', '%m/%d/%Y %H:%M:%S', '%m/%d/%y %H:%M:%S', '%x %H:%M:%S'), blank=False, strip=None, exc_msg=None, lang='en')¶
Validate a datetime.
- Parameters
value (str, optional) – The value being validated.
formats (Union[str, Sequence[str]]) – The formats to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not a valid datetime.
- Returns
The value argument, not value.
- Return type
str
- prototools.validate_email(value, blank=False, strip=None, allow_regex=None, block_regex=None, exc_msg=None, lang='en')¶
Validate an email address.
- Parameters
value (str, optional) – The value being validated.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
allow_regex (Optional[Sequence], optional) – If not None, the value is only allowed to match one of the regexes.
block_regex (Optional[Sequence], optional) – If not None, the value is only allowed to match none of the regexes.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not a valid email address.
- Returns
The value argument, not value.
- Return type
str
- prototools.validate_float(value, blank=False, strip=None, min=None, max=None, lt=None, gt=None, exc_msg=None, lang='en')¶
Validate a float.
- Parameters
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
number_type (str) – One of ‘num’, ‘int’, or ‘float’ to validate against, where ‘num’ means int or float.
min (Union[int, float, None]) – Minimum valur (inclusive).
max (Union[int, float, None]) – Maximum value (inclusive).
lt (Union[int, float, None]) – Minimum value (exclusive).
gt (Union[int, float, None]) – Maximum value (exclusive).
exc_msg (str, optional) – Custom message for exceptions. Defaults to None.
lang (str) – Establish the language.
value (str) –
- Raises
Exception – If value is not a float.
- Returns
Value.
- Return type
float
- prototools.validate_int(value, blank=False, strip=None, min=None, max=None, lt=None, gt=None, exc_msg=None, lang='en')¶
Validate an integer.
- Parameters
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
number_type (str) – One of ‘num’, ‘int’, or ‘float’ to validate against, where ‘num’ means int or float.
min (Union[int, float, None]) – Minimum valur (inclusive).
max (Union[int, float, None]) – Maximum value (inclusive).
lt (Union[int, float, None]) – Minimum value (exclusive).
gt (Union[int, float, None]) – Maximum value (exclusive).
exc_msg (str, optional) – Custom message for exceptions. Defaults to None.
lang (str) – Establish the language.
value (str) –
- Raises
Exception – If value is not an int.
- Returns
Value.
- Return type
int
- prototools.validate_number(value, blank=False, strip=None, n_type='num', min=None, max=None, lt=None, gt=None, exc_msg=None, lang='en')¶
Validate a number.
- Parameters
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
n_type (str) – One of ‘num’, ‘int’, or ‘float’ to validate against, where ‘num’ means int or float.
min (Union[int, float, None]) – Minimum valur (inclusive).
max (Union[int, float, None]) – Maximum value (inclusive).
lt (Union[int, float, None]) – Minimum value (exclusive).
gt (Union[int, float, None]) – Maximum value (exclusive).
exc_msg (str) – Custom message for exceptions. Defaults to None.
lang (str) – Establish the language.
value (str) –
- Raises
ValidatorsException – If value is not a float or int.
- Returns
Value.
- Return type
Union[int, float, str]
- prototools.validate_regex(value, regex, flags=0, blank=False, strip=None, allow_regex=None, block_regex=None, exc_msg=None, lang='en')¶
Validate a string using a regular expression.
- Parameters
value (str, optional) – The value being validated.
regex (Union[str, Pattern]) – The regex to use.
flags (int, optional) – The flags to use in re.compile().
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
allow_regex (Optional[Sequence], optional) – If not None, the value is only allowed to match one of the regexes.
block_regex (Optional[Sequence], optional) – If not None, the value is only allowed to match none of the regexes.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not a valid string.
- Returns
The value argument, not value.
- Return type
str
- prototools.validate_roman(value, blank=False, strip=None, allow_regex=None, block_regex=None, exc_msg=None, lang='en')¶
Validate a roman numeral string.
- Parameters
value (str, optional) – The value being validated.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
allow_regex (Optional[Sequence], optional) – If not None, the value is only allowed to match one of the regexes.
block_regex (Optional[Sequence], optional) – If not None, the value is only allowed to match none of the regexes.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not a valid roman numeral string.
- Returns
The value argument, not value.
- Return type
str
- prototools.validate_str(value, blank=False, strip=None, exc_msg=None, lang='en')¶
Validate a str.
- Parameters
value (str, optional) –
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not an str.
- Returns
Value.
- Return type
str
- prototools.validate_time(value, formats=('%H:%M:%S', '%H:%M', '%X'), blank=False, strip=None, exc_msg=None, lang='en')¶
Validate a time.
- Parameters
value (str, optional) – The value being validated.
formats (Union[str, Sequence[str]]) – The formats to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not a valid time.
- Returns
The value argument, not value.
- Return type
str
- prototools.validate_url(value, blank=False, strip=None, allow_regex=None, block_regex=None, exc_msg=None, lang='en')¶
Validate a URL.
- Parameters
value (str, optional) – The value being validated.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
allow_regex (Optional[Sequence], optional) – If not None, the value is only allowed to match one of the regexes.
block_regex (Optional[Sequence], optional) – If not None, the value is only allowed to match none of the regexes.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not a valid URL.
- Returns
The value argument, not value.
- Return type
str
- prototools.validate_yes_no(value, blank=False, strip=None, yes_value='yes', no_value='no', sensitive=False, exc_msg=None, lang='en')¶
Validate a yes/no response.
- Parameters
value (str, optional) – The value being validated.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
yes_value (bool, optional) – Value of affirmative response. Defaults ‘yes’.
no_value (bool, optional) – Value of negative response. Defaults ‘no’.
sensitive (bool, optional) – If True, then the exact case of the option must be entered.
exc_msg (str, optional) – Custom message to use in the raised ValidatorsException.
lang (str) – Establish the language.
- Raises
Exception – If value is not a yes or no response.
- Returns
The yes_val or no_val argument, not value.
- Return type
str
- prototools.white(text)¶
- prototools.write_letters(text)¶
Example
>>> write_letters("Hello World!") _____ _ _ _ | _ | ___ ___ | |_ ___ | |_ ___ ___ | | ___ | __|| _|| . || _|| . || _|| . || . || ||_ -| |__| |_| |___||_| |___||_| |___||___||_||___|
- Parameters
text (str) –
- Return type
None
- prototools.write_letters_custom(text, n, color)¶
- Parameters
text (str) –
n (int) –
color (Callable) –
- Return type
None
- prototools.yellow(text)¶
- prototools.yes_no_input(prompt='', yes_value=None, no_value=None, sensitive=False, default=None, blank=False, strip=None, timeout=None, limit=None, function=None, validation=None, lang='en')¶
Prompt the user to enter a yes/no response.
- Parameters
prompt (str, optional) – Prompts the user to enter input.
yes_value (bool, optional) – Value of affirmative response. Defaults ‘yes’.
no_value (bool, optional) – Value of negative response. Defaults ‘no’.
sensitive (bool, optional) – If True, then the exact case of the option must be entered.
default (Any, optional) – Default value to use.
blank (bool, optional) – If True, a blank string will be accepted. Defaults to False.
strip (Union[None, str, bool], optional) – If None, whitespace is strip from value. If str, the characters in it are stripped. If False, nothing is stripped.
timeout (int, optional) – Time in seconds to enter an input.
limit (int, optional) – Number of tries to enter a valid input.
function (Callable, optional) – Optional function that is passed the user’s input and returns the new value as the input.
validation (Callable, optional) – Validator.
lang (str) – Establish the language.
- Raises
Exception – If value is not a yes or no response.
- Returns
The yes_val or no_val argument, not value.
- Return type
str
>>> s = yes_no_input("Do you like this?") Do you like this? Yeah Yeah is not a valid yes/no response Do you like Python? yes >>> s 'yes'