Browse Source

Use f-strings instead of str.format

Now that I've freed myself from Pythons older than 3.6, I can use
f-strings for very clear and concise string formatting!  That's now how
it's done everywhere except one place in the shell plugin where
str.format is really the right thing to do.
Clara Hobbs 6 years ago
parent
commit
33e8293def
3 changed files with 23 additions and 23 deletions
  1. 2
    2
      kayleevc/kaylee.py
  2. 15
    14
      kayleevc/plugins/darksky.py
  3. 6
    7
      kayleevc/recognizer.py

+ 2
- 2
kayleevc/kaylee.py View File

112
     def _log_history(self, plugin, text):
112
     def _log_history(self, plugin, text):
113
         """Log the recognized sentence to the history file"""
113
         """Log the recognized sentence to the history file"""
114
         if self.options['history']:
114
         if self.options['history']:
115
-            self.history.append("{}: {}".format(plugin.name, text))
115
+            self.history.append(f"{plugin.name}: {text}")
116
             if len(self.history) > self.options['history']:
116
             if len(self.history) > self.options['history']:
117
                 # Pop off the first item
117
                 # Pop off the first item
118
                 self.history.pop(0)
118
                 self.history.pop(0)
133
         if self.options['invalid_sentence_command']:
133
         if self.options['invalid_sentence_command']:
134
             subprocess.call(self.options['invalid_sentence_command'],
134
             subprocess.call(self.options['invalid_sentence_command'],
135
                             shell=True)
135
                             shell=True)
136
-        print("no matching command {0}".format(text))
136
+        print(f"no matching command {text}")
137
 
137
 
138
     def recognizer_finished(self, recognizer, text):
138
     def recognizer_finished(self, recognizer, text):
139
         confidence_heap = queue.PriorityQueue()
139
         confidence_heap = queue.PriorityQueue()

+ 15
- 14
kayleevc/plugins/darksky.py View File

41
         super().__init__(config, name)
41
         super().__init__(config, name)
42
 
42
 
43
         self._cache_filename = os.path.join(config.cache_dir, 'darksky.json')
43
         self._cache_filename = os.path.join(config.cache_dir, 'darksky.json')
44
-        self._weather_url = 'https://api.darksky.net/forecast/{}/{},{}'.format(
45
-            self.options['api_key'],
46
-            self.options['latitude'],
47
-            self.options['longitude']
48
-        )
44
+
45
+        key = self.options['api_key']
46
+        lat = self.options['latitude']
47
+        lon = self.options['longitude']
48
+        self._url = f'https://api.darksky.net/forecast/{key}/{lat},{lon}'
49
+
49
         try:
50
         try:
50
             self._cache_max_age = self.options['cache_max_age']
51
             self._cache_max_age = self.options['cache_max_age']
51
         except KeyError:
52
         except KeyError:
72
         """Return a handler if a recognized command is heard"""
73
         """Return a handler if a recognized command is heard"""
73
         if text in self.corpus_strings:
74
         if text in self.corpus_strings:
74
             return self.commands[text](1, self._cache_filename,
75
             return self.commands[text](1, self._cache_filename,
75
-                    self._weather_url, self._cache_max_age,
76
+                    self._url, self._cache_max_age,
76
                     self._temp_precision)
77
                     self._temp_precision)
77
         else:
78
         else:
78
             return None
79
             return None
113
 
114
 
114
     def _format_temperature(self, temperature, unit='Fahrenheit'):
115
     def _format_temperature(self, temperature, unit='Fahrenheit'):
115
         """Format a temperature for the TTS system"""
116
         """Format a temperature for the TTS system"""
116
-        return '{:.{prec}f} degrees {}'.format(temperature, unit,
117
-                prec=self._temp_precision)
117
+        return f'{temperature:.{self._temp_precision}f} degrees {unit}'
118
 
118
 
119
     def _format_percent(self, value):
119
     def _format_percent(self, value):
120
         """Format a percentage value for the TTS system"""
120
         """Format a percentage value for the TTS system"""
121
-        return '{:.0f} percent'.format(100 * value)
121
+        return f'{100*value:.0f} percent'
122
 
122
 
123
     def _format_time(self, epoch_time):
123
     def _format_time(self, epoch_time):
124
         """Format a time in seconds since the epoch for the TTS system"""
124
         """Format a time in seconds since the epoch for the TTS system"""
141
             ante_post = 'AE ' + ante_post[1]
141
             ante_post = 'AE ' + ante_post[1]
142
 
142
 
143
         # Put the parts together
143
         # Put the parts together
144
-        return '{} {} {}'.format(hour, minute, ante_post)
144
+        return f'{hour} {minute} {ante_post}'
145
 
145
 
146
     def __call__(self, tts):
146
     def __call__(self, tts):
147
         """Update the cache if necessary and load it"""
147
         """Update the cache if necessary and load it"""
203
     def __call__(self, tts):
203
     def __call__(self, tts):
204
         """Speak the current weather conditions"""
204
         """Speak the current weather conditions"""
205
         super().__call__(tts)
205
         super().__call__(tts)
206
-        tts('{}, {}, relative humidity {}'.format(
207
-            self.cache['currently']['summary'],
208
-            self._format_temperature(self.cache['currently']['temperature']),
209
-            self._format_percent(self.cache['currently']['humidity'])))
206
+        summary = self.cache['currently']['summary']
207
+        temperature = self._format_temperature(
208
+                self.cache['currently']['temperature'])
209
+        humidity = self._format_percent(self.cache['currently']['humidity'])
210
+        tts(f'{summary}, {temperature}, relative humidity {humidity}')
210
 
211
 
211
 
212
 
212
 class DarkSkySunsetHandler(DarkSkyHandler):
213
 class DarkSkySunsetHandler(DarkSkyHandler):

+ 6
- 7
kayleevc/recognizer.py View File

24
 
24
 
25
         src = config.options.microphone
25
         src = config.options.microphone
26
         if src:
26
         if src:
27
-            audio_src = 'alsasrc device="hw:{0},0"'.format(src)
27
+            audio_src = f'alsasrc device="hw:{src},0"'
28
         else:
28
         else:
29
             audio_src = 'autoaudiosrc'
29
             audio_src = 'autoaudiosrc'
30
 
30
 
31
         # Build the pipeline
31
         # Build the pipeline
32
         cmd = (
32
         cmd = (
33
-            audio_src +
34
-            ' ! audioconvert' +
35
-            ' ! audioresample' +
36
-            ' ! pocketsphinx lm=' + config.lang_file + ' dict=' +
37
-            config.dic_file +
38
-            ' ! appsink sync=false'
33
+            f'{audio_src}'
34
+            f' ! audioconvert'
35
+            f' ! audioresample'
36
+            f' ! pocketsphinx lm={config.lang_file} dict={config.dic_file}'
37
+            f' ! appsink sync=false'
39
         )
38
         )
40
         try:
39
         try:
41
             self.pipeline = Gst.parse_launch(cmd)
40
             self.pipeline = Gst.parse_launch(cmd)

Loading…
Cancel
Save