mdfy package

Subpackages

Submodules

Module contents

class mdfy.MdCode(code: str, inline: bool = False, syntax: str = '')[source]

Bases: MdElement

Represents Markdown code or code block.

code

The code string.

Type:

str

inline

Determines if the code should be represented as inline or block.

Type:

bool

syntax

The programming language syntax for the code block.

Type:

str

Examples

>>> code = MdCode("print('Hello World!')", inline=True)
>>> print(code)
`print('Hello World!')`
>>> code = MdCode("print('Hello World!')", inline=False, syntax="python")
>>> print(code)
```python
print('Hello World!')
```
__str__() str[source]

Returns a string representation of the code in Markdown format.

Returns:

String representation of the code.

Return type:

str

Warning

If the code is None, it will log a warning and set the code to an empty string.

class mdfy.MdElement[source]

Bases: object

Represents a Markdown element.

content

The content of the element.

Type:

str or MdElement

to_str() str[source]

Returns a string representation of the element in Markdown format.

Returns:

String representation of the element.

Return type:

str

class mdfy.MdHeader(content: str, level: int = 1)[source]

Bases: MdElement

Represents a Markdown header.

content

The content of the header.

Type:

str

level

The header level.

Type:

int

Examples

>>> from mdfy.elements import MdHeader
>>>
>>> header = MdHeader("This is a header")
>>> print(header)
# This is a header
>>>
>>> header = MdHeader("This is a header", level=2)
>>> print(header)
## This is a header
__str__() str[source]

Returns a string representation of the header in Markdown format.

Returns:

String representation of the header.

Return type:

str

class mdfy.MdHorizontal(content: str = '***')[source]

Bases: MdElement

Represents a Markdown horizontal rule.

content

The content for representing the horizontal rule.

Type:

str

Examples

>>> from mdfy.elements import MdHorizontal
>>>
>>> horizontal = MdHorizontal()
>>> print(horizontal)
***
>>>
>>> horizontal = MdHorizontal("---")
>>> print(horizontal)
---
class mdfy.MdImage(src: str, alt: str = '')[source]

Bases: MdElement

Represents a Markdown image.

src

The source URL or path of the image.

Type:

str

alt

The alternative text for the image.

Type:

str

Examples

