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

Alan Gauld alan.gauld at btinternet.com
Wed Sep 16 12:56:09 CEST 2015


On 16/09/15 01:46, John Wong wrote:
> def create_vm(.....):
>      # returns vm object
>
> def modify_vm(.....):
>      return new vm object
>
> def get_vm_status(.....):
>      return status
> # Constraints:
> # I cannot modify vm until vm is finished,
> # I also cannot modify VM while the VM is being updated.
> # Obviously it looks ugly and wrong to include the while
> # in my functio. Those are user APIs.

You don't actually specify but I'm guessing VM
means Virtual Machine? Is it a specific type
of VM? eg VMWare/VirtualBox or somesuch, or is
it more of a sandbox environment like virtualenv?
That might help us understand the restrictions better.

> # Straight-forward option
> create_vm(...)
> status = get_vm_status(...)
> while status != "ready":
>      time.sleep(10)
>      status = get_vm_status(...)
> modify_vm(....)
> while status != "ready":
>      time.sleep(10)
>      status = get_vm_status(...)
> print("done!")
>
>
> I was thinking about context manager. But I feel like that's not the
> right choice.

A context manager might wait for the initial ready state and
handle the shutdown for you but I don't think it would be
so easy to deal with the intermediate pauses.

The simplest approach is to make the functions synchronous
and not return until the status changes, thus blocking
the client code. But that's not usually the most user friendly
approach, especially if using the code in an interactive
environment.

I would be tempted to use an asynchronous approach with a
when_ready() function that takes my function as an input
parameter. You could then run the when_ready in a thread
or, I suspect, utilize the asyncio or asyncore modules,
although I haven't tried using them for this kind of
thing myself.

The bottom line is you need to wait for the status to
change. How you do that wait is up to you but you can
make it more readable for the user. The easier it is for
the user the harder it will be for you.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list