Peter Corke
Peter Corke

Reputation: 584

How to configure IPython session using start_ipython()?

I have some code that launches an IPython session using start_ipython. It accepts a config option allowing to pass in a Config() object.

I can do things like:

c = Config()
c.InteractiveShellEmbed.colors = args.color
c.InteractiveShell.confirm_exit = args.confirmexit
c.InteractiveShell.prompts_class = MyPrompt
c.InteractiveShell.ast_node_interactivity = 'last_expr_or_assign'

IPython.start_ipython(config=c, user_ns=globals())

which changes prompts and display behaviour. All good.

I also wish to set some of the default formatters. The following works once I am in IPython

plain = get_ipython().display_formatter.formatters['text/plain']
plain.for_type(np.float64, plain.lookup_by_type(float))

but I want to set this up before launching IPython. The config object has a DisplayFormatter attribute but I don't understand how to configure it.

An ugly workaround is

code = [
    "plain = get_ipython().display_formatter.formatters['text/plain'];",
    "plain.for_type(np.float64, plain.lookup_by_type(float));",
    "precision('%.3g');"
       ]
c.InteractiveShellApp.exec_lines = code
IPython.start_ipython(config=c, user_ns=globals())

which does the trick but the IPython session starts with

Out[1]: <function IPython.core.formatters.PlainTextFormatter._type_printers_default.<locals>.<lambda>(obj, p, cycle)>
Out[1]: "('%.3g');"

which I'd prefer not to see (and despite semicolons on the ends of the lines).

I want to avoid the need to change any external configuration files, so that IPython works for the user out of the box with specific behaviour.

Upvotes: 1

Views: 231

Answers (1)

Crash0v3rrid3
Crash0v3rrid3

Reputation: 538

The formatter classes are configurable as well.

Passing the type to formatter func dict might work for you. Refer https://ipython.readthedocs.io/en/stable/config/options/terminal.html#configtrait-BaseFormatter.type_printers.

PlainTextFormatter also has an option to set the precision. Refer https://ipython.readthedocs.io/en/stable/config/options/terminal.html#configtrait-PlainTextFormatter.float_precision

Update #1:

c.PlainTextFormatter.float_precision = "%.3f"
c.BaseFormatter.type_printers = {np.float64: lambda obj, *args: str("%.3f" % obj)}

Upvotes: 2

Related Questions