flam.utils
This page documents the flam.utils module. It contains generic utilities used by flam which may be useful for you too.
- class ProgressBar
Utility for iterating over a list and presenting a progress bar to the user via stdout:
# How you might hypothetically fetch a list of movies while presenting a progress bar about it. with ProgressBar(movies_to_fetch, desc='Downloading', keyfunc=lambda m: m.title) as bar: for movie in bar: fetch_movie(movie)
- __init__(elements: list[T], desc: None | str = None, keyfunc: None | Callable[[T], str] = None) None
- Parameters:
elements (list[T]) – list of elements to process while displaying the progress bar.
desc (None | str) – short description to print to the user of what is being done.
keyfunc (None | Callable[[T], str]) – function which receives an element from the list and returns a short string indicating to the user which element is currently being processed.
- Return type:
None
- __iter__() Iterator[T]
Iterate over
elementsand update the progress bar with each iteration.- Return type:
Iterator[T]
- __enter__() Self
Returns self. When the context exits the progress bar will be cleaned up.
- Return type:
Self
- __exit__(exc_type: type[BaseException], exc_value: None | BaseException, traceback: None | TracebackType) None
Cleanly ends the progress bar while ensuring it correctly reflects the element where iteration stopped.
- Parameters:
exc_type (type[BaseException])
exc_value (None | BaseException)
traceback (None | TracebackType)
- Return type:
None
- class Timeout
Utility for keeping track of time and raising an exception if a timeout is reached:
with Timeout(30) as timeout: do_some_operation_async() while operation_not_complete() time.sleep(1) timeout.tick() return operation_result()
- __init__(timeout_secs: float = float('inf')) None
- Parameters:
timeout_secs (float) – the timeout.
- Return type:
None
- tick() None
Raises a
TimeoutErrorif the time spent in the current context is greater than the timeout.- Return type:
None
- __enter__() Self
Begins counting time and returns self.
- Return type:
Self
- __exit__(exc_type: type[BaseException], exc_value: None | BaseException, traceback: None | TracebackType) None
Resets the time counter.
- Parameters:
exc_type (type[BaseException])
exc_value (None | BaseException)
traceback (None | TracebackType)
- Return type:
None
- download_file_using_browser(download_cmd: Callable[[], Any], file_extension: str, downloads_dir: str, timeout_secs: float = float('inf')) str
Handles downloading a file with an external tool which should download it to some directory. Watches that directory and waits for the downloaded file to appear.
- Parameters:
download_cmd (Callable[[], Any]) – function which should trigger an asynchronous file download.
file_extension (str) – the extension the downloaded file should have.
downloads_dir (str) – path to where the file is expected to be downloaded.
timeout_secs (float) – timeout for the download.
- Return type:
str
- slugify(s: str) str
Removes special characters from a string to turn it into a valid filename.
- Parameters:
s (str) – string to convert.
- Return type:
str
- import_file(file: str) ModuleType
Dynamically imports a file based on a path, and returns the module object.
- Parameters:
file (str) – path of the file to import.
- Return type:
ModuleType
- tree(dir_path: str, prefix: str = '', stats: None | Callable[[str], str] = None) Iterable[str]
Iterate over lines which together represent a directory tree in a pretty, human-readable format.
- Parameters:
dir_path (str) – path to the directory whose subtree we’re interested in.
prefix (str) – string that will appear at the start of each line.
stats (None | Callable[[str], str]) – function which receives a file path and returns a string with information to display next to that file.
- Return type:
Iterable[str]
- tabulate(records: list[list[str]], fillchar: str = ' ', use_color: bool = True, header_color: str = '', fill_color: str = colorama.Fore.BLACK + colorama.Style.BRIGHT, column_colors: None | list[str] = None) Iterable[str]
Turn a table into a nice printable format and iterate over its lines.
- Parameters:
records (list[list[str]]) – the table as a list of lists, where the outer lists are rows and the inner lists are columns.
fillchar (str) – character to use as spacing between columns.
use_color (bool) – whether columns should be colored for enhanced readability.
header_color (str) – additional color to apply on the header row. It may combine with the column colors.
fill_color (str) – color to use for
fillchar.column_colors (None | list[str]) – list of colors to use for columns. They will be used round-robin. If this is
None, a default list of colors will be used.
- Return type:
Iterable[str]
- class TruncationStyle
Enumeration of possible ways to truncate a string.
- NO_TRIM = 1
“What’s in the box?” -> “What’s in the box?”
- TRIM_END = 2
“What’s in the box?” -> “What’s i…”
- TRIM_START = 3
“What’s in the box?” -> “…the box?”
- TRIM_MIDDLE = 4
“What’s in the box?” -> “What…box?”
- truncate(s: str, max_len: int, ellipsis: str = '...', truncation_style: TruncationStyle = TruncationStyle.TRIM_END) str
Truncates a string.
- Parameters:
s (str) – the string to truncate.
max_len (int) – the maximum length beyond which the string will be truncated down to this length.
ellipsis (str) – short string to use to indicate a truncated part of the string.
truncation_style (TruncationStyle) – preference for which part of the string to truncate.
- Return type:
str
- num_pretty(num: int, abbreviate: bool = True) str
Formats a large number as a human-readable string.
- Parameters:
num (int) – the number to convert.
abbreviate (bool) – whether to shorten large numbers with a magnitude sign.
- Return type:
str
- parse_num_pretty(num_str: str) int
Inverse of
num_pretty().- Parameters:
num_str (str)
- Return type:
int
- stable_dedup(elements: Iterable[TElem], key: None | Callable[[TElem], TKey] = None) Iterable[TElem]
Removes duplicate elements from an iterable but preserves the original order.
- Parameters:
elements (Iterable[TElem]) – ordered collection of objects to deduplicate
key (None | Callable[[TElem], TKey]) – function which receives an element and returns a value by which to deduplicate it. I.e., all elements with the same key are considered duplicates.
- Return type:
Iterable[TElem]
- str2bool(s: str) bool
Parse some common, case-insensitive string representations of a boolean (‘true’, ‘yes’, ‘no’, ‘n’, etc.).
- Parameters:
s (str)
- Return type:
bool
- move_clobber(src: str, dst: str, must_exist: bool = True) None
Rename a file without caring if a different file by that name already exists.
- Parameters:
src (str)
dst (str)
must_exist (bool)
- Return type:
None