fohrloop / wakepy

Cross-platform keep-awake with python
MIT License
195 stars 14 forks source link

Conditionally using wakepy modes #372

Open fohrloop opened 4 months ago

fohrloop commented 4 months ago

It's probably quite usual use case to do something like:

if some_flag:
    with keep.running():
        do_something()
else:
    do_something()

I thought first that there could be some conditional flag added to the modes, like

with keep.running(only_if=some_flag):
    do_something()

but that raises questions like: What does "success" mean here is the flag is set and the mode is not entered?

It would be probably enough to document a recipe for conditionally using a wakepy mode using the solution from the standard library: nullcontext -- which conveniently supports Python 3.7+ (all versions which wakepy supports). The recipe is:

mode = keep.running() if some_flag else contextlib.nullcontext()

with mode:
    do_something()

EDIT: The nullcontext is not a 100% drop-in replacement as you cannot do, for example:

mode = keep.running() if some_flag else contextlib.nullcontext()

with mode as m:
    print('Used method:', m.used_method)
    do_something()

because the with statement target (m) does will be a Mode instance when using keep.running() and None by default when using the nullcontext. As the nullcontext gives any input argument as the with statement target, there it could be:

import contextlib
from wakepy import keep, DummyMode

mode = keep.running() if some_flag else contextlib.nullcontext(DummyMode())

with mode:
    do_something()

This already needs two imports and requires that the user knows about the contextlib.nullcontext. It would be probably more user-friendly to provide the dummy / no-op mode from wakepy, so one could write:

from wakepy import keep, DummyMode

mode = keep.running() if some_flag else DummyMode()

with mode:
    do_something()

Questions to be answered:

1. What is the nicest name for this?

2. What attributes/attribute values the DummyMode should have?

From the docs, the Modes have the following attributes (among others):

3. Is this any better than using keep.running(only_if=some_flag)?

This is starting to become more complicated. Would the initial idea be simper from the user's perspective?

Task


Comments / suggestions welcome!