Sourcery Starbot ⭐ refactored RumiAllbert/wttr.in#3
Conversation
SourceryAI
left a comment
There was a problem hiding this comment.
Due to GitHub API limits, only the first 60 comments can be shown.
| print("cache found: %s" % location) | ||
| print(f"cache found: {location}") | ||
|
|
||
| if answer is None: | ||
| answer = query_osm(location) | ||
|
|
There was a problem hiding this comment.
Function find_location refactored with the following changes:
- Replace interpolated string formatting with f-string (
replace-interpolation-with-fstring) - Remove unnecessary else after guard condition (
remove-unnecessary-else)
| but is using the fake data from "test/proxy-data". | ||
|
|
||
| """ | ||
|
|
There was a problem hiding this comment.
Lines 37-37 refactored with the following changes:
- Replace interpolated string formatting with f-string (
replace-interpolation-with-fstring)
| f_name = 'share/translations/%s.txt' % f_name | ||
| f_name = f'share/translations/{f_name}.txt' |
There was a problem hiding this comment.
Function load_translations refactored with the following changes:
- Replace interpolated string formatting with f-string (
replace-interpolation-with-fstring)
| digest = hashlib.sha1(("%s %s" % (path, query)).encode("utf-8")).hexdigest() | ||
| digest = hashlib.sha1(f"{path} {query}".encode("utf-8")).hexdigest() | ||
| digest_number = ord(digest[0].upper()) | ||
| expiry_interval = 60*(digest_number+90) | ||
|
|
||
| timestamp = "%010d" % (int(time.time())//expiry_interval*expiry_interval) | ||
| filename = os.path.join(PROXY_CACHEDIR, timestamp, path, query) | ||
|
|
||
| return filename | ||
| return os.path.join(PROXY_CACHEDIR, timestamp, path, query) |
There was a problem hiding this comment.
Function _cache_file refactored with the following changes:
- Replace interpolated string formatting with f-string (
replace-interpolation-with-fstring) - Inline variable that is immediately returned (
inline-immediately-returned-variable)
| return (open(cache_file, 'r').read(), | ||
| json.loads(open(cache_file+".headers", 'r').read())) | ||
| return open(cache_file, 'r').read(), json.loads( | ||
| open(f"{cache_file}.headers", 'r').read() | ||
| ) |
There was a problem hiding this comment.
Function _load_content_and_headers refactored with the following changes:
- Use f-string instead of string concatenation (
use-fstring-for-concatenation)
| help_file = os.path.join(MYDIR, 'share/translations/%s-help.txt' % lang) | ||
| if os.path.exists(help_file): | ||
| return help_file | ||
| return HELP_FILE | ||
| help_file = os.path.join(MYDIR, f'share/translations/{lang}-help.txt') | ||
| return help_file if os.path.exists(help_file) else HELP_FILE |
There was a problem hiding this comment.
Function get_help_file refactored with the following changes:
- Replace interpolated string formatting with f-string (
replace-interpolation-with-fstring) - Lift code into else after jump in control flow (
reintroduce-else) - Replace if statement with if expression (
assign-if-exp)
| if limits: | ||
| self.limit = _time_caps(*limits) | ||
| else: | ||
| self.limit = _time_caps(30, 600, 1000) | ||
|
|
||
| if whitelist: | ||
| self.whitelist = whitelist[:] | ||
| else: | ||
| self.whitelist = [] | ||
|
|
||
| self.limit = _time_caps(*limits) if limits else _time_caps(30, 600, 1000) | ||
| self.whitelist = whitelist[:] if whitelist else [] |
There was a problem hiding this comment.
Function Limits.__init__ refactored with the following changes:
- Replace if statement with if expression [×2] (
assign-if-exp)
| log("%s LIMITED [%s for %s]" % (ip_address, self._get_limit(interval), interval)) | ||
| log(f"{ip_address} LIMITED [{self._get_limit(interval)} for {interval}]") |
There was a problem hiding this comment.
Function Limits._report_excessive_visits refactored with the following changes:
- Replace interpolated string formatting with f-string (
replace-interpolation-with-fstring)
| return ("Not so fast! Number of queries per %s is limited to %s" | ||
| % (interval, self._get_limit(interval))) | ||
| return f"Not so fast! Number of queries per {interval} is limited to {self._get_limit(interval)}" |
There was a problem hiding this comment.
Function Limits.check_ip refactored with the following changes:
- Replace interpolated string formatting with f-string (
replace-interpolation-with-fstring)
| geo = requests.get('%s/%s' % (GEOLOCATOR_SERVICE, location)).text | ||
| geo = requests.get(f'{GEOLOCATOR_SERVICE}/{location}').text | ||
| except requests.exceptions.ConnectionError as exception: | ||
| print("ERROR: %s" % exception) | ||
| print(f"ERROR: {exception}") | ||
| return None | ||
|
|
||
| if geo == "": | ||
| return None | ||
|
|
||
| try: | ||
| answer = json.loads(geo.encode('utf-8')) | ||
| return answer | ||
| return json.loads(geo.encode('utf-8')) | ||
| except ValueError as exception: | ||
| print("ERROR: %s" % exception) | ||
| print(f"ERROR: {exception}") |
There was a problem hiding this comment.
Function _geolocator refactored with the following changes:
- Replace interpolated string formatting with f-string [×3] (
replace-interpolation-with-fstring) - Inline variable that is immediately returned (
inline-immediately-returned-variable)
| file.write(location[3] + ';' + location[2] + ';' + location[1] + ';' + location[0]) | ||
| file.write(f'{location[3]};{location[2]};{location[1]};{location[0]}') |
There was a problem hiding this comment.
Function _ipcachewrite refactored with the following changes:
- Use f-string instead of string concatenation [×6] (
use-fstring-for-concatenation)
| _debug_log("[_ipcache] %s not found" % ip_addr) | ||
| _debug_log(f"[_ipcache] {ip_addr} not found") |
There was a problem hiding this comment.
Function _ipcache refactored with the following changes:
- Replace interpolated string formatting with f-string (
replace-interpolation-with-fstring)
| _debug_log("[_ip2location] %s search" % ip_addr) | ||
| _debug_log(f"[_ip2location] {ip_addr} search") | ||
| r = requests.get( | ||
| 'http://api.ip2location.com/?ip=%s&key=%s&package=WS3' # WS5 provides latlong | ||
| % (ip_addr, IP2LOCATION_KEY)) | ||
| f'http://api.ip2location.com/?ip={ip_addr}&key={IP2LOCATION_KEY}&package=WS3' | ||
| ) | ||
| r.raise_for_status() | ||
| location = r.text | ||
|
|
||
| parts = location.split(';') | ||
| if len(parts) >= 4: | ||
| # ccode, country, region, city, (rest) | ||
| _debug_log("[_ip2location] %s found" % ip_addr) | ||
| _debug_log(f"[_ip2location] {ip_addr} found") |
There was a problem hiding this comment.
Function _ip2location refactored with the following changes:
- Replace interpolated string formatting with f-string [×3] (
replace-interpolation-with-fstring)
This removes the following comments ( why? ):
# WS5 provides latlong
| r = requests.get( | ||
| 'https://ipinfo.io/%s/json?token=%s' | ||
| % (ip_addr, IPINFO_TOKEN)) | ||
| r = requests.get(f'https://ipinfo.io/{ip_addr}/json?token={IPINFO_TOKEN}') |
There was a problem hiding this comment.
Function _ipinfo refactored with the following changes:
- Replace interpolated string formatting with f-string (
replace-interpolation-with-fstring)
| _debug_log("[_geoip] %s search" % ip_addr) | ||
| _debug_log(f"[_geoip] {ip_addr} search") | ||
| response = GEOIP_READER.city(ip_addr) | ||
| # print(response.subdivisions) | ||
| city, region, country, ccode, lat, long = response.city.name, response.subdivisions[0].names["en"], response.country.name, response.country.iso_code, response.location.latitude, response.location.longitude | ||
| _debug_log("[_geoip] %s found" % ip_addr) | ||
| _debug_log(f"[_geoip] {ip_addr} found") |
There was a problem hiding this comment.
Function _geoip refactored with the following changes:
- Replace interpolated string formatting with f-string [×2] (
replace-interpolation-with-fstring)
| converted_hours = [] | ||
| for hour in hours: | ||
| converted_hours.append(_convert_hour(hour)) | ||
| return converted_hours | ||
| return [_convert_hour(hour) for hour in hours] |
There was a problem hiding this comment.
Function _convert_hourly refactored with the following changes:
- Convert for loop into list comprehension (
list-comprehension) - Inline variable that is immediately returned (
inline-immediately-returned-variable)
| elif us_ip: | ||
| query['use_imperial'] = True | ||
| query['use_metric'] = False | ||
| else: | ||
| if us_ip: | ||
| query['use_imperial'] = True | ||
| query['use_metric'] = False | ||
| else: | ||
| query['use_imperial'] = False | ||
| query['use_metric'] = True | ||
| query['use_imperial'] = False | ||
| query['use_metric'] = True |
There was a problem hiding this comment.
Function metric_or_imperial refactored with the following changes:
- Merge else clause's nested if statement into elif (
merge-else-if-into-elif)
| parsed.update(parse_query(to_be_parsed)) | ||
| parsed |= parse_query(to_be_parsed) |
There was a problem hiding this comment.
Function parse_wttrin_png_name refactored with the following changes:
- Merge dictionary updates via the union operator (
dict-assign-update-to-union)
| '?key=%s&q=%s&format=json' | ||
| '&num_of_days=3&tp=3&lang=%s') % (key, location, lang) | ||
| url = 'http://127.0.0.1:5001' + url | ||
| url = f'http://127.0.0.1:5001{url}' |
There was a problem hiding this comment.
Function get_weather_data refactored with the following changes:
- Use f-string instead of string concatenation (
use-fstring-for-concatenation)
| user_agent = parsed_query.get("user_agent", "").lower() | ||
| html_output = not any(agent in user_agent for agent in PLAIN_TEXT_AGENTS) | ||
| return html_output | ||
| return all(agent not in user_agent for agent in PLAIN_TEXT_AGENTS) |
There was a problem hiding this comment.
Function get_output_format refactored with the following changes:
- Inline variable that is immediately returned (
inline-immediately-returned-variable) - Invert any/all to simplify comparisons (
invert-any-all)
| else: | ||
| if query.get('days', '3') != '0' \ | ||
| elif query.get('days', '3') != '0' \ | ||
| and not query.get('no-follow-line') \ | ||
| and ((parsed_query.get("view") or "v2")[:2] in ["v2", "v3"]): | ||
| if parsed_query['html_output']: | ||
| output = add_buttons(output) | ||
| else: | ||
| message = get_message('FOLLOW_ME', parsed_query['lang']) | ||
| if parsed_query.get('no-terminal', False): | ||
| message = remove_ansi(message) | ||
| output += '\n' + message + '\n' | ||
| if parsed_query['html_output']: | ||
| output = add_buttons(output) | ||
| else: | ||
| message = get_message('FOLLOW_ME', parsed_query['lang']) | ||
| if parsed_query.get('no-terminal', False): | ||
| message = remove_ansi(message) | ||
| output += '\n' + message + '\n' |
There was a problem hiding this comment.
Function _response refactored with the following changes:
- Split conditional into multiple branches (
split-or-ifs) - Merge duplicate blocks in conditional (
merge-duplicate-blocks) - Merge else clause's nested if statement into elif (
merge-else-if-into-elif) - Remove redundant conditional (
remove-redundant-if)
| parsed_query.update(parse_query.parse_wttrin_png_name(png_filename)) | ||
| parsed_query |= parse_query.parse_wttrin_png_name(png_filename) |
There was a problem hiding this comment.
Function parse_request refactored with the following changes:
- Merge dictionary updates via the union operator (
dict-assign-update-to-union) - Replace interpolated string formatting with f-string (
replace-interpolation-with-fstring)
| if inverse: | ||
| return 'black' | ||
| return 'lightgray' | ||
|
|
||
| return 'black' if inverse else 'lightgray' | ||
| if color in ['green', 'black', 'cyan', 'blue', 'brown']: | ||
| return color | ||
| try: | ||
| return ( | ||
| int(color[0:2], 16), | ||
| int(color[2:4], 16), | ||
| int(color[4:6], 16)) | ||
| return int(color[:2], 16), int(color[2:4], 16), int(color[4:6], 16) |
There was a problem hiding this comment.
Function _color_mapping refactored with the following changes:
- Lift code into else after jump in control flow (
reintroduce-else) - Replace if statement with if expression (
assign-if-exp) - Replace a[0:x] with a[:x] and a[x:len(a)] with a[x:] (
remove-redundant-slice-index)
| if cat in ['Latin', 'Common']: | ||
| return 'default' | ||
| return cat | ||
| return 'default' if cat in ['Latin', 'Common'] else cat |
There was a problem hiding this comment.
Function _script_category refactored with the following changes:
- Lift code into else after jump in control flow (
reintroduce-else) - Replace if statement with if expression (
assign-if-exp)
| font = {} | ||
| for cat in FONT_CAT: | ||
| font[cat] = ImageFont.truetype(FONT_CAT[cat], FONT_SIZE) | ||
|
|
||
| font = {cat: ImageFont.truetype(FONT_CAT[cat], FONT_SIZE) for cat in FONT_CAT} |
There was a problem hiding this comment.
Function _gen_term refactored with the following changes:
- Convert for loop into dictionary comprehension (
dict-comprehension) - Replace comparison with min/max call [×2] (
min-max-identity) - Convert for loop into list comprehension (
list-comprehension) - Inline variable that is only used once (
inline-variable) - Replace interpolated string formatting with f-string (
replace-interpolation-with-fstring)
| return 'Unknown location; please try ~%s' % parsed_query["location"] | ||
| return f'Unknown location; please try ~{parsed_query["location"]}' |
There was a problem hiding this comment.
Function format_weather_data refactored with the following changes:
- Replace interpolated string formatting with f-string (
replace-interpolation-with-fstring)
| output = format_weather_data(query, parsed_query, data) | ||
| return output | ||
| return format_weather_data(query, parsed_query, data) |
There was a problem hiding this comment.
Function wttr_line refactored with the following changes:
- Inline variable that is immediately returned (
inline-immediately-returned-variable)
| dateutil.parser.parse(date) | ||
| except Exception as e: | ||
| print("ERROR: %s" % e) | ||
| print(f"ERROR: {e}") |
There was a problem hiding this comment.
Function get_moon refactored with the following changes:
- Replace interpolated string formatting with f-string (
replace-interpolation-with-fstring)
| data["weather"][i], for_day="%sd" % i, already_seen=already_seen) | ||
| data["weather"][i], for_day=f"{i}d", already_seen=already_seen | ||
| ) |
There was a problem hiding this comment.
Function render_prometheus refactored with the following changes:
- Replace interpolated string formatting with f-string (
replace-interpolation-with-fstring)
| url = ( | ||
| 'http://' | ||
| 'localhost:5001/premium/v1/weather.ashx' | ||
| '?key=%s' | ||
| '&q=%s&format=json&num_of_days=3&tp=3&lang=None' | ||
| ) % (WWO_KEY, config["location"]) | ||
| url = f'http://localhost:5001/premium/v1/weather.ashx?key={WWO_KEY}&q={config["location"]}&format=json&num_of_days=3&tp=3&lang=None' | ||
| text = requests.get(url).text | ||
| parsed_data = json.loads(text) | ||
| return parsed_data | ||
| return json.loads(text) |
There was a problem hiding this comment.
Function get_data refactored with the following changes:
- Inline variable that is immediately returned (
inline-immediately-returned-variable) - Replace interpolated string formatting with f-string (
replace-interpolation-with-fstring)
Thanks for starring sourcery-ai/sourcery ✨ 🌟 ✨
Here's your pull request refactoring your most popular Python repo.
If you want Sourcery to refactor all your Python repos and incoming pull requests install our bot.
Review changes via command line
To manually merge these changes, make sure you're on the
masterbranch, then run: