[Tutor] Is context manager the answer to synchronous function calls?

John Wong gokoproject at gmail.com
Wed Sep 16 21:50:14 CEST 2015


Ah. Thanks.. I removed the previous code. Please excuse me. I will rewrite
the question so it is clear.

Here is my current solution in an imperative way. My application will work
with AWS boto library to create EC2 instances and RDS instances. Assuming
my API will simply send the request, and return if the request is accepted,
I need to lock until the instance is ready before I can start the next
operation.

def create_vm(.....):
    # returns vm object

def modify_vm(.....):
    return new vm object

def get_vm_status(.....):
    return status


# NOTE: This is obviously a simplified version, but pretty much half
of the code.
def lock_until_ready(conn, get_status_func, _id, max_wait=60):
    wait_count = 1
    status = get_status_func(conn, _id)
    while status != 'available' and wait_count < max_wait:
        print("Querying status (attempt {i}): {status}".format(
            i=wait_count, status=status))
        wait_count += 1
        time.sleep(10)
        status = get_status_func(conn, _id)


def clone(data_center, image_id, options):

    conn = get_connection(data_center)
    vm_id = create_vm(conn, image_id, ....)
    lock_until_ready(conn, get_vm_status, vm_id, max_wait=30)
    modify_vm(conn, options)
    lock_until_ready(conn, get_vm_status, vm_id, max_wait=30)


I hope this doesn't come across as a code review. This works. I made my
lock function extensible and testable, but I feel like there should be a
better more user-friendly way, even in the imperative world in Python. I
thought of context manager because I can do some clean up on entry (verify
the db name has not been taken), and exit (if fail rollback). If you are
familiar with cloudformation, it almost seems like that's what I am doing.
I am writing this because I have custom needs that cloudformation can't do
elegantly without many hops. API is much more flexible for my current task,
FYI.

Any feedback is welcome. Thank you.

John

On Wed, Sep 16, 2015 at 10:53 AM, Chris Angelico <rosuav at gmail.com> wrote:

> On Thu, Sep 17, 2015 at 12:34 AM, John Wong <gokoproject at gmail.com> wrote:
> > Sorry first time posting to tutor / general list. Usually on TIP list. As
> > per Mark's recommendation, now posting to python-list at python.org.
>
> But, sadly, without a lot of context. When you change lists, it's
> helpful to include a lot of extra verbiage so folks who don't follow
> the other list can pick up where you were.
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20150916/639433ca/attachment.html>


More information about the Python-list mailing list