Forum Archive

[Suggestion] Location Context Manager

blmacbeth

I was playing around with the location module the other day and was wondering about how it deals with scripts closing without manually turning off location tracking. So I made a context Manager for the location module

import location


class LocationManager (object):
    def __enter__(self):
        location.start_updates()

    def __exit__(self):
        location.stop_updates()

You can use it like so:

with LocationManager():
    # Do stuff that requires `location` here...
    ...

Now, this may be completely unnecessary, but I have found it useful for applications where constant location updates are not needed (e.g. get my location every 15 minutes or set my initial location for some one off script).

@omz also think this may be a good feature for the built-in location module to adopt (if possible). So we can have both location.start(stop)_updates() or with location: ....

Let me know what y'all think (criticism is welcome).

B.

EDIT
A bit less verbose code with the help of @ccc on contexlib

import contexlib
import location

@contexlib.contexmanager
def location_enabled():
    location.start_updates()
    yield
    location.stop_updates()

the use case is still the same.

with location_enabled():
    # Do location stuff here...
    ...
ccc

Similar thoughts at:
* https://forum.omz-software.com/topic/1951/getting-the-battery-level-and-battery-state-of-the-device and
* https://forum.omz-software.com/topic/3078/accessing-barometer-measurements Note @omz comments on auto shutoff after a few minutes of the app not being in the foreground.
* https://github.com/cclauss/Ten-lines-or-less/blob/master/battery_info.py

Webmaster4o

Very clean and Pythonic; I approve.