Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

wasabi

Package Overview
Dependencies
Maintainers
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

wasabi

A lightweight console printing and formatting toolkit

  • 1.1.2
  • PyPI
  • Socket score

Maintainers
2

wasabi: A lightweight console printing and formatting toolkit

Over the years, I've written countless implementations of coloring and formatting utilities to output messages in our libraries like spaCy, Thinc and Prodigy. While there are many other great open-source options, I've always ended up wanting something slightly different or slightly custom.

This package is still a work in progress and aims to bundle those utilities in a standardised way so they can be shared across our other projects. It's super lightweight, has zero dependencies and works with Python 3.6+.

tests PyPi conda GitHub Code style: black

💬 FAQ

Are you going to add more features?

Yes, there's still a few of helpers and features to port over. However, the new features will be heavily biased by what we (think we) need. I always appreciate pull requests to improve the existing functionality – but I want to keep this library as simple, lightweight and specific as possible.

Can I use this for my projects?

Sure, if you like it, feel free to adopt it! Just keep in mind that the package is very specific and not intended to be a full-featured and fully customisable formatting library. If that's what you're looking for, you might want to try other packages – for example, colored, crayons, colorful, tabulate, console or py-term, to name a few.

Why wasabi?

I was looking for a short and descriptive name, but everything was already taken. So I ended up naming this package after one of my rats, Wasabi. 🐀

⌛️ Installation

pip install wasabi

🎛 API

function msg

An instance of Printer, initialized with the default config. Useful as a quick shortcut if you don't need to customize initialization.

from wasabi import msg

msg.good("Success!")

class Printer

method Printer.__init__
from wasabi import Printer

msg = Printer()
ArgumentTypeDescriptionDefault
prettyboolPretty-print output with colors and icons.True
no_printboolDon't actually print, just return.False
colorsdictAdd or overwrite color values, names mapped to 0-256.None
iconsdictAdd or overwrite icon. Name mapped to unicode.None
line_maxintMaximum line length (for divider).80
animationstrSteps of loading animation for Printer.loading."⠙⠹⠸⠼⠴⠦⠧⠇⠏"
animation_asciistrAlternative animation for ASCII terminals."|/-\\"
hide_animationboolDon't display animation, e.g. for logs.False
ignore_warningsboolDon't output messages of type MESSAGE.WARN.False
env_prefixstrPrefix for environment variables, e.g. WASABI_LOG_FRIENDLY."WASABI"
timestampboolAdd timestamp before output.False
RETURNSPrinterThe initialized printer.-
method Printer.text
msg = Printer()
msg.text("Hello world!")
ArgumentTypeDescriptionDefault
titlestrThe main text to print.""
textstrOptional additional text to print.""
color unicode / intColor name or value.None
iconstrName of icon to add.None
showboolWhether to print or not. Can be used to only output messages under certain condition, e.g. if --verbose flag is set.True
spacedboolWhether to add newlines around the output.False
no_printboolDon't actually print, just return. Overwrites global setting.False
exitsintIf set, perform a system exit with the given code after printing.None
method Printer.good, Printer.fail, Printer.warn, Printer.info

Print special formatted messages.

msg = Printer()
msg.good("Success")
msg.fail("Error")
msg.warn("Warning")
msg.info("Info")
ArgumentTypeDescriptionDefault
titlestrThe main text to print.""
textstrOptional additional text to print.""
showboolWhether to print or not. Can be used to only output messages under certain condition, e.g. if --verbose flag is set.True
exitsintIf set, perform a system exit with the given code after printing.None
method Printer.divider

Print a formatted divider.

msg = Printer()
msg.divider("Heading")
ArgumentTypeDescriptionDefault
textstrHeadline text. If empty, only the line is printed.""
charstrSingle line character to repeat."="
showboolWhether to print or not. Can be used to only output messages under certain condition, e.g. if --verbose flag is set.True
iconstrOptional icon to use with title.None
contextmanager Printer.loading
msg = Printer()
with msg.loading("Loading..."):
    # Do something here that takes longer
    time.sleep(10)
msg.good("Successfully loaded something!")
ArgumentTypeDescriptionDefault
textstrThe text to display while loading."Loading..."
method Printer.table, Printer.row

See Tables.

property Printer.counts

Get the counts of how often the special printers were fired, e.g. MESSAGES.GOOD. Can be used to print an overview like "X warnings"

msg = Printer()
msg.good("Success")
msg.fail("Error")
msg.warn("Error")

print(msg.counts)
# Counter({'good': 1, 'fail': 2, 'warn': 0, 'info': 0})
ArgumentTypeDescription
RETURNSCounterThe counts for the individual special message types.

Tables

function table

Lightweight helper to format tabular data.

from wasabi import table

