sc_printing

sc_printing

Printing/notification functions.

Highlights

  • sc.heading(): print text as a ‘large’ heading
  • sc.colorize(): print text in a certain color
  • sc.pr(): print full representation of an object, including methods and each attribute
  • sc.sigfig(): truncate a number to a certain number of significant figures
  • sc.progressbar(): show a (text-based) progress bar
  • sc.capture(): capture text output (e.g., stdout) as a variable

Classes

Name Description
capture Captures stdout (e.g., from print()) as a variable.
prettyobj Use pretty repr for objects, instead of just showing the type and memory pointer
progressbars Create multiple progress bars
quickobj Like sc.prettyobj(), but do not print attribute values.

capture

sc_printing.capture(seq='', *args, **kwargs)

Captures stdout (e.g., from print()) as a variable.

Based on contextlib.redirect_stdout, but saves the user the trouble of defining and reading from an IO stream. Useful for testing the output of functions that are supposed to print certain output.

Examples:

``python # Using with…as with sc.capture() as txt1: print(‘Assign these lines’) print(‘to a variable’)

Using start()…stop()

txt2 = sc.capture().start() print(‘This works’) print(‘the same way’) txt2.stop()

print(‘txt1:’) print(txt1) print(‘txt2:’) print(txt2) `` New in version 1.3.3.

prettyobj

sc_printing.prettyobj(*args, **kwargs)

Use pretty repr for objects, instead of just showing the type and memory pointer (the Python default for objects). Can also be used as the base class for custom classes.

See sc.quickobj() for a similar class that does not print attribute values (better for large objects that take a while to display).

Parameters

Name Type Description Default
args dict dictionaries which are used to assign attributes ()
kwargs any can also be used to assign attributes {}

Example 1:

``python myobj = sc.prettyobj(a=3) print(myobj)

<sciris.sc_printing.prettyobj at 0x7fbba4a97f40>

————————————————————————————————————————————————————————————

Methods:

Methods N/A

————————————————————————————————————————————————————————————

a: 3

————————————————————————————————————————————————————————————

`` Example 2:

``python myobj = sc.prettyobj(a=3) myobj.b = {‘a’:6} print(myobj)

<sciris.sc_printing.prettyobj at 0x7ffa1e243910>

————————————————————————————————————————————————————————————

Methods:

Methods N/A

————————————————————————————————————————————————————————————

a: 3

b: {‘a’: 6}

————————————————————————————————————————————————————————————

`` Example 3:

``python class MyObj(sc.prettyobj):

def __init__(self, a, b):
    self.a = a
    self.b = b

def mult(self):
    return self.a * self.b

myobj = MyObj(a=4, b=6) print(myobj)

<main.MyObj at 0x7fd9acd96c10>

————————————————————————————————————————————————————————————

Methods:

mult()

————————————————————————————————————————————————————————————

a: 4

b: 6

————————————————————————————————————————————————————————————

``

  • New in version 2.0.0: allow positional arguments
  • New in version 3.1.4: moved from sc_utils to sc_printing
  • New in version 3.1.6: linked back to sc_utils to prevent unpickling errors

progressbars

sc_printing.progressbars(n=1, total=1, label=None, leave=False, **kwargs)

Create multiple progress bars

Useful for tracking the progress of multiple long-running tasks. Unlike regular tqdm instances, this uses a pickable version so it can be used directly in multiprocessing instances.

Parameters

Name Type Description Default
n int number of progress bars to create 1
total float length of the progress bars 1
label str / list an optional prefix for the progress bar, or list of all labels None
leave bool whether to remove the progress bars when they’re done False
kwargs dict passed to tqdm.tqdm() {}

Note: bars are supposed to update in-place, but may appear on separate lines instead if not run in the terminal (e.g. if run in IPython environments like Spyder or Jupyter).

Example:

``python import sciris as sc import random

def run_sim(index, ndays, pbs): for i in range(ndays): val = random.random() sc.timedsleep(val*5/ndays) pbs.update(index) # Update this progress bar based on the index return

nsims = 5 ndays = 365

Create progress bars

pbs = sc.progressbars(nsims, total=ndays, label=‘Sim’)

