more flexible functions, allow passing arguments to functions

This commit is contained in:
2017-04-19 02:16:50 -04:00
parent 64c094d3d0
commit e093cac35b
6 changed files with 94 additions and 41 deletions

View File

@@ -12,6 +12,25 @@ UPDATE_INTERVAL = 60 * 20
__weather = {}
class AttrDict(dict):
""" Dictionary subclass whose entries can be accessed by attributes
(as well as normally).
"""
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
@staticmethod
def from_nested_dict(data):
""" Construct nested AttrDicts from nested dictionaries. """
if not isinstance(data, dict):
return data
else:
return AttrDict({key: AttrDict.from_nested_dict(data[key])
for key in data})
def update_weather(force=False):
global __weather
now = datetime.now()
@@ -22,6 +41,7 @@ def update_weather(force=False):
if force or interval <= 0 or interval > UPDATE_INTERVAL:
__weather = pywapi.get_weather_from_weather_com(LOCATION, UNITS)
__weather.setdefault('current_conditions', {}).setdefault('last_checked', str(now))
__weather = AttrDict.from_nested_dict(__weather)
print('updated weather at', now)
@@ -33,4 +53,4 @@ def get_weather(force_update=False):
if __name__ == '__main__':
while True:
print('{0[current_conditions][temperature]}\u00b0{0[units][temperature]}'.format(get_weather()))
print('{current_conditions.temperature}\u00b0{units.temperature}'.format(**get_weather()))