>>> from mdfy.elements import MdImage
>>>
>>> image = MdImage("https://example.com/image.png")
>>> print(image)
![](https://example.com/image.png)
>>>
>>> image = MdImage("https://example.com/image.png", alt="Example image")
>>> print(image)
![Example image](https://example.com/image.png)
__str__() str[source]

Returns a string representation of the image in Markdown format.

Returns:

String representation of the image.

Return type:

str

Warning

If the image source is None, it will log a warning and set the source to an empty string.

Bases: MdElement

Represents a Markdown link.

url

The URL of the link.

Type:

str

text

The display text for the link.

Type:

str

title

The title attribute for the link.

Type:

str

Examples

>>> from mdfy.elements import MdLink
>>>
>>> link = MdLink("https://www.example.com", "example")
>>> print(link)
[example](https://www.example.com)
>>>
>>> link = MdLink("https://www.example.com", "example", title="example")
>>> print(link)
[example](https://www.example.com "example")
__str__() str[source]

Returns a string representation of the link in Markdown format.

Returns:

String representation of the link.

Return type:

str

Warning

If the link URL is None, it will log a warning and set the URL to an empty string.

class mdfy.MdList(items: list[str | MdList], depth: int = 0, indent: int = 4, numbered: bool = False)[source]

Bases: MdElement

Represents a Markdown list.

items

List of items, where each item can be a string or another MdList.

Type:

list[Union[str, MdList]]

depth

Current depth of the list.

Type:

int

indent

indent size of the list.

Type:

int

numbered

If True, the list will be numbered. Otherwise, it will be bulleted.

Type:

bool

Examples

>>> from mdfy.elements import MdList
>>>
>>> list = MdList(["item 1", "item 2"])
>>> print(list)
- item 1
- item 2
>>>
>>> list = MdList(["item 1", "item 2"], numbered=True)
>>> print(list)
1. item 1
1. item 2
>>>
>>> list = MdList([
...     "item 1",
...     [
...         "item 2.1",
...         "item 2.2"
...     ]
... ])
>>> print(list)
- item 1
    - item 2.1
    - item 2.2
__str__() str[source]

Returns a string representation of the list in Markdown format.

Returns:

Formatted markdown string for the entire list.

Return type:

str

class mdfy.MdQuote(content: str | MdElement)[source]

Bases: MdElement

Represents a Markdown blockquote.

content

The content of the quote.

Type:

str or MdElement

Examples

>>> from mdfy.elements import MdQuote
>>>
>>> quote = MdQuote("This is a quote.")
>>> print(quote)
> This is a quote.
>>>
>>> quote = MdQuote("This is a quote.\nThis is another line.")
>>> print(quote)
> This is a quote.
> This is another line.
__str__() str[source]

Returns a string representation of the blockquote in Markdown format.

Returns:

String representation of the blockquote.

Return type:

str

class mdfy.MdTable(data: Dict[str, Any] | list[Dict[str, Any]], header: list[str] | None = None, row_labels: list[str] | None = None, transpose: bool = False, precision: None | int = None)[source]

Bases: MdElement

Converter for dict or list to markdown table.

Parameters:
  • data (dict or list) – The data to convert.

  • header (list[str], optional) – Custom header labels. If not provided, dictionary keys will be used.

  • row_labels (list[str], optional) – Custom row labels. If not provided, no row labels will be shown.

  • transpose (bool, optional) – If True, transpose the table. Defaults to False.

  • precision (Optional[int]) – Number of decimal places for floats. If None, values are not formatted.

Examples

>>> data = {
...     "Name": "John Doe",
...     "Age": 30,
...     "Occupation": "Software Engineer",
... }
>>> table = MdTable(data)
>>> print(table)
| Name | Age | Occupation |
| --- | --- | --- |
| John Doe | 30 | Software Engineer |
>>> # Custom headers
>>> table = MdTable(data, header=["Full Name", "Years", "Job"])
>>> print(table)
| Full Name | Years | Job |
| --- | --- | --- |
| John Doe | 30 | Software Engineer |
>>> # With row labels
>>> data = [
...     {"Name": "John Doe", "Age": 30},
...     {"Name": "Jane Doe", "Age": 25}
... ]
>>> table = MdTable(data, row_labels=["Person 1", "Person 2"])
>>> print(table)
| | Name | Age |
| --- | --- | --- |
| Person 1 | John Doe | 30 |
| Person 2 | Jane Doe | 25 |
>>> # Transposed table
>>> print(MdTable(data, transpose=True))
| | | |
| --- | --- | --- |
| Name | John Doe | Jane Doe |
| Age | 30 | 25 |
class mdfy.MdTableOfContents(contents: list[str | MdElement] | None = None, render_all: bool = False)[source]

Bases: MdControlElement

Represents a table of contents in Markdown.

This element can generate a table of contents from a list of markdown elements. If contents are provided during initialization, it will generate the table of contents when stringified. Otherwise, it will return just the title.

title

The title of the table of contents.

Type:

str

level

The heading level for the table of contents title.

Type:

int

contents

The markdown contents to generate TOC from.

Type:

Optional[ContentType]

render(contents: list[str | MdElement] | None = None, index: int | None = None) str[source]

Generates a table of contents from a list of elements.

Parameters:
  • elements (list[ContentElementType]) – The list of elements to generate TOC from.

  • toc (MdTableOfContents) – The table of contents element with configuration.

Returns:

The generated table of contents.

Return type:

str

class mdfy.MdText(content: str, formatter: MdFormatter | None = None, no_style: bool = False)[source]

Bases: MdElement

MdElementt class to handle the text and styling of text.

content

The content string containing potential style markers.

Type:

str

formatter

The formatter to apply styling to the content.

Type:

MdFormatter

Examples

>>> # If you have installed mdfy[styled-text]
>>> from mdfy import MdText
>>> try:
>>>   import lark
>>> except ModuleNotFoundError:
>>>   print("Please install mdfy[styled-text] to use MdText with styles.")
>>>   exit(0)
>>>
>>> text = MdText("This is [bold:bold] text.")
>>> print(text)
This is **bold** text.
>>> MdText("[This is underline text:underline].").to_str()
<u>This is underline text</u>.
>>> MdText("[This is [nested:bold] style text:underline].").to_str()
<u>This is **nested** style text</u>.
>>> MdText("You can use aliases e.g. [st:st]  [bd:bo].").to_str()
You can use aliases e.g. ***st***  **bd**.

Note

Available style patterns:
  • strong: bold text (e.g. ***strong***)

  • bold: bold text (e.g. **bold**)

  • italic: italic text (e.g. *italic*)

  • not: strike-through text (e.g. ~~strike-through~~)

  • underline: underlined text (e.g. <u>underlined</u>)

  • code: inline code (e.g. code)

Also, the following aliases are available for the style patterns:
  • strong: st

  • bold: bo, bd

  • italic: it

  • not: no, nt

  • underline: un, ul

  • code: cd, quote

__add__(other: MdText) MdText[source]

Adds two MdText objects together.

Parameters:

other (MdText) – The other MdText object to be added.

Returns:

A new MdText object containing the concatenated content of the two objects.

Return type:

MdText

__str__() str[source]

Returns the styled content as per the specified style markers.

Returns:

Formatted markdown string with the appropriate styles applied.

Return type:

str

class mdfy.Mdfier(filepath: Path | None = None, textio: TextIOBase | None = None, encoding: str = 'utf-8')[source]

Bases: object

Writes Markdown content to a file.

Examples

>>> from mdfy import Mdfier, MdHeader, MdQuote, MdText
>>> # Writing Markdown content to a file
>>> mdfier = Mdfier("/tmp/quote.md")
>>> mdfier.write([
...     MdHeader("Hello, world!", 1),
...     MdQuote("This is a quote.")
... ])
>>>
>>> with open("/tmp/quote.md") as file:
...     print(file.read())
...
# Hello, world!
> This is a quote.

from mdfy import MdHeader, MdQuote, MdText >>> mdfier = Mdfier(“/tmp/nest.md”) >>> # Nested content will be flattened >>> mdfier.write([ … MdHeader(“Hello, world!”, 1), … [ … MdText(f”{i} * {i} = {i * i}”) … for i in range(1, 3) … ] … ]) >>> with open(“/tmp/nest.md”) as file: … print(file.read()) … # Hello, world! 1 * 1 = 1 2 * 2 = 4

__enter__() Mdfier[source]

Returns the Mdfier instance.

Returns:

The Mdfier instance.

Return type:

Mdfier

__exit__(exc_type: Type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None) None[source]

Writes the Markdown content to the file.

Parameters:
  • exc_type (type) – The type of the exception.

  • exc_value (Exception) – The exception that was raised.

  • traceback (Traceback) – The traceback of the exception.

classmethod from_file(file_object: TextIOBase) Mdfier[source]

Creates an instance of the Mdfier class to write Markdown content to a file object.

Parameters:

file_object (TextIOBase) – The file object or TextIOBase object to write to.

Returns:

An instance of the Mdfier class.

Return type:

Mdfier

classmethod from_filepath(filepath: str | Path, encoding: str = 'utf-8', create_dir_if_not_exist: bool = True) Mdfier[source]

Creates an instance of the Mdfier class to write Markdown content to a file.

Parameters:
  • filepath (Union[str, Path]) – The path to the file.

  • encoding (str) – The encoding of the file.

  • create_dir_if_not_exist (bool) – If True, creates the directory if it does not exist. Defaults to True.

Returns:

An instance of the Mdfier class.

Return type:

Mdfier

classmethod stringify(contents: str | MdElement | Iterable[str | MdElement | Iterable[MdContents]], separator: str = '\n\n') str[source]

Converts the given Markdown content to a string.

Parameters:

content (Union[str, MdElement]) – The Markdown content to convert to a string.

write(contents: str | MdElement | Iterable[str | MdElement | Iterable[MdContents]]) None[source]

Writes the given Markdown content to the file.

Parameters:

content (Union[str, MdElement]) – The Markdown content to write to the file.

mdfy.code(code: str, inline: bool = False, syntax: str = '') MdCode[source]

Creates a code element.

mdfy.header(content: str, level: int = 1) MdHeader[source]

Creates a header element.

mdfy.horizontal(content: str = '***') MdHorizontal[source]

Creates a horizontal rule element.

mdfy.image(src: str, alt: str = '') MdImage[source]

Creates an image element.

Creates a link element.

mdfy.list(items: list[str | MdList], depth: int = 0, indent: int = 4, numbered: bool = False) MdList

Creates a list item element.

mdfy.quote(content: str | MdElement) MdQuote[source]

Creates a quote element.

mdfy.table(data: dict[str, Any] | list[dict[str, Any]], header: list[str] | None = None, row_labels: list[str] | None = None, transpose: bool = False, precision: None | int = None) MdTable[source]

Creates a table element.

mdfy.text(content: str, formatter: MdFormatter | None = None, no_style: bool = False) MdText[source]

Creates a text element.

mdfy.toc(contents: list[Any] | None = None, render_all: bool = False) MdTableOfContents[source]

Creates a table of contents element.