Run tasks

sc.parallelize(run_sim, iterarg=range(nsims), ndays=ndays, pbs=pbs)

Produces output like:

Sim 0: 39%|███████████████████████████▊ | 143/365 [00:01<00:01, 137.17it/s]

Sim 1: 42%|████████████████████████████▉ | 154/365 [00:01<00:01, 148.70it/s]

Sim 2: 45%|████████████████████████████████ | 165/365 [00:01<00:01, 144.19it/s]

Sim 3: 44%|███████████████████████████████ | 160/365 [00:01<00:01, 151.22it/s]

Sim 4: 42%|████████████████████████████▏ | 145/365 [00:01<00:01, 136.75it/s]

`` New in version 3.0.0.

quickobj

sc_printing.quickobj(*args, **kwargs)

Like sc.prettyobj(), but do not print attribute values.

This class is better for large objects that take a while to display. It is somewhat similar to calling dir() on an object.

This class also defines a disp() method, which calls sc.pr() on the object.

Example:

python import numpy as np myobj = sc.quickobj(big1=np.random.rand(100,100), big2=sc.dataframe(a=np.arange(1000))) print(myobj)

  • New in version 3.1.5.

Methods

Name Description
disp Return full display of the object
disp
sc_printing.quickobj.disp(output=False, *args, **kwargs)

Return full display of the object

Functions

Name Description
arraymean Quickly calculate the mean and standard deviation of an array.
arraymedian Quickly calculate the median and confidence interval of an array.
blank Tiny function to print n blank lines, 3 by default
classatt Return a sorted string of class attributes for the Python repr method; see sc.prepr() for options
colorize Colorize output text.
createcollist Creates a string for a nice columnated list (e.g. to use in repr method)
heading Create a colorful heading. If just supplied with a string (or list of inputs like print()),
humanize_bytes Convert a number of bytes into a human-readable total.
indent Small wrapper to make textwrap more user friendly.
objatt Return a sorted string of object attributes for the Python repr method; see sc.prepr() for options
objectid Return the object ID as per the default Python __repr__ method
objmeth Return a sorted string of object methods for the Python repr method; see sc.prepr() for options
objprop Return a sorted string of object properties for the Python repr method; see sc.prepr() for options
objrepr Print out a detailed representation of an object: methods, properties, attributes, etc.
percentcomplete Display progress as a percentage.
pr Pretty-print a detailed representation of an object (“pr” is short for “print repr”).
prepr Pretty-print a detailed representation of an object.
printarr Print a numpy array nicely.
printblue Alias to print(colors.blue(s))
printbold Alias to print(colors.bold(s))
printcyan Alias to print(colors.cyan(s))
printdata Nicely print a complicated data structure, a la Matlab.
printgreen Alias to print(colors.green(s))
printmagenta Alias to print(colors.magenta(s))
printmean Alias to sc.arraymean() with doprint=True
printmedian Alias to sc.arraymedian() with doprint=True
printred Alias to print(colors.red(s))
printtologfile Append a message string to a file specified by a filename name/path.
printv Optionally print a message and automatically indent. The idea is that
printvars Print out a list of variables. Note that the first argument must be locals().
printyellow Alias to print(colors.yellow(s))
progressbar Show a progress bar for a for loop.
sigfig Return a string representation of variable x with sigfigs number of significant figures
sigfiground Round number(s) to the specified number of significant figures.
slacknotification Send a Slack notification when something is finished.
strip_ansi Remove ANSI codes (e.g. colors) from a string

arraymean

sc_printing.arraymean(
    data,
    stds=2,
    axis=None,
    mean_sf=None,
    err_sf=None,
    tostring=True,
    doprint=False,
    **kwargs,
)

Quickly calculate the mean and standard deviation of an array.

By default, will calculate the correct number of significant figures based on the deviation. The default is to multiply the standard deviation by 2, as an approximation of the 95% confidence level (z=1.96).

Parameters

