[Tutor] Is context manager the answer to synchronous function calls?
Mark Lawrence
breamoreboy at yahoo.co.uk
Wed Sep 16 13:54:24 CEST 2015
On 16/09/2015 11:56, Alan Gauld wrote:
> 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.
>
Assuming your (Alan's) guess is correct, and I certainly agree it's
plausible, I suspect this might be better asked on the main Python
mailing list, I don't see this as tutor material.
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Tutor
mailing list