Keeping context-manager object alive through function calls

Ben Finney ben+python at benfinney.id.au
Tue Nov 10 17:47:09 EST 2015


Pablo Lucena <plucena24 at gmail.com> writes:

> In order to keep the SSH session open and not have to re-establish it
> across function calls, I would like to do add an argument to
> "do_stuff" which can optionally return the SSH session along with the
> data returned from the SSH session, as follows:
>
> def do_stuff(device, return_handle=False):
>     with manager(device) as conn:
>         output = conn.send_command("show ip route")
>         #process output...
>         if return_handle:
>             return (processed_output, conn)
>         else:
>             return processed_output

Since you're making it the caller's responsibility to deal with the
context manager, why not require the caller to *provide* the context
manager in the first place::

    def do_stuff(conn):
        """ Do stuff via the device connection `conn`.

            :param conn: The context manager for the device connection.
            :return: The processed output.

            """
        with conn:
            output = conn.send_command("show ip route")
            #process output...
        return processed_output

Also, note that if you just unconditionally want to return the output,
do it *outside* the ‘with’ block.

Then your caller is the one responsible for creating the connection
manager, and has the option of interrogating it further if it needs to::

    bsu5000_conn = make_connection("bsu5000")
    gen = do_stuff(bsu5000_conn)
    do_more_things_with(bsu5000_conn)

-- 
 \       “I don't know anything about music. In my line you don't have |
  `\                             to.” —Elvis Aaron Presley (1935–1977) |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list