Name Type Description Default
data array the data to summarize required
stds int the number of multiples of the standard deviation to show (default 2) 2
axis int the axis of the data to operate on (default None) None
mean_sf int if provided, use this number of significant figures for the mean rather than the auto-calculated None
err_sf int ditto, but for the error (standard deviation) None
doprint bool whether to print (else, return the string) False
kwargs dict passed to sc.sigfig() {}

Example:

python data = [1210, 1072, 1722, 1229, 1902] sc.arraymean(data) # Returns 1430 ± 320

  • New in version 3.0.0.
  • New in version 3.2.0: “axis” argument, “tostring” argument (allow numerical output)

arraymedian

sc_printing.arraymedian(data, ci=95, sf=3, doprint=False, **kwargs)

Quickly calculate the median and confidence interval of an array.

The confidence interval defaults to 95%. If an integer is supplied, this is treated as a percentile (e.g. 95=95% CI). If a float is supplied, it’s treated as a quantile (e.g. 0.95=95% CI). If a pair of ints or floats is provided, these are treated as upper and lower percentiles/quantiles. If ‘iqr’ is provided, then print the interquartile range (equivalent to 50% CI). If ‘range’ is provided then print the full range (equivalent to 100% CI).

Parameters

Name Type Description Default
data array the data to summarize required
ci int / float / list / str the confidence interval to use to use (see above for details) 95
sf int number of significant figures to use 3
doprint bool whether to print (else, return the string) False
kwargs dict passed to sc.sigfig() {}

Examples:

python data = [1210, 1072, 1722, 1229, 1902] sc.printmedian(data, 80) # Returns '1230 (80.0% CI: 1130, 1830)' New in version 3.0.0.

blank

sc_printing.blank(n=3)

Tiny function to print n blank lines, 3 by default

classatt

sc_printing.classatt(
    obj,
    strlen=_strlen,
    ncol=_ncol,
    private=False,
    sort=True,
    _objkeys=None,
    _dirkeys=None,
    return_keys=False,
)

Return a sorted string of class attributes for the Python repr method; see sc.prepr() for options

colorize

sc_printing.colorize(
    color=None,
    string=None,
    doprint=None,
    output=False,
    enable=True,
    showhelp=False,
    fg=None,
    bg=None,
    style=None,
)

Colorize output text.

Parameters

Name Type Description Default
color str the color you want (use ‘bg’ with background colors, e.g. ‘bgblue’); alternatively, use fg, bg, and style None
string str the text to be colored None
doprint bool whether to print the string (default true unless output) None
output bool whether to return the modified version of the string (default false) False
enable bool switch to allow sc.colorize() to be easily turned off without converting to a print() statement True
showhelp bool show help rather than changing colors False
fg str foreground colour None
bg str background colour None
style str font style (eg, italic, underline, bold) None

Examples:

python sc.colorize('green', 'hi') # Simple example sc.colorize(['yellow', 'bgblack']); print('Hello world'); print('Goodbye world'); colorize() # Colorize all output in between bluearray = sc.colorize(color='blue', string=str(range(5)), output=True); print("c'est bleu: " + bluearray) sc.colorize('magenta') # Now type in magenta for a while sc.colorize() # Stop typing in magenta sc.colorize('cat in the hat', fg='#ffa044', bg='blue', style='italic+underline') # Alternate usage example To get available colors, type sc.colorize(showhelp=True).

  • New in version 1.3.1: “doprint” argument; ansicolors shortcut

createcollist

sc_printing.createcollist(items, title=None, strlen=_strlen, ncol=_ncol)

Creates a string for a nice columnated list (e.g. to use in repr method)

heading

sc_printing.heading(
    string='',
    *args,
    color='cyan',
    divider='—',
    spaces=2,
    spacesafter=1,
    minlength=10,
    maxlength=200,
    sep=' ',
    tight=False,
    doprint=None,
    output=False,
    **kwargs,
)

Create a colorful heading. If just supplied with a string (or list of inputs like print()), create blue text with horizontal lines above and below and 3 spaces above. You can customize the color, the divider character, how many spaces appear before the heading, and the minimum length of the divider (otherwise will expand to match the length of the string, up to a maximum length).

Parameters

