Skip to content

Commit 6f9d3ae

Browse files
author
ikkamens
committed
use f-strings
1 parent 079fcb7 commit 6f9d3ae

160 files changed

Lines changed: 551 additions & 764 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎astropy/__init__.py‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,8 +155,7 @@ class base_constants_version(ScienceState):
155155
@classmethod
156156
def validate(cls, value):
157157
if value not in cls._versions:
158-
raise ValueError('Must be one of {}'
159-
.format(list(cls._versions.keys())))
158+
raise ValueError(f'Must be one of {list(cls._versions.keys())}')
160159
return cls._versions[value]
161160

162161
@classmethod

‎astropy/config/paths.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -287,8 +287,8 @@ class set_temp_cache(_SetTempPath):
287287

288288

289289
def _find_or_create_root_dir(dirnm, linkto, pkgname='astropy'):
290-
innerdir = os.path.join(_find_home(), '.{}'.format(pkgname))
291-
maindir = os.path.join(_find_home(), '.{}'.format(pkgname), dirnm)
290+
innerdir = os.path.join(_find_home(), f'.{pkgname}')
291+
maindir = os.path.join(_find_home(), f'.{pkgname}', dirnm)
292292

293293
if not os.path.exists(maindir):
294294
# first create .astropy dir if needed

‎astropy/constants/__init__.py‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,8 +77,7 @@ def set_enabled_constants(modname):
7777
codata_context = modmodule.codata
7878
iaudata_context = modmodule.iaudata
7979
except ImportError as exc:
80-
exc.args += ('Context manager does not currently handle {}'
81-
.format(modname),)
80+
exc.args += (f'Context manager does not currently handle {modname}',)
8281
raise
8382

8483
module = find_current_module()