data = [("a1", "a2", "a3"), ("b1", "b2", "b3")]
header = ("Column 1", "Column 2", "Column 3")
widths = (8, 9, 10)
aligns = ("r", "c", "l")
formatted = table(data, header=header, divider=True, widths=widths, aligns=aligns)
Column 1   Column 2    Column 3
--------   ---------   ----------
      a1      a2       a3
      b1      b2       b3
ArgumentTypeDescriptionDefault
dataiterable / dictThe data to render. Either a list of lists (one per row) or a dict for two-column tables.
headeriterableOptional header columns.None
footeriterableOptional footer columns.None
dividerboolShow a divider line between header/footer and body.False
widthsiterable / "auto"Column widths in order. If "auto", widths will be calculated automatically based on the largest value."auto"
max_colintMaximum column width.30
spacingintNumber of spaces between columns.3
alignsiterable / unicodeColumns alignments in order. "l" (left, default), "r" (right) or "c" (center). If If a string, value is used for all columns.None
multilineboolIf a cell value is a list of a tuple, render it on multiple lines, with one value per line.False
env_prefixunicodePrefix for environment variables, e.g. WASABI_LOG_FRIENDLY."WASABI"
color_valuesdictAdd or overwrite color values, name mapped to value.None
fg_colorsiterableForeground colors, one per column. None can be specified for individual columns to retain the default background color.None
bg_colorsiterableBackground colors, one per column. None can be specified for individual columns to retain the default background color.None
RETURNSstrThe formatted table.
function row
from wasabi import row

data = ("a1", "a2", "a3")
formatted = row(data)
a1   a2   a3
ArgumentTypeDescriptionDefault
dataiterableThe individual columns to format.
widthslist / int / "auto"Column widths, either one integer for all columns or an iterable of values. If "auto", widths will be calculated automatically based on the largest value."auto"
spacingintNumber of spaces between columns.3
alignslistColumns alignments in order. "l" (left), "r" (right) or "c" (center).None
env_prefixunicodePrefix for environment variables, e.g. WASABI_LOG_FRIENDLY."WASABI"
fg_colorslistForeground colors for the columns, in order. None can be specified for individual columns to retain the default foreground color.None
bg_colorslistBackground colors for the columns, in order. None can be specified for individual columns to retain the default background color.None
RETURNSstrThe formatted row.

class TracebackPrinter

Helper to output custom formatted tracebacks and error messages. Currently used in Thinc.

method TracebackPrinter.__init__

Initialize a traceback printer.

from wasabi import TracebackPrinter

tb = TracebackPrinter(tb_base="thinc", tb_exclude=("check.py",))
ArgumentTypeDescriptionDefault
color_errorstr / intColor name or code for errors (passed to color helper)."red"
color_tbstr / intColor name or code for traceback headline (passed to color helper)."blue"
color_highlightstr / intColor name or code for highlighted text (passed to color helper)."yellow"
indentintNumber of spaces to use for indentation.2
tb_basestrName of directory to use to show relative paths. For example, "thinc" will look for the last occurence of "/thinc/" in a path and only show path to the right of it.None
tb_excludetupleList of filenames to exclude from traceback.tuple()
RETURNSTracebackPrinterThe traceback printer.
method TracebackPrinter.__call__

Output custom formatted tracebacks and errors.

from wasabi import TracebackPrinter
import traceback

tb = TracebackPrinter(tb_base="thinc", tb_exclude=("check.py",))

error = tb("Some error", "Error description", highlight="kwargs", tb=traceback.extract_stack())
raise ValueError(error)
  Some error
  Some error description

  Traceback:
  ├─ <lambda> [61] in .env/lib/python3.6/site-packages/pluggy/manager.py
  ├─── _multicall [187] in .env/lib/python3.6/site-packages/pluggy/callers.py
  └───── pytest_fixture_setup [969] in .env/lib/python3.6/site-packages/_pytest/fixtures.py
         >>> result = call_fixture_func(fixturefunc, request, kwargs)
ArgumentTypeDescriptionDefault
titlestrThe message title.
*textsstrOptional texts to print (one per line).
highlightstrOptional sequence to highlight in the traceback, e.g. the bad value that caused the error.False
tbiterableThe traceback, e.g. generated by traceback.extract_stack().None
RETURNSstrThe formatted traceback. Can be printed or raised by custom exception.

class MarkdownRenderer

Helper to create Markdown-formatted content. Will store the blocks added to the Markdown document in order.

from wasabi import MarkdownRenderer

md = MarkdownRenderer()
md.add(md.title(1, "Hello world"))
md.add("This is a paragraph")
print(md.text)

method MarkdownRenderer.__init__

Initialize a Markdown renderer.

from wasabi import MarkdownRenderer

md = MarkdownRenderer()
ArgumentTypeDescriptionDefault
no_emojiboolDon't include emoji in titles.False
RETURNSMarkdownRendererThe renderer.