Name Type Description Default
string str the string to print as the heading (or object to convert to a string) ''
args list additional strings to print ()
color str color to use for the heading (default cyan) 'cyan'
divider str symbol to use for the divider (default ‘—’) '—'
spaces int number of spaces to put before the heading (default 2) 2
spacesafter int number of spaces to put after the heading (default 1) 1
minlength int minimum length of the divider (default 10) 10
maxlength int maximum length of the divider (default 200) 200
sep str if multiple arguments are supplied, use this separator to join them ' '
tight bool if True, use 1 space before the heading and none after (i.e. spaces=1, spacesafter=0) False
doprint bool whether to print the string (default true if no output) None
output bool whether to return the string as output (else, print) False
kwargs dict passed to sc.colorize() {}

Returns

Name Type Description
Formatted string if output=True

Examples:

python sc.heading('This is a heading') sc.heading(string='This is also a heading', color='red', divider='*', spaces=0, minlength=50) sc.heading('This is a compact heading', tight=True)

  • New in version 1.3.1.: “spacesafter”
  • New in version 3.3.0.: “tight”

humanize_bytes

sc_printing.humanize_bytes(bytesize, decimals=3)

Convert a number of bytes into a human-readable total.

Parameters

Name Type Description Default
bytesize int the number of bytes required
decimals int the number of decimal places to show 3

Example:

python sc.humansize(2.3423887e6, decimals=2) # Returns '2.34 MB' See the humansize library for more flexibility.

New in version 3.0.0.

indent

sc_printing.indent(
    prefix=None,
    text=None,
    suffix='\n',
    n=0,
    pretty=False,
    width=70,
    **kwargs,
)

Small wrapper to make textwrap more user friendly.

Parameters

Name Type Description Default
prefix str text to begin with (optional) None
text str text to wrap None
suffix str what to put on the end (by default, a newline) '\n'
n int if prefix is not specified, the size of the indent 0
pretty bool whether to use pprint to format the text False
width int maximum width before wrapping (if None, don’t wrap) 70
kwargs dict passed to textwrap.fill() {}

Examples:

``python prefix = ‘and then they said:’ text = ‘blah’*100 print(sc.indent(prefix, text))

print(‘my fave is:’ + sc.indent(text=rand(100), n=12)) `` New in version 1.3.1: more flexibility in arguments

objatt

sc_printing.objatt(
    obj,
    strlen=_strlen,
    ncol=_ncol,
    private=False,
    sort=True,
    _keys=None,
    return_keys=False,
)

Return a sorted string of object attributes for the Python repr method; see sc.prepr() for options

objectid

sc_printing.objectid(obj, showclasses=False)

Return the object ID as per the default Python __repr__ method

New in version 3.1.0: “showclasses” argument

objmeth

sc_printing.objmeth(
    obj,
    strlen=_strlen,
    ncol=_ncol,
    private=False,
    sort=True,
    _keys=None,
    return_keys=False,
)

Return a sorted string of object methods for the Python repr method; see sc.prepr() for options

objprop

sc_printing.objprop(
    obj,
    strlen=_strlen,
    ncol=_ncol,
    private=False,
    sort=True,
    _keys=None,
    return_keys=False,
)

Return a sorted string of object properties for the Python repr method; see sc.prepr() for options

objrepr

sc_printing.objrepr(
    obj,
    showid=True,
    showmeth=True,
    showprop=True,
    showatt=True,
    showclassatt=True,
    private=False,
    sort=True,
    dividerchar='—',
    dividerlen=_dividerlen,
    strlen=_strlen,
    ncol=_ncol,
    _objkeys=None,
    _dirkeys=None,
)

Print out a detailed representation of an object: methods, properties, attributes, etc.

Similar to sc.prepr(obj, vals=False).

See sc.prepr() for an explanation of arguments.

percentcomplete

sc_printing.percentcomplete(step=None, maxsteps=None, stepsize=1, prefix=None)

Display progress as a percentage.

Examples:

``python maxiters = 500

Will print on every 5th iteration

for i in range(maxiters): sc.percentcomplete(i, maxiters)

Will print on every 50th iteration

for i in range(maxiters): sc.percentcomplete(i, maxiters, stepsize=10)

Will print e.g. ‘Completeness: 1%’

