Skip to content

Push v0.3.3 to main #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open

Push v0.3.3 to main #20

wants to merge 4 commits into from

Conversation

R5dan
Copy link
Collaborator

@R5dan R5dan commented Apr 24, 2025

No description provided.

Copy link

coderabbitai bot commented Apr 24, 2025

Summary by CodeRabbit

  • New Features

    • Added advanced element querying and indexing by attributes and text content, including support for complex attribute types.
    • Introduced new methods for element selection using CSS-like selectors, attribute values, and text content.
    • Added dictionary and list serialisation/deserialisation methods for tables.
  • Improvements

    • Simplified constructors for various elements, unifying and streamlining property handling.
    • Enhanced recursive type support for attributes, enabling nested lists and dictionaries.
    • Improved table and row classes with iterable and length support.
  • Other Changes

    • Updated package version to 0.3.3.
    • Removed publishing to TestPyPI in the release workflow.

Walkthrough

This update introduces several significant changes across the codebase. The GitHub Actions workflow is modified to remove the step that publishes distributions to TestPyPI, retaining only the main PyPI publishing step. The BetterMD package's import structure is updated to use qualified module imports for elements, and the __all__ export list is adjusted accordingly. Multiple element classes are refactored to simplify constructors and attribute handling, particularly for styles and classes. The Symbol class and related element classes now unify style and class management via the props dictionary. The InnerHTML class is extended with advanced indexing and querying capabilities for attributes and text content, using new hashable wrapper classes. Table-related classes receive new methods for serialisation and deserialisation, as well as iterable and length support. The type alias for attribute types is made recursive to support nested structures. The package version is incremented to 0.3.3.

Changes

File(s) Change Summary
.github/workflows/publish.yml Removed the step that published distributions to TestPyPI; now only publishing to main PyPI remains.
setup.py Updated version string from "0.3.2" to "0.3.3".
BetterMD/init.py Changed wildcard import of elements to qualified import; updated references to Symbol to use elements.Symbol; changed __all__ to export elements instead of Symbol.
BetterMD/typing.py Updated ATTR_TYPES type alias to a recursive union, allowing nested lists and dictionaries of attribute types.
BetterMD/elements/col.py
BetterMD/elements/track.py
Removed self_closing attribute from Col and Track classes; added type attribute with value "void".
BetterMD/elements/style.py Simplified Style class constructor: removed positional styles, classes, and inner parameters; now only accepts keyword arguments and passes **props to the superclass.
BetterMD/elements/symbol.py Refactored Symbol class: removed explicit styles and classes parameters from constructor; added styles and classes properties that access these via props; removed nl attribute; updated copy and get_prop methods; adjusted parse to normalise but not remove "class" and "style" keys.
BetterMD/elements/table.py Refactored constructors for Table, THead, TBody, TFoot, Tr, and Data to remove styles and classes parameters; added dictionary serialisation/deserialisation methods (to_dict, from_dict) for Table; reintroduced and relocated to_list and from_list methods for table components; added iterable and length support to row and section classes; refined internal data structure handling and preparation logic.
BetterMD/elements/document.py Added HashableList and HashableDict classes for hashable attribute indexing; updated Fetcher to accept both protocol and dict; extended InnerHTML with advanced attribute and text indexing (attrs, text, children_attrs, children_text); normalised attribute keys in add_elm; added advanced querying methods (find, get_by_text, get_by_attr, advanced_find); changed tag name lookup to be case-insensitive.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant InnerHTML
    participant Symbol

    User->>InnerHTML: find(key) / get_by_text(text) / get_by_attr(attr, value) / advanced_find(tag, attrs)
    InnerHTML->>InnerHTML: Look up elements in attrs/text indexes
    InnerHTML->>Symbol: Return list of matching Symbol instances
Loading
sequenceDiagram
    participant User
    participant Table

    User->>Table: to_dict()
    Table->>Table: Convert columns to dict of header to cell lists
    Table-->>User: Return dictionary

    User->>Table: from_dict(data)
    Table->>Table: Create Table from dict, populate head/body
    Table-->>User: Return Table instance
Loading

Possibly related PRs

  • Better-MD/better-md#18: Updates and fixes the publishing workflow, including the TestPyPI step; both PRs modify the same workflow file but this PR removes TestPyPI publishing.
  • Better-MD/better-md#19: Also removes the TestPyPI publishing step and updates import style and exports in BetterMD/__init__.py, indicating overlapping changes with this PR.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🔭 Outside diff range comments (2)
BetterMD/elements/style.py (1)

66-77: 🛠️ Refactor suggestion

Constructor/docstring mismatch and missing inner forwarding

inner is no longer accepted yet it is still documented (lines 70-75) and not passed to
Symbol.__init__, so callers cannot supply child elements.

