Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #98616 > unrolled thread

Re: Keeping context-manager object alive through function calls

Started byBen Finney <ben+python@benfinney.id.au>
First post2015-11-11 09:47 +1100
Last post2015-11-11 09:47 +1100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Keeping context-manager object alive through function calls Ben Finney <ben+python@benfinney.id.au> - 2015-11-11 09:47 +1100

#98616 — Re: Keeping context-manager object alive through function calls

FromBen Finney <ben+python@benfinney.id.au>
Date2015-11-11 09:47 +1100
SubjectRe: Keeping context-manager object alive through function calls
Message-ID<mailman.222.1447195686.16136.python-list@python.org>
Pablo Lucena <plucena24@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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web