for i in range(maxiters): sc.percentcomplete(i, maxiters, prefix=‘Completeness:’) `See alsosc.progressbar()` for a progress bar.

pr

sc_printing.pr(obj, *args, **kwargs)

Pretty-print a detailed representation of an object (“pr” is short for “print repr”).

See sc.prepr() for arguments and examples.

Note: sc.prepr() creates a string, while sc.pr() prints the output, i.e. sc.pr(obj) is an alias to print(sc.prepr(obj)).

prepr

sc_printing.prepr(
    obj,
    vals=True,
    maxlen=None,
    maxitems=None,
    skip=None,
    dividerchar='—',
    dividerlen=_dividerlen,
    use_repr=True,
    private=False,
    sort=True,
    strlen=_strlen,
    ncol=_ncol,
    maxtime=3,
    maxrecurse=5,
    die=False,
    debug=False,
)

Pretty-print a detailed representation of an object.

This function returns a pretty (and pretty detailed) representation of an object – all attributes (except any that are skipped), plus methods and ID.

This function is usually used via the interactive sc.pr() (which prints), rather than this function (which returns a string).

Parameters

Name Type Description Default
obj anything the object to be represented required
vals bool whether to show attribute values (else, just list attributes; similar to sc.objrepr()) True
maxlen int maximum number of characters to show for each attribute None
maxitems int maximum number of attribute to show in the object None
skip list any attributes to skip None
dividerchar str divider for methods, attributes, etc. '—'
dividerlen int number of divider characters _dividerlen
use_repr bool whether to use repr() or str() to parse the object True
private bool whether to include private methods/attributes (those starting with “__“) False
maxtime float maximum amount of time (in seconds) to spend on trying to print the object 3
maxrecurse int maximum number of levels to descend in the object (set to 0 to turn off the check) 5
die bool whether to raise an exception if an error is encountered False
debug bool print out detail during string construction False
  • New in version 3.0.0: “debug” argument
  • New in version 3.1.4: more robust handling of invalid object properties
  • New in version 3.1.5: “vals” argument to turn off printing attribute values
  • New in version 3.1.6: “maxrecurse” argument, and checking for recursion

Examples:

``python # Default options df = sc.dataframe(a=[1,2,3], b=[4,5,6]) print(df) # See just the data sc.pr(df) # See all the methods too sc.pr(df, vals=False) # Only see methods, not the values

Demonstrate options

obj = sc.prettyobj({k:k for k in [l + str(n) for n in range(10) for l in ‘abcde’]}) # Big object sc.pr(obj, maxitems=20, sort=False, dividerchar=‘•’, dividerlen=43, private=True) ``

printarr

sc_printing.printarr(
    arr,
    fmt=None,
    colsep='  ',
    vsep='—',
    decimals=2,
    doprint=True,
    dtype=None,
)

Print a numpy array nicely.

Parameters

Name Type Description Default
arr array the array to print required
fmt str the formatting string to use None
colsep str the separator between columns of values ' '
vsep str the vertical separator between 2D slices '—'
decimals int number of decimal places to print 2
doprint bool whether to print (else, return the string) True

Examples:

python numeric = np.random.randn(3,7,4)**10 mixed = np.array([['cat', 'nudibranch'], [23, 2423482]], dtype=object) sc.printarr(numeric) sc.printarr(mixed) New in version 2.0.3: “fmt”, “colsep”, “vsep”, “decimals”, and “dtype” arguments New in version 3.0.0: “doprint” argument

printblue

sc_printing.printblue(s, **kwargs)

Alias to print(colors.blue(s))

printbold

sc_printing.printbold(s, **kwargs)

Alias to print(colors.bold(s))

New in version 3.3.0.

printcyan

sc_printing.printcyan(s, **kwargs)

Alias to print(colors.cyan(s))

printdata

sc_printing.printdata(
    data,
    name='Variable',
    depth=1,
    maxlen=40,
    indent='',
    level=0,
    showcontents=False,
)

Nicely print a complicated data structure, a la Matlab.

Note: this function is deprecated.

Parameters

