Python supercharged for fastai development
56
Programmatic HTML and XML generation with a fluent API, supporting all standard HTML elements and providing safe string handling for web development. The xml module enables building HTML documents and web components through Python code with type safety and modern web standards support.
Fundamental classes for creating and manipulating XML/HTML structures with a fluent, chainable API.
class FT:
"""
Fast Tag - Core class for XML/HTML element creation and manipulation.
Provides a flexible, chainable interface for building HTML/XML structures
with automatic attribute handling, content management, and event system.
Features:
- Chainable method calls for fluent API
- Automatic attribute name conversion (class_, htmlClass -> class)
- Event listener system for dynamic updates
- Support for nested elements and content
- Void element handling (self-closing tags)
Parameters:
- tag: str, HTML/XML tag name
- cs: tuple, child elements and content
- attrs: dict, element attributes
- void_: bool, whether element is self-closing
- **kwargs: additional attributes
"""
def __init__(self, tag, cs, attrs=None, void_=False, **kwargs): ...
def __call__(self, *c, **kw):
"""
Add children and/or attributes (chainable).
Parameters:
- *c: child elements or content to add
- **kw: attributes to set
Returns:
self: For method chaining
"""
def set(self, *c, **kw):
"""
Set children and/or attributes, replacing existing (chainable).
Parameters:
- *c: child elements or content to set
- **kw: attributes to set
Returns:
self: For method chaining
"""
def get(self, k, default=None):
"""
Get attribute value.
Parameters:
- k: str, attribute name
- default: default value if attribute not found
Returns:
Attribute value or default
"""
def on(self, f):
"""
Add event listener for element changes.
Parameters:
- f: callable, listener function called on changes
"""
def changed(self):
"""
Notify listeners of element changes and return self.
Returns:
self: For method chaining
"""
# Properties and indexing
@property
def list(self):
"""Get [tag, children, attrs] representation."""
def __getitem__(self, idx): ...
def __setitem__(self, i, o): ...
def __iter__(self): ...
def ft(tag, *c, **kw):
"""
Create FT (Fast Tag) element with specified tag, content, and attributes.
Convenient factory function for creating HTML/XML elements with
automatic preprocessing of content and attributes.
Parameters:
- tag: str, HTML/XML tag name
- *c: child elements, strings, or other content
- **kw: element attributes (automatically converted)
Returns:
FT: Configured element ready for use
Examples:
div = ft('div', 'Hello World', class_='container')
link = ft('a', 'Click here', href='https://example.com')
"""
def Html(*c, **kwargs):
"""
Create complete HTML document structure.
Generates proper HTML5 document with DOCTYPE and html root element.
Automatically handles head and body sections if provided.
Parameters:
- *c: content for the document (head, body, or direct elements)
- **kwargs: attributes for html element (lang, etc.)
Returns:
str: Complete HTML document string
"""
class Safe:
"""
Wrapper for HTML strings that should not be escaped.
Used to mark strings as safe HTML content that should be
inserted directly without HTML entity escaping.
Parameters:
- s: str, HTML content that is safe to insert directly
Usage:
content = Safe('<strong>Bold text</strong>')
div = Div(content) # HTML is not escaped
"""
def __init__(self, s): ...
def to_xml(elm, lvl=0):
"""
Convert element tree to XML/HTML string representation.
Serializes FT elements and nested structures to properly
formatted XML/HTML with appropriate indentation and escaping.
Parameters:
- elm: FT element or content to serialize
- lvl: int, indentation level for formatting
Returns:
str: XML/HTML string representation
"""Utilities for handling HTML attributes and values with proper conversion and escaping.
def attrmap(o):
"""
Map Python attribute names to HTML attribute names.
Converts Python-friendly attribute names to proper HTML attributes:
- class_, cls, htmlClass, klass -> class
- _for, fr, htmlFor -> for
- Leading underscores removed: _id -> id
- Underscores converted to hyphens: data_value -> data-value
Parameters:
- o: str, attribute name to convert
Returns:
str: HTML-compatible attribute name
"""
def valmap(o):
"""
Convert Python values to HTML attribute values.
Handles various Python types for HTML attribute values:
- Lists: joined with spaces (['btn', 'primary'] -> 'btn primary')
- Dicts: CSS-style ({"color": "red"} -> 'color:red')
- None/empty: returns None (attribute omitted)
Parameters:
- o: value to convert to HTML attribute format
Returns:
str|None: HTML-compatible attribute value or None
"""
voids = {
"""
Set of HTML void elements (self-closing tags).
Contains all HTML elements that don't have closing tags:
area, base, br, col, embed, hr, img, input, link, meta,
param, source, track, wbr
Used automatically by element creation functions to determine
whether to generate self-closing tags.
"""
}Pre-configured classes for all standard HTML elements with appropriate default behaviors.
# Document structure elements
def Head(*c, **kwargs):
"""HTML head element for document metadata."""
def Title(*c, **kwargs):
"""HTML title element for document title."""
def Meta(*c, **kwargs):
"""HTML meta element for metadata (void element)."""
def Link(*c, **kwargs):
"""HTML link element for external resources (void element)."""
def Style(*c, **kwargs):
"""HTML style element for embedded CSS."""
def Body(*c, **kwargs):
"""HTML body element for document content."""
# Text content elements
def P(*c, **kwargs):
"""HTML paragraph element."""
def Div(*c, **kwargs):
"""HTML div element for generic container."""
def Span(*c, **kwargs):
"""HTML span element for inline content."""
def Pre(*c, **kwargs):
"""HTML pre element for preformatted text."""
def Code(*c, **kwargs):
"""HTML code element for code snippets."""
# Heading elements
def H1(*c, **kwargs):
"""HTML h1 element for main heading."""
def H2(*c, **kwargs):
"""HTML h2 element for secondary heading."""
def H3(*c, **kwargs):
"""HTML h3 element for tertiary heading."""
def H4(*c, **kwargs):
"""HTML h4 element for quaternary heading."""
def H5(*c, **kwargs):
"""HTML h5 element for quinary heading."""
def H6(*c, **kwargs):
"""HTML h6 element for senary heading."""
# Text formatting elements
def Strong(*c, **kwargs):
"""HTML strong element for strong importance."""
def Em(*c, **kwargs):
"""HTML em element for emphasized text."""
def B(*c, **kwargs):
"""HTML b element for bold text."""
def I(*c, **kwargs):
"""HTML i element for italic text."""
def U(*c, **kwargs):
"""HTML u element for underlined text."""
def S(*c, **kwargs):
"""HTML s element for strikethrough text."""
def Strike(*c, **kwargs):
"""HTML strike element (deprecated, use S)."""
def Sub(*c, **kwargs):
"""HTML sub element for subscript text."""
def Sup(*c, **kwargs):
"""HTML sup element for superscript text."""
def Mark(*c, **kwargs):
"""HTML mark element for highlighted text."""
def Small(*c, **kwargs):
"""HTML small element for smaller text."""
# Structure elements
def Hr(*c, **kwargs):
"""HTML hr element for thematic break (void element)."""
def Br(*c, **kwargs):
"""HTML br element for line break (void element)."""
# Media elements
def Img(*c, **kwargs):
"""HTML img element for images (void element)."""
def Video(*c, **kwargs):
"""HTML video element for video content."""
def Audio(*c, **kwargs):
"""HTML audio element for audio content."""
def Source(*c, **kwargs):
"""HTML source element for media resources (void element)."""
def Canvas(*c, **kwargs):
"""HTML canvas element for graphics."""
def Svg(*c, **kwargs):
"""HTML svg element for vector graphics."""
def Iframe(*c, **kwargs):
"""HTML iframe element for embedded content."""
def Object(*c, **kwargs):
"""HTML object element for embedded objects."""
def Embed(*c, **kwargs):
"""HTML embed element for embedded content (void element)."""
def Param(*c, **kwargs):
"""HTML param element for object parameters (void element)."""
# Navigation and linking
def A(*c, **kwargs):
"""HTML a element for hyperlinks."""
def Nav(*c, **kwargs):
"""HTML nav element for navigation links."""
# List elements
def Ul(*c, **kwargs):
"""HTML ul element for unordered lists."""
def Ol(*c, **kwargs):
"""HTML ol element for ordered lists."""
def Li(*c, **kwargs):
"""HTML li element for list items."""
def Dl(*c, **kwargs):
"""HTML dl element for description lists."""
def Dt(*c, **kwargs):
"""HTML dt element for description terms."""
def Dd(*c, **kwargs):
"""HTML dd element for description details."""
# Table elements
def Table(*c, **kwargs):
"""HTML table element for tabular data."""
def Thead(*c, **kwargs):
"""HTML thead element for table header."""
def Tbody(*c, **kwargs):
"""HTML tbody element for table body."""
def Tfoot(*c, **kwargs):
"""HTML tfoot element for table footer."""
def Tr(*c, **kwargs):
"""HTML tr element for table rows."""
def Th(*c, **kwargs):
"""HTML th element for table headers."""
def Td(*c, **kwargs):
"""HTML td element for table data."""
def Caption(*c, **kwargs):
"""HTML caption element for table captions."""
def Col(*c, **kwargs):
"""HTML col element for table columns (void element)."""
def Colgroup(*c, **kwargs):
"""HTML colgroup element for column groups."""
# Form elements
def Form(*c, **kwargs):
"""HTML form element for user input forms."""
def Input(*c, **kwargs):
"""HTML input element for form inputs (void element)."""
def Textarea(*c, **kwargs):
"""HTML textarea element for multi-line text input."""
def Button(*c, **kwargs):
"""HTML button element for clickable buttons."""
def Select(*c, **kwargs):
"""HTML select element for dropdown selections."""
def Option(*c, **kwargs):
"""HTML option element for select options."""
def Label(*c, **kwargs):
"""HTML label element for form labels."""
def Fieldset(*c, **kwargs):
"""HTML fieldset element for form grouping."""
def Legend(*c, **kwargs):
"""HTML legend element for fieldset captions."""
# Semantic structure elements
def Main(*c, **kwargs):
"""HTML main element for main content."""
def Header(*c, **kwargs):
"""HTML header element for introductory content."""
def Footer(*c, **kwargs):
"""HTML footer element for footer content."""
def Section(*c, **kwargs):
"""HTML section element for document sections."""
def Article(*c, **kwargs):
"""HTML article element for standalone content."""
def Aside(*c, **kwargs):
"""HTML aside element for sidebar content."""
def Figure(*c, **kwargs):
"""HTML figure element for figure content."""
def Figcaption(*c, **kwargs):
"""HTML figcaption element for figure captions."""
# Interactive elements
def Details(*c, **kwargs):
"""HTML details element for disclosure widget."""
def Summary(*c, **kwargs):
"""HTML summary element for details summary."""
# Scripting elements
def Script(*c, **kwargs):
"""HTML script element for JavaScript."""
def Noscript(*c, **kwargs):
"""HTML noscript element for no-script fallback."""
def Template(*c, **kwargs):
"""HTML template element for client-side templates."""
def Slot(*c, **kwargs):
"""HTML slot element for web components."""
# Mathematical elements
def Math(*c, **kwargs):
"""HTML math element for mathematical notation."""Helper functions for HTML processing, syntax highlighting, and debugging.
def highlight(s, lang='xml'):
"""
Syntax highlight code string.
Applies syntax highlighting to code strings for display
in HTML or terminal environments.
Parameters:
- s: str, code to highlight
- lang: str, language for syntax highlighting
Returns:
str: Highlighted code (HTML or ANSI codes)
"""
def showtags(s):
"""
Display HTML tags in string for debugging.
Visualizes HTML structure by showing tag boundaries
and nesting levels for debugging HTML generation.
Parameters:
- s: str, HTML string to analyze
Returns:
str: Formatted representation showing tag structure
"""from fastcore.xml import ft, Html, Head, Title, Body, Div, P, A
# Simple element creation
div = ft('div', 'Hello World', class_='greeting')
print(to_xml(div))
# <div class="greeting">Hello World</div>
# Using convenience classes
paragraph = P('This is a paragraph with ', Strong('bold text'), '.')
print(to_xml(paragraph))
# <p>This is a paragraph with <strong>bold text</strong>.</p>
# Chaining methods for fluent API
container = (Div()
.set('Welcome to our site!')
.set(class_='container', id='main')
.set(P('This is the main content area.'))
)
print(to_xml(container))
# <div class="container" id="main">Welcome to our site!<p>This is the main content area.</p></div>from fastcore.xml import *
# Build complete HTML document
def create_webpage(title_text, content):
return Html(
Head(
Title(title_text),
Meta(charset='utf-8'),
Meta(name='viewport', content='width=device-width, initial-scale=1'),
Link(rel='stylesheet', href='styles.css')
),
Body(
Header(
H1(title_text),
Nav(
Ul(
Li(A('Home', href='/')),
Li(A('About', href='/about')),
Li(A('Contact', href='/contact'))
)
)
),
Main(
Section(content, class_='content'),
Aside(
H2('Sidebar'),
P('This is sidebar content.')
)
),
Footer(
P('© 2024 My Website. All rights reserved.')
)
),
lang='en'
)
# Generate the page
webpage = create_webpage('My Website', [
H2('Welcome'),
P('This is the main content of the page.'),
P('You can add more paragraphs and elements here.')
])
html_string = to_xml(webpage)
print(html_string)from fastcore.xml import *
# Dynamic attribute handling
def create_button(text, button_type='button', **kwargs):
classes = ['btn']
if 'primary' in kwargs:
classes.append('btn-primary')
if 'large' in kwargs:
classes.append('btn-lg')
return Button(text,
type=button_type,
class_=classes, # List automatically joined with spaces
**{k: v for k, v in kwargs.items()
if k not in ['primary', 'large']})
# Create various buttons
submit_btn = create_button('Submit', 'submit', primary=True, id='submit-form')
cancel_btn = create_button('Cancel', onclick='closeModal()', large=True)
print(to_xml(submit_btn))
# <button type="submit" class="btn btn-primary" id="submit-form">Submit</button>
# CSS-style attributes from dictionaries
styled_div = Div('Styled content',
style={'color': 'red', 'background': 'yellow', 'padding': '10px'}
)
print(to_xml(styled_div))
# <div style="color:red; background:yellow; padding:10px">Styled content</div>
# Safe HTML content
from fastcore.xml import Safe
# This HTML won't be escaped
safe_content = Safe('<em>Emphasized</em> and <strong>bold</strong> text')
container = Div('This contains ', safe_content, '!')
print(to_xml(container))
# <div>This contains <em>Emphasized</em> and <strong>bold</strong> text!</div>from fastcore.xml import *
# Complex form generation
def create_contact_form():
return Form(
Fieldset(
Legend('Contact Information'),
Div(
Label('Name:', fr='name'), # fr becomes 'for'
Input(type='text', id='name', name='name', required=True),
class_='form-group'
),
Div(
Label('Email:', fr='email'),
Input(type='email', id='email', name='email', required=True),
class_='form-group'
),
Div(
Label('Message:', fr='message'),
Textarea('', id='message', name='message', rows=5, cols=50),
class_='form-group'
)
),
Fieldset(
Legend('Preferences'),
Div(
Input(type='checkbox', id='newsletter', name='newsletter', value='yes'),
Label('Subscribe to newsletter', fr='newsletter'),
class_='checkbox-group'
),
Div(
Label('Preferred contact method:', fr='contact-method'),
Select(
Option('Email', value='email', selected=True),
Option('Phone', value='phone'),
Option('Text', value='text'),
id='contact-method',
name='contact_method'
),
class_='form-group'
)
),
Div(
Button('Submit', type='submit', class_='btn btn-primary'),
Button('Reset', type='reset', class_='btn btn-secondary'),
class_='form-actions'
),
method='POST',
action='/contact'
)
contact_form = create_contact_form()
print(to_xml(contact_form))from fastcore.xml import *
# Generate data table
def create_data_table(headers, rows):
return Table(
Caption('Data Summary'),
Thead(
Tr(*[Th(header) for header in headers])
),
Tbody(*[
Tr(*[Td(cell) for cell in row])
for row in rows
]),
class_='data-table'
)
# Sample data
headers = ['Name', 'Age', 'City', 'Score']
data = [
['Alice', 30, 'New York', 95],
['Bob', 25, 'San Francisco', 87],
['Charlie', 35, 'Chicago', 92]
]
table = create_data_table(headers, data)
# Add zebra striping and responsive classes
table = table.set(class_='data-table table-striped table-responsive')
print(to_xml(table))from fastcore.xml import *
# Reusable components
class HTMLComponent:
"""Base class for reusable HTML components."""
def render(self):
raise NotImplementedError
class Card(HTMLComponent):
def __init__(self, title, content, image_url=None, actions=None):
self.title = title
self.content = content
self.image_url = image_url
self.actions = actions or []
def render(self):
card_content = []
if self.image_url:
card_content.append(
Img(src=self.image_url, class_='card-img-top', alt=self.title)
)
body_content = [
H5(self.title, class_='card-title'),
P(self.content, class_='card-text')
]
if self.actions:
body_content.append(
Div(*self.actions, class_='card-actions')
)
card_content.append(
Div(*body_content, class_='card-body')
)
return Div(*card_content, class_='card')
class CardGrid(HTMLComponent):
def __init__(self, cards, columns=3):
self.cards = cards
self.columns = columns
def render(self):
return Div(
*[card.render() for card in self.cards],
class_=f'card-grid cols-{self.columns}'
)
# Use components
cards = [
Card(
'Product 1',
'Description of product 1',
image_url='/images/product1.jpg',
actions=[
Button('Buy Now', class_='btn btn-primary'),
A('Learn More', href='/product1', class_='btn btn-secondary')
]
),
Card(
'Product 2',
'Description of product 2',
actions=[Button('Buy Now', class_='btn btn-primary')]
),
Card(
'Product 3',
'Description of product 3',
image_url='/images/product3.jpg'
)
]
grid = CardGrid(cards, columns=3)
html_output = to_xml(grid.render())from fastcore.xml import *
# Event-driven HTML updates
class LiveCounter:
def __init__(self, initial_value=0):
self.value = initial_value
self.display = Span(str(self.value), class_='counter-value')
self.container = Div(
P('Current count: ', self.display),
Button('Increment', onclick='increment()'),
Button('Decrement', onclick='decrement()'),
class_='counter-widget'
)
# Add event listener for updates
self.display.on(self.on_update)
def increment(self):
self.value += 1
self.display.set(str(self.value))
def decrement(self):
self.value -= 1
self.display.set(str(self.value))
def on_update(self, element):
print(f"Counter updated to: {self.value}")
def render(self):
return self.container
# Create and use counter
counter = LiveCounter(5)
counter.increment() # Triggers update event
html = to_xml(counter.render())
# Template system with placeholders
class Template:
def __init__(self, html_structure):
self.structure = html_structure
self.placeholders = {}
def set_placeholder(self, name, content):
self.placeholders[name] = content
return self
def render(self):
def replace_placeholders(element):
if hasattr(element, 'children'):
new_children = []
for child in element.children:
if isinstance(child, str) and child.startswith('{{') and child.endswith('}}'):
placeholder_name = child[2:-2].strip()
new_children.append(self.placeholders.get(placeholder_name, child))
else:
new_children.append(replace_placeholders(child) if hasattr(child, 'children') else child)
return element.set(*new_children)
return element
return replace_placeholders(self.structure)
# Use template
template = Template(
Div(
H1('{{title}}'),
P('{{description}}'),
Div('{{content}}', class_='main-content')
)
)
rendered = template.set_placeholder('title', 'Welcome') .set_placeholder('description', 'This is a dynamic page') .set_placeholder('content', 'Main page content here') .render()
print(to_xml(rendered))Install with Tessl CLI
npx tessl i tessl/pypi-fastcoredocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10