-def __init__(self, *, style: t.Optional[StyleDict] = None, raw: str = "", **props):
+def __init__(self, *, style: t.Optional[StyleDict] = None, raw: str = "",
+             inner: list[Symbol] | None = None, **props):

-    super().__init__(**props)
+    super().__init__(inner=inner, **props)

Please also update the docstring to drop/reflect the changed parameters.

BetterMD/elements/symbol.py (1)

72-82: ⚠️ Potential issue

copy() uses undefined variables – raises NameError

inner and classes were removed from the signature but are still referenced,
and Symbol(...) is called with an obsolete positional pattern.

-def copy(self, styles: dict[str, str] | None = None):
-    if inner is None:
-        inner = []
-    if styles is None:
-        styles = {}
-    if classes is None:
-        classes = []
-
-    styles.update(self.styles)
-    return Symbol(styles, classes, inner=inner)
+def copy(self, *, styles: dict[str, str] | None = None,
+               inner: list["Symbol"] | None = None,
+               **extra_props):
+    styles = {**self.styles, **(styles or {})}
+    inner = list(inner or self.children)        # shallow copy by default
+    return type(self)(inner=inner, style=styles, **self.props, **extra_props)

Without this patch copy() raises immediately.

🧰 Tools
🪛 Ruff (0.8.2)

73-73: Undefined name inner

(F821)


77-77: Undefined name classes

(F821)

🧹 Nitpick comments (5)
BetterMD/elements/symbol.py (1)

52-59: styles/classes are read-only views – provide setters or clarify immutability

The helper properties return the underlying mapping/list, but there is no
corresponding setter. Users mutating symbol.styles["color"]="red" will modify
props silently, whereas symbol.styles = {...} will raise AttributeError.
Consider exposing explicit getters/setters or documenting the intended usage.

BetterMD/elements/document.py (2)

44-46: Incorrect class name in HashableDict.__repr__

The __repr__ claims HashableList, should be HashableDict – aids debugging.

-    def __repr__(self):
-        return f"HashableList({self.dct})"
+    def __repr__(self):
+        return f"HashableDict({self.dct})"

5-5: Unused import flagged by Ruff

ATTR_TYPES is imported only for type checking; silence Ruff with a noqa:

-from ..typing import ATTR_TYPES
+from ..typing import ATTR_TYPES  # noqa: F401
🧰 Tools
🪛 Ruff (0.8.2)

5-5: ..typing.ATTR_TYPES imported but unused

Remove unused import: ..typing.ATTR_TYPES

(F401)

BetterMD/elements/table.py (2)

191-200: Type annotations for cols may break static type-checkers

defaultdict[Th|Td|HeadlessTd, list[Td | Th]] uses PEP 604 unions directly in a sub-script position, which mypy, pyright and older versions of typing reject.
Prefer a single typing.Union (or stringified forward ref) to keep the code type-checker-friendly:

- self.cols: 'defaultdict[Th|Td|HeadlessTd, list[Td | Th]]' = defaultdict(list)
+ self.cols: 'defaultdict[t.Union[Th, Td, HeadlessTd], list[t.Union[Td, Th]]]' = defaultdict(list)

427-433: Exception re-raising loses original traceback

raise e inside the except clause discards the original traceback. Use exception chaining:

-except Exception as e:
-    logger.error(f"Exception occurred in `from_list`: {e}")
-    raise e
+except Exception as e:
+    logger.error("Exception occurred in `from_list`", exc_info=True)
+    raise e from None

This also satisfies Ruff B904.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 58e221c and 0b25d0f.

📒 Files selected for processing (10)
  • .github/workflows/publish.yml (0 hunks)
  • BetterMD/__init__.py (7 hunks)
  • BetterMD/elements/col.py (1 hunks)
  • BetterMD/elements/document.py (5 hunks)
  • BetterMD/elements/style.py (2 hunks)
  • BetterMD/elements/symbol.py (5 hunks)
  • BetterMD/elements/table.py (9 hunks)
  • BetterMD/elements/track.py (1 hunks)
  • BetterMD/typing.py (1 hunks)
  • setup.py (1 hunks)
💤 Files with no reviewable changes (1)
  • .github/workflows/publish.yml
🧰 Additional context used
🧬 Code Graph Analysis (1)
BetterMD/elements/document.py (1)
BetterMD/elements/symbol.py (4)
  • text (66-70)
  • get_prop (242-246)
  • classes (57-58)
  • inner_html (263-266)
🪛 Ruff (0.8.2)
BetterMD/elements/document.py

5-5: ..typing.ATTR_TYPES imported but unused

Remove unused import: ..typing.ATTR_TYPES

(F401)