Name Type Description Default
data the data to display required
name the name of the variable (automatically read except for first one) 'Variable'
depth how many levels of recursion to follow 1
maxlen number of characters of data to display (if 0, don’t show data) 40
indent where to start the indent (used internally) ''

Version: 2015aug21

printgreen

sc_printing.printgreen(s, **kwargs)

Alias to print(colors.green(s))

printmagenta

sc_printing.printmagenta(s, **kwargs)

Alias to print(colors.magenta(s))

printmean

sc_printing.printmean(*args, doprint=True, **kwargs)

Alias to sc.arraymean() with doprint=True

printmedian

sc_printing.printmedian(*args, doprint=True, **kwargs)

Alias to sc.arraymedian() with doprint=True

printred

sc_printing.printred(s, **kwargs)

Alias to print(colors.red(s))

printtologfile

sc_printing.printtologfile(message=None, filename=None)

Append a message string to a file specified by a filename name/path.

Note: in almost all cases, you are better off using Python’s built-in logging system rather than this function.

printv

sc_printing.printv(string, thisverbose=1, verbose=2, indent=2, **kwargs)

Optionally print a message and automatically indent. The idea is that a global or shared “verbose” variable is defined, which is passed to subfunctions, determining how much detail to print out.

The general idea is that verbose is an integer from 0-4 as follows:

  • 0 = no printout whatsoever
  • 1 = only essential warnings, e.g. suppressed exceptions
  • 2 = standard printout
  • 3 = extra debugging detail (e.g., printout on each iteration)
  • 4 = everything possible (e.g., printout on each timestep)

Thus a very important statement might be e.g.

sc.printv(‘WARNING, everything is wrong’, 1, verbose)

whereas a much less important message might be

sc.printv(f’This is timestep {i}’, 4, verbose)

Parameters

Name Type Description Default
string str string to print required
thisverbose int level of verbosity at which to print this message 1
verbose int global verbose variable 2
indent int amount by which to indent based on verbosity level 2
kwargs dict passed to print() {}

New in version 3.0.0: “kwargs” argument; removed “newline” argument

printvars

sc_printing.printvars(
    localvars=None,
    varlist=None,
    label=None,
    divider=True,
    spaces=1,
    color=None,
)

Print out a list of variables. Note that the first argument must be locals().

Parameters

Name Type Description Default
localvars function must be called with locals() as first argument None
varlist the list of variables to print out None
label optional label to print out, so you know where the variables came from None
divider whether or not to offset the printout with a spacer (i.e. ——) True
spaces how many spaces to use between variables 1
color optionally label the variable names in color so they’re easier to see None

Example::

a = range(5) b = ‘example’ sc.printvars(locals(), [‘a’,‘b’], color=‘green’)

Another useful usage case is to print out the kwargs for a function:

sc.printvars(locals(), kwargs.keys())

Version: 2017oct28

printyellow

sc_printing.printyellow(s, **kwargs)

Alias to print(colors.yellow(s))

progressbar

sc_printing.progressbar(
    i=None,
    maxiters=None,
    label='',
    every=1,
    length=30,
    empty='—',
    full='•',
    newline=False,
    flush=False,
    output=False,
    **kwargs,
)

Show a progress bar for a for loop.

It can be called manually inside each iteration of the loop, or it can be used to wrap the object being iterated. In the latter case, it acts as an alias for the tqdm.tqdm() progress bar.

Parameters

Name Type Description Default
i int / iterable current iteration (for text output), or iterable object (for tqdm) None
maxiters int maximum number of iterations (can also use an object with length) None
label str initial label to print ''
every int / float if int, print every “every”th iteration (if 1, print all); if float and <1, print every maxiters*every iteration 1
length int length of progress bar 30
empty str character for not-yet-completed steps '—'
full str character for completed steps '•'
newline bool whether to print each iteration on a new line (else overwrite it; only works in terminals) False
flush bool whether to force-flush the buffer False
output bool whether to return the string (else print) False
kwargs dict passed to tqdm.tqdm(); see its documentation for full options {}

Examples:

``python # Direct usage inside a loop for i in range(20): sc.progressbar(i+1, 20) sc.timedsleep(0.05)

Direct usage inside a loop with custom formatting

