Module osbot_utils.helpers.CPrint

Expand source code
from osbot_utils.base_classes.Kwargs_To_Self import Kwargs_To_Self


# note these attributes will be replaced by methods by CPrint. This is done like this in order to:
#     - Have code complete on CPrint
#     - not have the write the code for each of the methods
#     - have a good and logical place to capture the ID of the color

class Colors:
    black           = "30"
    blue            = "34"
    cyan            = "36"
    grey            = "38;5;15"
    green           = "32"
    none            = "0"
    magenta         = "35"
    red             = "31"
    white           = "38;5;15"
    yellow          = "33"
    bright_black    = "90"
    bright_red      = "91"
    bright_green    = "92"
    bright_yellow   = "93"
    bright_blue     = "94"
    bright_magenta  = "95"
    bright_cyan     = "96"
    bright_white    = "97"
    dark_red        = "38;5;124"            # see https://github.com/fidian/ansi for a full list


class CPrint(Colors, Kwargs_To_Self):
    apply_colors   : bool = True
    auto_new_line  : bool = True
    auto_print     : bool = True
    clear_on_print : bool = True
    current_line   : str
    lines          : list

    def __getattribute__(self, name):                                                       # this will replace the attributes defined in colors with methods that will call add_to_current_line with the params provided
        if name != '__getattribute__' and hasattr(Colors, name):                                                           # if name is one of the colors defined in Colors
            def method(*args, **kwargs):                                                    # create a method to replace the attribute
                return self.add_with_color(name, *args, **kwargs)                     # pass the data to add_with_color
            return method
        return super().__getattribute__(name)                                               # if the attribute name is not one of the attributes defined in colors, restore the normal behaviour of __getattribute__

    def add_with_color(self, color_name, *args, **kwargs):
        color_code = getattr(Colors, color_name)                                            # capture the color from the Colors class
        self.add_to_current_line(color_code, *args, **kwargs)                         # add the color code to the current line
        return self

    def add_to_current_line(self, color_code, *args, **kwargs):
        args             = [str(arg) for arg in args]                                           # Convert all non-string arguments to strings
        text             = "".join(args)                                                        # Concatenate all arguments without a space (to have beter support for multi-prints per line)
        if self.apply_colors:
            color_start      = f"\033[{color_code}m"                                            # ANSI color code start and end
            color_end        = "\033[0m"
            kwargs['end']    = ''                                                               # remove the default print end (which is \n)

            text_with_colors = f"{color_start}{text}{color_end}"
            self.current_line += text_with_colors
        else:
            self.current_line += text
        self.apply_config_options()
        return self

    def apply_config_options(self):
        if self.auto_new_line:
            self.flush()
        if self.auto_print:
            self.print()

    def flush(self):
        if self.current_line:
            self.lines.append(self.current_line)
        self.current_line = ''
        return self

    def lines_str(self):
        lines_str = ''
        for line in self.lines:
            lines_str += line + '\n'
        return lines_str

    def new_line(self):
        self.flush()
        self.lines.append('')
        self.apply_config_options()
        return self

    def print(self):
        self.flush()
        for line in self.lines:
            print(line)
        if self.clear_on_print:
            self.lines = []
        return self

Classes

class CPrint (**kwargs)

A mixin class to strictly assign keyword arguments to pre-defined instance attributes during initialization.

This base class provides an init method that assigns values from keyword arguments to instance attributes. If an attribute with the same name as a key from the kwargs is defined in the class, it will be set to the value from kwargs. If the key does not match any predefined attribute names, an exception is raised.

This behavior enforces strict control over the attributes of instances, ensuring that only predefined attributes can be set at the time of instantiation and avoids silent attribute creation which can lead to bugs in the code.

Usage

class MyConfigurableClass(Kwargs_To_Self): attribute1 = 'default_value' attribute2 = True attribute3 : str attribute4 : list attribute4 : int = 42

# Other methods can be added here

Correctly override default values by passing keyword arguments

instance = MyConfigurableClass(attribute1='new_value', attribute2=False)

This will raise an exception as 'attribute3' is not predefined

instance = MyConfigurableClass(attribute3='invalid_attribute')

this will also assign the default value to any variable that has a type defined. In the example above the default values (mapped by default__kwargs and locals) will be: attribute1 = 'default_value' attribute2 = True attribute3 = '' # default value of str attribute4 = [] # default value of list attribute4 = 42 # defined value in the class

Note

It is important that all attributes which may be set at instantiation are predefined in the class. Failure to do so will result in an exception being raised.

Methods

init(**kwargs): The initializer that handles the assignment of keyword arguments to instance attributes. It enforces strict attribute assignment rules, only allowing attributes that are already defined in the class to be set.

Initialize an instance of the derived class, strictly assigning provided keyword arguments to corresponding instance attributes.

Parameters

**kwargs: Variable length keyword arguments.

Raises