‎astropy/convolution/convolve.py‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -176,8 +176,7 @@ def convolve(array, kernel, boundary='fill', fill_value=0.,
176176
"""
177177

178178
if boundary not in BOUNDARY_OPTIONS:
179-
raise ValueError("Invalid boundary option: must be one of {}"
180-
.format(BOUNDARY_OPTIONS))
179+
raise ValueError(f"Invalid boundary option: must be one of {BOUNDARY_OPTIONS}")
181180

182181
if nan_treatment not in ('interpolate', 'fill'):
183182
raise ValueError("nan_treatment must be one of 'interpolate','fill'")

‎astropy/convolution/tests/test_convolve_speeds.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,12 @@
3333
("", "fft_pad=False")):
3434
statement = f"convolve{convolve_type}(array, kernel, boundary='fill', {extra})"
3535
besttime = min(timeit.Timer(stmt=statement, setup=setup).repeat(3, 10))
36-
print("%17f" % (besttime), end=' ')
36+
print(f"{besttime:17f}", end=' ')
3737
else:
3838
print("%17s" % "skipped", end=' ')
3939
statement = "convolve_fft(array, kernel, boundary='fill')"
4040
besttime = min(timeit.Timer(stmt=statement, setup=setup).repeat(3, 10))
41-
print("%17f" % (besttime), end=' ')
41+
print(f"{besttime:17f}", end=' ')
4242

4343
print()
4444

@@ -59,12 +59,12 @@
5959
else:
6060
statement = f"convolve{convolve_type}(array, kernel, boundary='fill')"
6161
besttime = min(timeit.Timer(stmt=statement, setup=setup).repeat(3, 10))
62-
print("%17f" % (besttime), end=' ')
62+
print(f"{besttime:17f}", end=' ')
6363
else:
6464
print("%17s" % "skipped", end=' ')
6565
statement = "convolve_fft(array, kernel, boundary='fill')"
6666
besttime = min(timeit.Timer(stmt=statement, setup=setup).repeat(3, 10))
67-
print("%17f" % (besttime), end=' ')
67+
print(f"{besttime:17f}", end=' ')
6868

6969
print()
7070

‎astropy/coordinates/angle_utilities.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -344,8 +344,7 @@ def parse(self, angle, unit, debug=False):
344344
angle, lexer=self._thread_local._lexer, debug=debug)
345345
except ValueError as e:
346346
if str(e):
347-
raise ValueError("{} in angle {!r}".format(
348-
str(e), angle))
347+
raise ValueError(f"{str(e)} in angle {angle!r}")
349348
else:
350349
raise ValueError(
351350
f"Syntax error parsing angle {angle!r}")
@@ -668,7 +667,7 @@ def sexagesimal_to_string(values, precision=None, pad=False, sep=(':',),
668667
literal.append('{1:02d}{sep[1]}')
669668
if fields == 3:
670669
if precision is None:
671-
last_value = '{:.4f}'.format(abs(values[2]))
670+
last_value = f'{abs(values[2]):.4f}'
672671
last_value = last_value.rstrip('0').rstrip('.')
673672
else:
674673
last_value = '{0:.{precision}f}'.format(

‎astropy/coordinates/angles.py‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -148,8 +148,7 @@ def _tuple_to_float(angle, unit):
148148
elif unit == u.degree:
149149
return util.dms_to_degrees(*angle)
150150
else:
151-
raise u.UnitsError("Can not parse '{}' as unit '{}'"
152-
.format(angle, unit))
151+
raise u.UnitsError(f"Can not parse '{angle}' as unit '{unit}'")
153152

154153
@staticmethod
155154
def _convert_unit_to_angle_unit(unit):
@@ -342,9 +341,7 @@ def plain_unit_format(val):
342341
func = plain_unit_format
343342
else:
344343
raise ValueError(
345-
"'{}' can not be represented in sexagesimal "
346-
"notation".format(
347-
unit.name))
344+
f"'{unit.name}' can not be represented in sexagesimal notation")
348345

349346
else:
350347
raise u.UnitsError(

‎astropy/coordinates/attributes.py‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -180,8 +180,7 @@ def convert_input(self, value):
180180
out = Time(value)
181181
except Exception as err:
182182
raise ValueError(
183-
'Invalid time input {}={!r}\n{}'.format(self.name,
184-
value, err))
183+
f'Invalid time input {self.name}={value!r}\n{err}')
185184
converted = True
186185

187186
# Set attribute as read-only for arrays (not allowed by numpy

‎astropy/coordinates/baseframe.py‎

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -605,8 +605,7 @@ def __init__(self, *args, copy=True, representation_type=None,
605605

606606
if kwargs:
607607
raise TypeError(
608-
'Coordinate frame got unexpected keywords: {}'.format(
609-
list(kwargs)))
608+
f'Coordinate frame got unexpected keywords: {list(kwargs)}')
610609

611610
# We do ``is None`` because self._data might evaluate to false for
612611
# empty arrays or data == 0
@@ -622,8 +621,7 @@ def __init__(self, *args, copy=True, representation_type=None,
622621
self._no_data_shape = check_broadcast(*shapes.values())
623622
except ValueError:
624623
raise ValueError(
625-
"non-scalar attributes with inconsistent "
626-
"shapes: {}".format(shapes))
624+
f"non-scalar attributes with inconsistent shapes: {shapes}")
627625

628626
# Above, we checked that it is possible to broadcast all
629627
# shapes. By getting and thus validating the attributes,
@@ -1395,11 +1393,9 @@ def __repr__(self):
13951393
frameattrs = f' ({frameattrs})'
13961394

13971395
if data_repr:
1398-
return '<{} Coordinate{}: {}>'.format(self.__class__.__name__,
1399-
frameattrs, data_repr)
1396+
return f'<{self.__class__.__name__} Coordinate{frameattrs}: {data_repr}>'
14001397
else:
1401-
return '<{} Frame{}>'.format(self.__class__.__name__,
1402-
frameattrs)
1398+
return f'<{self.__class__.__name__} Frame{frameattrs}>'
14031399

14041400
def _data_repr(self):
14051401
"""Returns a string representation of the coordinate data."""
@@ -1483,9 +1479,7 @@ def _frame_attrs_repr(self):
14831479
attrstr = attr._astropy_repr_in_frame()
14841480
else:
14851481
attrstr = str(attr)
1486-
attr_strs.append("{attribute_name}={attrstr}".format(
1487-
attribute_name=attribute_name,
1488-
attrstr=attrstr))
1482+
attr_strs.append(f"{attribute_name}={attrstr}")
14891483

14901484
return ', '.join(attr_strs)
14911485

‎astropy/coordinates/calculation.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ def horoscope(birthday, corrected=True, chinese=False):
153153
else:
154154
zodiac_sign = get_sign(birthday.to_datetime())
155155
url = f"http://www.astrology.com/us/horoscope/daily-overview.aspx?sign={zodiac_sign}"
156-
summ_title_sfx = 'on {}'.format(today.strftime("%Y-%m-%d"))
156+
summ_title_sfx = f"on {today.strftime('%Y-%m-%d')}"
157157

158158
res = Request(url, headers=headers)
159159
with urlopen(res) as f:
@@ -165,7 +165,7 @@ def horoscope(birthday, corrected=True, chinese=False):
165165
raise CelestialError(err_msg)
166166

167167
print("*"*79)
168-
color_print("Horoscope for {} {}:".format(zodiac_sign.capitalize(), summ_title_sfx),
168+
color_print(f"Horoscope for {zodiac_sign.capitalize()} {summ_title_sfx}:",
169169
'green')
170170
print("*"*79)
171171
for block in textwrap.wrap(desc, 79):

0 commit comments

Comments
 (0)