for i in range(1000): sc.progressbar(i+1, 1000, every=100, length=10, empty=’ ‘, full=’✓’, newline=True) sc.timedsleep(0.001)

Used to wrap an iterable, using tqdm

x = np.arange(100) for i in sc.progressbar(x): plt.pause(0.01) `` Adapted from example by Greenstick (https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console)

  • New in version 1.3.3: “every” argument
  • New in version 3.0.0: wrapper for tqdm
  • New in version 3.3.0: “output” argument

sigfig

sc_printing.sigfig(
    x,
    sigfigs=4,
    SI=False,
    sep=False,
    keepints=False,
    formats=None,
)

Return a string representation of variable x with sigfigs number of significant figures

Note: sc.sigfig() and sc.sigfigs() are aliases.

Parameters

Name Type Description Default
x int / float / list / arr the number(s) to round required
sigfigs int number of significant figures to round to (if None, use ‘g’ format) 4
SI bool whether to use SI notation (only for numbers >1) False
sep bool / str if provided, use as thousands separator False
keepints bool never round ints False
formats str / list custom format suffixes; if str (e.g. ‘kmb’), split into chars; if list (e.g. [‘k’,‘m’,‘bn’]), use as-is for 1e3, 1e6, etc. None

Examples:

``python x = 3432.3842 sc.sigfig(x, SI=True) # Returns ‘3.432K’ sc.sigfig(x, sep=True) # Returns ‘3,432’ sc.sigfig(x, SI=True, formats=‘kmb’) # Returns ‘3.432k’ (lowercase) sc.sigfig(x, sigfigs=None) # Returns ‘3432.38’ (uses ‘g’ format)

vals = np.random.rand(5) sc.sigfig(vals, sigfigs=3) ``

  • New in version 3.0.0: changed default number of significant figures from 5 to 4; return list rather than tuple; changed SI suffixes to uppercase
  • New in version 3.2.6: “formats” argument; use ‘g’ format when sigfigs=None

sigfiground

sc_printing.sigfiground(x, sigfigs=4)

Round number(s) to the specified number of significant figures.

Parameters

Name Type Description Default
x int / float / list / arr the number(s) to round required
sigfigs int number of significant figures to round to 4

Examples:

python sc.sigfiground(3.28343) # Returns 3.283 sc.sigfiground(834_875, 5) # Returns 834880 sc.sigfiground([3.28343, 834_874, 0, -83_742], 2) # Returns [3.3, 830000, 0, -84000]

  • New in version 3.2.0.

slacknotification

sc_printing.slacknotification(
    message=None,
    webhook=None,
    to=None,
    fromuser=None,
    verbose=2,
    die=False,
)

Send a Slack notification when something is finished.

The webhook is either a string containing the webhook itself, or a plain text file containing a single line which is the Slack webhook. By default it will look for the file “.slackurl” in the user’s home folder. The webhook needs to look something like “https://hooks.slack.com/services/af7d8w7f/sfd7df9sb/lkcpfj6kf93ds3gj”. Webhooks are effectively passwords and must be kept secure! Alternatively, you can specify the webhook in the environment variable SLACKURL.

Parameters

Name Type Description Default
message str The message to be posted. None
webhook str See above None
to str The Slack channel or user to post to. Channels begin with #, while users begin with @ (note: ignored by new-style webhooks) None
fromuser str The pseudo-user the message will appear from (note: ignored by new-style webhooks) None
verbose bool How much detail to display. 2
die bool If false, prints warnings. If true, raises exceptions. False

Example:

python sc.slacknotification('Long process is finished') sc.slacknotification(webhook='/.slackurl', channel='@username', message='Hi, how are you going?') What’s the point? Add this to the end of a very long-running script to notify your loved ones that the script has finished.

Version: 2018sep25

strip_ansi

sc_printing.strip_ansi(string)

Remove ANSI codes (e.g. colors) from a string

Parameters

Name Type Description Default
string str the string to remove the ANSI codes from required

Example:

python colored = sc.colorize('red', 'hello', output=True) plain = sc.strip_ansi(colored) # Returns 'hello' New in version 3.3.0.