Exception
If a key from kwargs does not correspond to any attribute pre-defined in the class, an exception is raised to prevent setting an undefined attribute.
Expand source code
class CPrint(Colors, Kwargs_To_Self):
    apply_colors   : bool = True
    auto_new_line  : bool = True
    auto_print     : bool = True
    clear_on_print : bool = True
    current_line   : str
    lines          : list

    def __getattribute__(self, name):                                                       # this will replace the attributes defined in colors with methods that will call add_to_current_line with the params provided
        if name != '__getattribute__' and hasattr(Colors, name):                                                           # if name is one of the colors defined in Colors
            def method(*args, **kwargs):                                                    # create a method to replace the attribute
                return self.add_with_color(name, *args, **kwargs)                     # pass the data to add_with_color
            return method
        return super().__getattribute__(name)                                               # if the attribute name is not one of the attributes defined in colors, restore the normal behaviour of __getattribute__

    def add_with_color(self, color_name, *args, **kwargs):
        color_code = getattr(Colors, color_name)                                            # capture the color from the Colors class
        self.add_to_current_line(color_code, *args, **kwargs)                         # add the color code to the current line
        return self

    def add_to_current_line(self, color_code, *args, **kwargs):
        args             = [str(arg) for arg in args]                                           # Convert all non-string arguments to strings
        text             = "".join(args)                                                        # Concatenate all arguments without a space (to have beter support for multi-prints per line)
        if self.apply_colors:
            color_start      = f"\033[{color_code}m"                                            # ANSI color code start and end
            color_end        = "\033[0m"
            kwargs['end']    = ''                                                               # remove the default print end (which is \n)

            text_with_colors = f"{color_start}{text}{color_end}"
            self.current_line += text_with_colors
        else:
            self.current_line += text
        self.apply_config_options()
        return self

    def apply_config_options(self):
        if self.auto_new_line:
            self.flush()
        if self.auto_print:
            self.print()

    def flush(self):
        if self.current_line:
            self.lines.append(self.current_line)
        self.current_line = ''
        return self

    def lines_str(self):
        lines_str = ''
        for line in self.lines:
            lines_str += line + '\n'
        return lines_str

    def new_line(self):
        self.flush()
        self.lines.append('')
        self.apply_config_options()
        return self

    def print(self):
        self.flush()
        for line in self.lines:
            print(line)
        if self.clear_on_print:
            self.lines = []
        return self

Ancestors

Class variables

var apply_colors : bool
var auto_new_line : bool
var auto_print : bool
var clear_on_print : bool
var current_line : str
var lines : list

Methods

def add_to_current_line(self, color_code, *args, **kwargs)
Expand source code
def add_to_current_line(self, color_code, *args, **kwargs):
    args             = [str(arg) for arg in args]                                           # Convert all non-string arguments to strings
    text             = "".join(args)                                                        # Concatenate all arguments without a space (to have beter support for multi-prints per line)
    if self.apply_colors:
        color_start      = f"\033[{color_code}m"                                            # ANSI color code start and end
        color_end        = "\033[0m"
        kwargs['end']    = ''                                                               # remove the default print end (which is \n)

        text_with_colors = f"{color_start}{text}{color_end}"
        self.current_line += text_with_colors
    else:
        self.current_line += text
    self.apply_config_options()
    return self
def add_with_color(self, color_name, *args, **kwargs)
Expand source code
def add_with_color(self, color_name, *args, **kwargs):
    color_code = getattr(Colors, color_name)                                            # capture the color from the Colors class
    self.add_to_current_line(color_code, *args, **kwargs)                         # add the color code to the current line
    return self
def apply_config_options(self)
Expand source code
def apply_config_options(self):
    if self.auto_new_line:
        self.flush()
    if self.auto_print:
        self.print()
def flush(self)
Expand source code
def flush(self):
    if self.current_line:
        self.lines.append(self.current_line)
    self.current_line = ''
    return self
def lines_str(self)
Expand source code
def lines_str(self):
    lines_str = ''
    for line in self.lines:
        lines_str += line + '\n'
    return lines_str
def new_line(self)
Expand source code
def new_line(self):
    self.flush()
    self.lines.append('')
    self.apply_config_options()
    return self
def print(self)
Expand source code
def print(self):
    self.flush()
    for line in self.lines:
        print(line)
    if self.clear_on_print:
        self.lines = []
    return self

Inherited members

class Colors
Expand source code
class Colors:
    black           = "30"
    blue            = "34"
    cyan            = "36"
    grey            = "38;5;15"
    green           = "32"
    none            = "0"
    magenta         = "35"
    red             = "31"
    white           = "38;5;15"
    yellow          = "33"
    bright_black    = "90"
    bright_red      = "91"
    bright_green    = "92"
    bright_yellow   = "93"
    bright_blue     = "94"
    bright_magenta  = "95"
    bright_cyan     = "96"
    bright_white    = "97"
    dark_red        = "38;5;124"            # see https://github.com/fidian/ansi for a full list

Subclasses

Class variables

var black
var blue
var bright_black
var bright_blue
var bright_cyan
var bright_green
var bright_magenta
var bright_red
var bright_white
var bright_yellow
var cyan
var dark_red
var green
var grey
var magenta
var none
var red
var white
var yellow