Module osbot_utils.helpers.html.Tag__Base
Expand source code
from collections import defaultdict
from osbot_utils.base_classes.Kwargs_To_Self import Kwargs_To_Self
from osbot_utils.utils.Files import file_create
INDENT_SIZE = 4
class Tag__Base(Kwargs_To_Self):
attributes : dict
elements : list
end_tag : bool = True
indent : int
tag_name : str
tag_classes : list
inner_html : str
new_line_before_elements : bool = True
def __init__(self, **kwargs):
super().__init__(**kwargs)
#self.locked() # lock the object so that it is not possible to add new attributes via normal assigment
def append(self, *elements):
self.elements.extend(elements)
return self
def attributes_values(self, *attributes_names):
attributes = {}
for attribute_name in attributes_names:
if hasattr(self, attribute_name):
attribute_value = getattr(self, attribute_name)
if attribute_value:
attributes[attribute_name] = attribute_value
return attributes
def elements__by_tag_name(self):
result = defaultdict(list)
for element in self.elements:
result[element.tag_name].append(element)
return dict(result)
def elements__with_tag_name(self, tag_name):
return self.elements__by_tag_name().get(tag_name)
def save(self, file_path):
return file_create(file_path, self.render())
def render_attributes(self):
attributes = self.attributes.copy()
if self.tag_classes:
attributes['class'] = ' '.join(self.tag_classes)
html_attributes = ' '.join([f'{key}="{value}"' for key, value in attributes.items()])
return html_attributes
def render_element(self):
html_attributes = self.render_attributes()
html_elements = self.render_elements()
element_indent = " " * self.indent * INDENT_SIZE
html = f"{element_indent}<{self.tag_name}"
if html_attributes:
html += f" {html_attributes}"
if self.end_tag:
html += ">"
if self.inner_html:
html += self.inner_html
if html_elements:
if self.new_line_before_elements:
html += "\n"
html += f"{html_elements}"
if self.new_line_before_elements:
html += "\n"
html += element_indent
html += f"</{self.tag_name}>"
else:
html += "/>"
return html
def render_elements(self):
html_elements = ""
for index, element in enumerate(self.elements):
if index:
html_elements += '\n'
element.indent = self.indent + 1 # set the indent of the child element based on the current one
html_element = element.render()
html_elements += html_element
return html_elements
def render(self):
return self.render_element()
Classes
class Tag__Base (**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 Tag__Base(Kwargs_To_Self): attributes : dict elements : list end_tag : bool = True indent : int tag_name : str tag_classes : list inner_html : str new_line_before_elements : bool = True def __init__(self, **kwargs): super().__init__(**kwargs) #self.locked() # lock the object so that it is not possible to add new attributes via normal assigment def append(self, *elements): self.elements.extend(elements) return self def attributes_values(self, *attributes_names): attributes = {} for attribute_name in attributes_names: if hasattr(self, attribute_name): attribute_value = getattr(self, attribute_name) if attribute_value: attributes[attribute_name] = attribute_value return attributes def elements__by_tag_name(self): result = defaultdict(list) for element in self.elements: result[element.tag_name].append(element) return dict(result) def elements__with_tag_name(self, tag_name): return self.elements__by_tag_name().get(tag_name) def save(self, file_path): return file_create(file_path, self.render()) def render_attributes(self): attributes = self.attributes.copy() if self.tag_classes: attributes['class'] = ' '.join(self.tag_classes) html_attributes = ' '.join([f'{key}="{value}"' for key, value in attributes.items()]) return html_attributes def render_element(self): html_attributes = self.render_attributes() html_elements = self.render_elements() element_indent = " " * self.indent * INDENT_SIZE html = f"{element_indent}<{self.tag_name}" if html_attributes: html += f" {html_attributes}" if self.end_tag: html += ">" if self.inner_html: html += self.inner_html if html_elements: if self.new_line_before_elements: html += "\n" html += f"{html_elements}" if self.new_line_before_elements: html += "\n" html += element_indent html += f"</{self.tag_name}>" else: html += "/>" return html def render_elements(self): html_elements = "" for index, element in enumerate(self.elements): if index: html_elements += '\n' element.indent = self.indent + 1 # set the indent of the child element based on the current one html_element = element.render() html_elements += html_element return html_elements def render(self): return self.render_element()
Ancestors
Subclasses
Class variables
var attributes : dict
var elements : list
var end_tag : bool
var indent : int
var inner_html : str
var new_line_before_elements : bool
var tag_classes : list
var tag_name : str
Methods
def append(self, *elements)
-
Expand source code
def append(self, *elements): self.elements.extend(elements) return self
def attributes_values(self, *attributes_names)
-
Expand source code
def attributes_values(self, *attributes_names): attributes = {} for attribute_name in attributes_names: if hasattr(self, attribute_name): attribute_value = getattr(self, attribute_name) if attribute_value: attributes[attribute_name] = attribute_value return attributes
def elements__by_tag_name(self)
-
Expand source code
def elements__by_tag_name(self): result = defaultdict(list) for element in self.elements: result[element.tag_name].append(element) return dict(result)
def elements__with_tag_name(self, tag_name)
-
Expand source code
def elements__with_tag_name(self, tag_name): return self.elements__by_tag_name().get(tag_name)
def render(self)
-
Expand source code
def render(self): return self.render_element()
def render_attributes(self)
-
Expand source code
def render_attributes(self): attributes = self.attributes.copy() if self.tag_classes: attributes['class'] = ' '.join(self.tag_classes) html_attributes = ' '.join([f'{key}="{value}"' for key, value in attributes.items()]) return html_attributes
def render_element(self)
-
Expand source code
def render_element(self): html_attributes = self.render_attributes() html_elements = self.render_elements() element_indent = " " * self.indent * INDENT_SIZE html = f"{element_indent}<{self.tag_name}" if html_attributes: html += f" {html_attributes}" if self.end_tag: html += ">" if self.inner_html: html += self.inner_html if html_elements: if self.new_line_before_elements: html += "\n" html += f"{html_elements}" if self.new_line_before_elements: html += "\n" html += element_indent html += f"</{self.tag_name}>" else: html += "/>" return html
def render_elements(self)
-
Expand source code
def render_elements(self): html_elements = "" for index, element in enumerate(self.elements): if index: html_elements += '\n' element.indent = self.indent + 1 # set the indent of the child element based on the current one html_element = element.render() html_elements += html_element return html_elements
def save(self, file_path)
-
Expand source code
def save(self, file_path): return file_create(file_path, self.render())
Inherited members