66-66: Do not perform function call Copy in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)


157-157: Do not use mutable data structures for argument defaults

Replace with None; initialize within function

(B006)

BetterMD/elements/table.py

344-344: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

🔇 Additional comments (7)
BetterMD/elements/col.py (1)

16-16: Improved element type definition

Replacing the boolean self_closing attribute with a more descriptive type = "void" improves code readability and standardises element typing across the codebase. This change aligns well with modern HTML semantics.

BetterMD/typing.py (1)

3-3: Enhanced type system with recursive structure support

The updated ATTR_TYPES type alias now properly supports arbitrarily nested lists and dictionaries, which is an excellent improvement. Using string literals for forward references is the correct approach for recursive type definitions in Python.

setup.py (1)

3-3: Version bump for release 0.3.3

The version increment from 0.3.2 to 0.3.3 follows semantic versioning practices and correctly reflects the nature of the changes in this update.

BetterMD/elements/track.py (2)

7-7: Trailing whitespace removed

Good code hygiene removing unnecessary whitespace.


9-9: Improved element type definition

Replacing the boolean self_closing attribute with a more descriptive type = "void" improves code readability and standardises element typing across the codebase. This change aligns with the same pattern used in other void element classes.

BetterMD/__init__.py (1)

70-70: Possible breaking change in __all__ export list

Replacing "Symbol" with "elements" alters the public interface – callers doing
from BetterMD import Symbol will now break.
If backwards-compatibility is required, keep exporting Symbol for at least one minor version:

-__all__ = ["HTML", "MD", "elements", "Collection", ...]
+from .elements import Symbol  # re-export for BC
+__all__ = ["HTML", "MD", "elements", "Symbol", "Collection", ...]
BetterMD/elements/table.py (1)

588-589: Column width calculation can overflow on empty cells

max(("" if col is None else col.data).splitlines(), key=len, default="") fails when col is a Td/Th whose data is None.
Safeguard with str(col.data or "") to avoid TypeError.

Would you confirm whether Data.data ever returns None? If so, I'll propose a concrete patch.

Comment on lines +155 to +156
return self.attrs.get(attr, {}).get(value, [])

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

get_by_attr misses hash-normalisation

Look-ups with list/dict values will fail because keys are stored in their
hashable wrappers. Apply make_hashable before querying:

-def get_by_attr(self, attr: str, value: str):
-    return self.attrs.get(attr, {}).get(value, [])
+def get_by_attr(self, attr: str, value):
+    key = value if isinstance(value, (str, int, float, bool)) else make_hashable(value)
+    return self.attrs.get(attr, {}).get(key, [])
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return self.attrs.get(attr, {}).get(value, [])
def get_by_attr(self, attr: str, value):
key = value if isinstance(value, (str, int, float, bool)) else make_hashable(value)
return self.attrs.get(attr, {}).get(key, [])

Comment on lines +118 to +123
# Normalize keys in elm.props for attrs merging
normalized_props = {
prop: {make_hashable(value): [elm] for value in values}
for prop, values in elm.props.items()
}

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

normalized_props comprehension breaks for non-iterable attribute values

When a prop value is a scalar (str, int, bool), iterating over it yields
single characters/digits, producing nonsense keys.

Consider:

-normalized_props = {
-    prop: {make_hashable(value): [elm] for value in values}
-    for prop, values in elm.props.items()
-}
+normalized_props: dict[str, dict[HASHABLE_ATTRS, list[Symbol]]] = {}
+for prop, val in elm.props.items():
+    key = make_hashable(val)
+    normalized_props.setdefault(prop, {})[key] = [elm]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Normalize keys in elm.props for attrs merging
normalized_props = {
prop: {make_hashable(value): [elm] for value in values}
for prop, values in elm.props.items()
}
# Normalize keys in elm.props for attrs merging
normalized_props: dict[str, dict[HASHABLE_ATTRS, list[Symbol]]] = {}
for prop, val in elm.props.items():
key = make_hashable(val)
normalized_props.setdefault(prop, {})[key] = [elm]

Comment on lines +66 to 69
def __init__(self, data: 't.Union[GetProtocol[T1, T2], dict[T1, T2]]', default:'T5'=Copy(None)):
self.data = data
self.default = default.copy() if isinstance(default, CopyProtocol) else default

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid calling Copy() in default argument (B008)

Default arguments are evaluated at import time. Replace with None and
initialise inside the function to prevent accidental state sharing.

-def __init__(self, data: ..., default: T5 = Copy(None)):
+def __init__(self, data: ..., default: T5 | None = None):
     self.data = data
-    self.default = default.copy() if isinstance(default, CopyProtocol) else default
+    default = default or Copy(None)
+    self.default = default.copy() if isinstance(default, CopyProtocol) else default

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Ruff (0.8.2)

