Running IPython REPL in a context manager

49 Views Asked by At

I need to launch an IPython repl with some context provided for use in the session. basically my app after some bootstrapping. Currently, I can do the following:

from my_stuff import app

async with app.run() as scoped:
    print(scoped)  # Prints my scope object

However, this doesn't work:

async with app.run() as scoped:
    loop = asyncio.get_running_loop()
    loop.run_in_executor(
        None,
        lambda: start_ipython(
            user_ns={'app': scoped},
            config=Config(config),
            argv=[]
        )
    )

When the session starts, the variable app is defined, but it doesn't have the "context" I expected.

Good to know maybe:

Entering my app like so async with app.run() essentially creates a MyContext object and sets it as a value of a ContextVar I'm using to hold some context that belongs to the current coroutine.

I have tried many different semantics and syntaxes, the only one that gave me the results I wanted is, in a startup script myscript.ipy:

from my_stuff import app

ctx = app.run()
app = await ctx.__aenter__()

yield

This throws:

SyntaxError: 'yield' outside function

But the session continues and my app variable is actually what I want it to be.

I have also tried the same using IPython.embed instead of start_ipython with the same results.

Is it achievable what I'm trying to do? Or should I consider a totally different approach?

0

There are 0 best solutions below