method MarkdownRenderer.add

Add a block to the Markdown document.

from wasabi import MarkdownRenderer

md = MarkdownRenderer()
md.add("This is a paragraph")
ArgumentTypeDescriptionDefault
textstrThe content to add.

property MarkdownRenderer.text

The rendered Markdown document.

md = MarkdownRenderer()
md.add("This is a paragraph")
print(md.text)
ArgumentTypeDescriptionDefault
RETURNSstrThe document as a single string.

method MarkdownRenderer.table

Create a Markdown-formatted table.

md = MarkdownRenderer()
table = md.table([("a", "b"), ("c", "d")], ["Column 1", "Column 2"])
md.add(table)
| Column 1 | Column 2 |
| --- | --- |
| a | b |
| c | d |
ArgumentTypeDescriptionDefault
dataIterable[Iterable[str]]The body, one iterable per row, containig an interable of column contents.
headerIterable[str]The column names.
alignsIterable[str]Columns alignments in order. "l" (left, default), "r" (right) or "c" (center).None
RETURNSstrThe table.

method MarkdownRenderer.title

Create a Markdown-formatted heading.

md = MarkdownRenderer()
md.add(md.title(1, "Hello world"))
md.add(md.title(2, "Subheading", "💖"))
# Hello world

## 💖 Subheading
ArgumentTypeDescriptionDefault
levelintThe heading level, e.g. 3 for ###.
textstrThe heading text.
emojistrOptional emoji to show before heading.None
RETURNSstrThe rendered title.

method MarkdownRenderer.list

Create a Markdown-formatted non-nested list.

md = MarkdownRenderer()
md.add(md.list(["item", "other item"]))
md.add(md.list(["first item", "second item"], numbered=True))
- item
- other item

1. first item
2. second item
ArgumentTypeDescriptionDefault
itemsIterable[str]The list items.
numberedboolWhether to use a numbered list.False
RETURNSstrThe rendered list.

Create a Markdown-formatted link.

md = MarkdownRenderer()
md.add(md.link("Google", "https://google.com"))
[Google](https://google.com)
ArgumentTypeDescriptionDefault
textstrThe link text.
urlstrThe link URL.
RETURNSstrThe rendered link.

method MarkdownRenderer.code_block

Create a Markdown-formatted code block.

md = MarkdownRenderer()
md.add(md.code_block("import spacy", "python"))
```python
import spacy
```
ArgumentTypeDescriptionDefault
textstrThe code text.
langstrOptional code language.""
RETURNSstrThe rendered code block.

method MarkdownRenderer.code, MarkdownRenderer.bold, MarkdownRenderer.italic

Create a Markdown-formatted text.

md = MarkdownRenderer()
md.add(md.code("import spacy"))
md.add(md.bold("Hello!"))
md.add(md.italic("Emphasis"))
`import spacy`

**Hello!**

_Emphasis_

Utilities

function color
from wasabi import color

formatted = color("This is a text", fg="white", bg="green", bold=True)
ArgumentTypeDescriptionDefault
textstrThe text to be formatted.-
fgstr / intForeground color. String name or 0 - 256.None
bgstr / intBackground color. String name or 0 - 256.None
boldboolFormat the text in bold.False
underlineboolFormat the text by underlining.False
RETURNSstrThe formatted string.
function wrap
from wasabi import wrap

wrapped = wrap("Hello world, this is a text.", indent=2)
ArgumentTypeDescriptionDefault
textstrThe text to wrap.-
wrap_maxintMaximum line width, including indentation.80
indentintNumber of spaces used for indentation.4
RETURNSstrThe wrapped text with line breaks.
function diff_strings
from wasabi import diff_strings

diff = diff_strings("hello world!", "helloo world")
ArgumentTypeDescriptionDefault
astrThe first string to diff.
bstrThe second string to diff.
fgstr / intForeground color. String name or 0 - 256."black"
bgtupleBackground colors as (insert, delete) tuple of string name or 0 - 256.("green", "red")
RETURNSstrThe formatted diff.

Environment variables

Wasabi also respects the following environment variables. The prefix can be customised on the Printer via the env_prefix argument. For example, setting env_prefix="SPACY" will expect the environment variable SPACY_LOG_FRIENDLY.

NameDescription
ANSI_COLORS_DISABLEDDisable colors.
WASABI_LOG_FRIENDLYMake output nicer for logs (no colors, no animations).
WASABI_NO_PRETTYDisable pretty printing, e.g. colors and icons.

🔔 Run tests

Fork or clone the repo, make sure you have pytest installed and then run it on the package directory. The tests are located in /wasabi/tests.

pip install pytest
cd wasabi
python -m pytest wasabi

FAQs


Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc