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

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

@@ -41,11 +41,12 @@ class Plugin(PluginBase):
41 41
         super().__init__(config, name)
42 42
 
43 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 50
         try:
50 51
             self._cache_max_age = self.options['cache_max_age']
51 52
         except KeyError:
@@ -72,7 +73,7 @@ class Plugin(PluginBase):
72 73
         """Return a handler if a recognized command is heard"""
73 74
         if text in self.corpus_strings:
74 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 77
                     self._temp_precision)
77 78
         else:
78 79
             return None
@@ -113,12 +114,11 @@ class DarkSkyHandler(Handler):
113 114
 
114 115
     def _format_temperature(self, temperature, unit='Fahrenheit'):
115 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 119
     def _format_percent(self, value):
120 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 123
     def _format_time(self, epoch_time):
124 124
         """Format a time in seconds since the epoch for the TTS system"""
@@ -141,7 +141,7 @@ class DarkSkyHandler(Handler):
141 141
             ante_post = 'AE ' + ante_post[1]
142 142
 
143 143
         # Put the parts together
144
-        return '{} {} {}'.format(hour, minute, ante_post)
144
+        return f'{hour} {minute} {ante_post}'
145 145
 
146 146
     def __call__(self, tts):
147 147
         """Update the cache if necessary and load it"""
@@ -203,10 +203,11 @@ class DarkSkyCurrentConditionsHandler(DarkSkyHandler):
203 203
     def __call__(self, tts):
204 204
         """Speak the current weather conditions"""
205 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 213
 class DarkSkySunsetHandler(DarkSkyHandler):

+ 6
- 7
kayleevc/recognizer.py View File

@@ -24,18 +24,17 @@ class Recognizer(GObject.GObject):
24 24
 
25 25
         src = config.options.microphone
26 26
         if src:
27
-            audio_src = 'alsasrc device="hw:{0},0"'.format(src)
27
+            audio_src = f'alsasrc device="hw:{src},0"'
28 28
         else:
29 29
             audio_src = 'autoaudiosrc'
30 30
 
31 31
         # Build the pipeline
32 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 39
         try:
41 40
             self.pipeline = Gst.parse_launch(cmd)

Loading…
Cancel
Save