66-66: Do not perform function call Copy in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)

Comment on lines +157 to +158
def advanced_find(self, tag:'str', attrs:'dict[t.Literal["text"] | str, str | bool | int | float | tuple[str, str | bool | int | float] | list[str | bool | int | float | tuple[str, str | bool | int | float]]]' = {}):
def check_attr(e:'Symbol', k:'str', v:'str | bool | int | float | tuple[str, str | bool | int | float]'):
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Mutable default for attrs parameter (B006)

Using {} as a default value causes state to leak between calls.

-def advanced_find(self, tag: str,
-                  attrs: dict[...]= {}):
+def advanced_find(self, tag: str,
+                  attrs: dict[...]|None = None):
     ...
-    if "text" in attrs:
+    attrs = attrs or {}
+    if "text" in attrs:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def advanced_find(self, tag:'str', attrs:'dict[t.Literal["text"] | str, str | bool | int | float | tuple[str, str | bool | int | float] | list[str | bool | int | float | tuple[str, str | bool | int | float]]]' = {}):
def check_attr(e:'Symbol', k:'str', v:'str | bool | int | float | tuple[str, str | bool | int | float]'):
def advanced_find(self, tag: str,
attrs: dict[t.Literal["text"] | str,
str | bool | int | float |
tuple[str, str | bool | int | float] |
list[str | bool | int | float |
tuple[str, str | bool | int | float]]]
| None = None):
attrs = attrs or {}
def check_attr(e: 'Symbol',
k: 'str',
v: 'str | bool | int | float |
tuple[str, str | bool | int | float]'):
...
🧰 Tools
🪛 Ruff (0.8.2)

157-157: Do not use mutable data structures for argument defaults

Replace with None; initialize within function

(B006)

Comment on lines +211 to +223
@classmethod
def from_dict(cls, data:'dict[str, list[str]]'):
self = cls()
head = THead.from_list(list(data.keys()))
body = TBody.from_list(list(data.values()))

self.head = head
self.body = body

self.add_child(head)
self.add_child(body)

return self
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

from_dict transposes rows/columns incorrectly

dict.values() returns columns, but TBody.from_list() expects a list of rows.
This produces a body whose row count equals the original column count.

- body = TBody.from_list(list(data.values()))
+ # Flip columns → rows
+ body = TBody.from_list(list(map(list, zip(*data.values()))))

Also, consider preparing the table before returning:

self.prepare()

Comment on lines +306 to +318
def from_list(cls, lst:'list[list[list[str] | str]]'):
logger.debug(f"Creating Table from list of lists with shape {len(lst)}")
self = cls()
head = THead.from_list(lst[0])
body = TBody.from_list(lst[1])
foot = TFoot.from_list(lst[2])

self.head = head
self.body = body
self.foot = foot

return self

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

from_list is an instance method but behaves like a classmethod

Inside Table, def from_list(cls, …) is defined without the @classmethod decorator, so cls will actually be self.
Any call such as Table.from_list(lst) raises TypeError (“missing positional argument”).

- def from_list(cls, lst: 'list[list[list[str] | str]]'):
+ @classmethod
+ def from_list(cls, lst: 'list[list[list[str] | str]]'):
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def from_list(cls, lst:'list[list[list[str] | str]]'):
logger.debug(f"Creating Table from list of lists with shape {len(lst)}")
self = cls()
head = THead.from_list(lst[0])
body = TBody.from_list(lst[1])
foot = TFoot.from_list(lst[2])
self.head = head
self.body = body
self.foot = foot
return self
@classmethod
def from_list(cls, lst: 'list[list[list[str] | str]]'):
logger.debug(f"Creating Table from list of lists with shape {len(lst)}")
self = cls()
head = THead.from_list(lst[0])
body = TBody.from_list(lst[1])
foot = TFoot.from_list(lst[2])
self.head = head
self.body = body
self.foot = foot
return self

Comment on lines +205 to +210

def to_dict(self):
return {
k.data: [d.data for d in v] for k, v in self.cols.items()
}

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

to_dict() is unusable on an un-prepared table

self.cols is only populated during prepare(). Calling Table.to_dict() before the table is prepared silently returns an empty dict.

 def to_dict(self):
-     return {
-         k.data: [d.data for d in v] for k, v in self.cols.items()
-     }
+     if not self.prepared:
+         self.prepare()
+     return {k.data: [d.data for d in v] for k, v in self.cols.items()}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def to_dict(self):
return {
k.data: [d.data for d in v] for k, v in self.cols.items()
}
def to_dict(self):
if not self.prepared:
self.prepare()
return {k.data: [d.data for d in v] for k, v in self.cols.items()}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant