Skip to content

Commit 2bc3e44

Browse files
committed
(utils) Prefer f-strings for building strings
1 parent 0859e5c commit 2bc3e44

22 files changed

Lines changed: 278 additions & 319 deletions

‎astroquery/utils/commons.py‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -131,8 +131,8 @@ def radius_to_unit(radius, unit='degree'):
131131
if isinstance(unit, six.string_types):
132132
if hasattr(rad, unit):
133133
return getattr(rad, unit)
134-
elif hasattr(rad, unit + 's'):
135-
return getattr(rad, unit + 's')
134+
elif hasattr(rad, f"{unit}s"):
135+
return getattr(rad, f"{unit}s")
136136

137137
return rad.to(unit).value
138138

@@ -447,10 +447,9 @@ def get_stringio(self):
447447

448448
def __repr__(self):
449449
if hasattr(self, '_fits'):
450-
return "Downloaded FITS file: " + self._fits.__repr__()
450+
return f"Downloaded FITS file: {self._fits!r}"
451451
else:
452-
return ("Downloaded object from URL {} with ID {}"
453-
.format(self._target, id(self._readable_object)))
452+
return f"Downloaded object from URL {self._target} with ID {id(self._readable_object)}"
454453

455454

456455
def get_readable_fileobj(*args, **kwargs):

‎astroquery/utils/decorators.py‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def deprecate_function(func, message=message, since=since,
2727
message = ('Function {} has been deprecated since {}.'
2828
.format(func.__name__, since))
2929
if alternative is not None:
30-
message += '\n Use {} instead.'.format(alternative)
30+
message += f'\n Use {alternative} instead.'
3131

3232
@functools.wraps(func)
3333
def deprecated_func(*args, **kwargs):
@@ -41,7 +41,7 @@ def deprecate_class(cls, message=message, since=since,
4141
message = ('Class {} has been deprecated since {}.'
4242
.format(cls.__name__, since))
4343
if alternative is not None:
44-
message += '\n Use {} instead.'.format(alternative)
44+
message += f'\n Use {alternative} instead.'
4545

4646
cls.__init__ = deprecate_function(cls.__init__, message=message)
4747

@@ -144,11 +144,9 @@ def wrapper(*args, **kwargs):
144144
'and will be removed in a future version. '
145145
.format(old_name[i], since[i]))
146146
if new_name[i] is not None:
147-
message += ('Use argument "{}" instead.'
148-
.format(new_name[i]))
147+
message += f'Use argument "{new_name[i]}" instead.'
149148
elif alternative:
150-
message += ('\n Use {} instead.'
151-
.format(alternative))
149+
message += f'\n Use {alternative} instead.'
152150
warnings.warn(message, warning_type, stacklevel=2)
153151

154152
# Check if the newkeyword was given as well.

‎astroquery/utils/download_file_list.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
__doctest_skip__ = ["download_list_of_fitsfiles"]
1414

1515
whitespace_re = re.compile(r"\s")
16-
valid_chars = "-_.()%s%s" % (string.ascii_letters, string.digits)
16+
valid_chars = f"-_.(){string.ascii_letters}{string.digits}"
1717

1818

1919
def validify_filename(filestr):
@@ -96,7 +96,7 @@ def download_list_of_fitsfiles(linklist, output_directory=None,
9696
coordstr = output_coord_format.format(lon, lat)
9797
except TypeError:
9898
coordstr = output_coord_format % (lon, lat)
99-
nametxt += "_" + coordstr
99+
nametxt += f"_{coordstr}"
100100

101101
if include_input_filename:
102102
filename_root = os.path.split(link)[1]
@@ -105,13 +105,13 @@ def download_list_of_fitsfiles(linklist, output_directory=None,
105105

106106
savename = output_prefix if output_prefix else ""
107107
savename += nametxt
108-
savename += "_" + filename_root
108+
savename += f"_{filename_root}"
109109

110110
# Set final directory and file names
111-
final_file = output_directory + savename
111+
final_file = f"{output_directory}{savename}"
112112

113113
if verbose:
114-
print("Saving file %s" % final_file)
114+
print(f"Saving file {final_file}")
115115

116116
try:
117117
fitsfile.writeto(final_file, clobber=overwrite)

‎astroquery/utils/schema.py‎

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,7 @@ def __init__(self, *args, **kw):
3232
self._error = kw.get('error')
3333

3434
def __repr__(self):
35-
return '%s(%s)' % (self.__class__.__name__,
36-
', '.join(repr(a) for a in self._args))
35+
return f"{self.__class__.__name__}({', '.join(repr(a) for a in self._args)})"
3736

3837
def validate(self, data):
3938
for s in [Schema(s, error=self._error) for s in self._args]:
@@ -50,7 +49,7 @@ def validate(self, data):
5049
return s.validate(data)
5150
except SchemaError as _x:
5251
x = _x
53-
raise SchemaError(['%r did not validate %r' % (self, data)] + x.autos,
52+
raise SchemaError([f'{self!r} did not validate {data!r}'] + x.autos,
5453
[self._error] + x.errors)
5554

5655

@@ -62,7 +61,7 @@ def __init__(self, callable_, error=None):
6261
self._error = error
6362

6463
def __repr__(self):
65-
return '%s(%r)' % (self.__class__.__name__, self._callable)
64+
return f'{self.__class__.__name__}({self._callable!r})'
6665

6766
def validate(self, data):
6867
try:
@@ -71,7 +70,7 @@ def validate(self, data):
7170
raise SchemaError([None] + x.autos, [self._error] + x.errors)
7271
except BaseException as x:
7372
f = self._callable.__name__
74-
raise SchemaError('%s(%r) raised %r' % (f, data, x), self._error)
73+
raise SchemaError(f'{f}({data!r}) raised {x!r}', self._error)
7574

7675

7776
def priority(s):
@@ -103,7 +102,7 @@ def __init__(self, schema, error=None):
103102
self._error = error
104103

105104
def __repr__(self):
106-
return '%s(%r)' % (self.__class__.__name__, self._schema)
105+
return f'{self.__class__.__name__}({self._schema!r})'
107106

108107
def validate(self, data):
109108
s = self._schema
@@ -141,30 +140,29 @@ def validate(self, data):
141140
new[nkey] = nvalue
142141
elif skey is not None:
143142
if x is not None:
144-
raise SchemaError(['key %r is required' % key] +
143+
raise SchemaError([f'key {key!r} is required'] +
145144
x.autos, [e] + x.errors)
146145
else:
147-
raise SchemaError('key %r is required' % skey, e)
146+
raise SchemaError(f'key {skey!r} is required', e)
148147
coverage = set(k for k in coverage if type(k) is not Optional)
149148
required = set(k for k in s if type(k) is not Optional)
150149
if coverage != required:
151-
raise SchemaError('missed keys %r' % (required - coverage), e)
150+
raise SchemaError(f'missed keys {(required - coverage)!r}', e)
152151
if len(new) != len(data):
153-
raise SchemaError('wrong keys %r in %r' % (new, data), e)
152+
raise SchemaError(f'wrong keys {new!r} in {data!r}', e)
154153
return new
155154
if hasattr(s, 'validate'):
156155
try:
157156
return s.validate(data)
158157
except SchemaError as x:
159158
raise SchemaError([None] + x.autos, [e] + x.errors)
160159
except BaseException as x:
161-
raise SchemaError('%r.validate(%r) raised %r' % (s, data, x),
162-
self._error)
160+
raise SchemaError(f'{s!r}.validate({data!r}) raised {x!r}', self._error)
163161
if type(s) is type:
164162
if isinstance(data, s):
165163
return data
166164
else:
167-
raise SchemaError('%r should be instance of %r' % (data, s), e)
165+
raise SchemaError(f'{data!r} should be instance of {s!r}', e)
168166
if callable(s):
169167
f = s.__name__
170168
try:
@@ -173,13 +171,12 @@ def validate(self, data):
173171
except SchemaError as x:
174172
raise SchemaError([None] + x.autos, [e] + x.errors)
175173
except BaseException as x:
176-
raise SchemaError('%s(%r) raised %r' % (f, data, x),
177-
self._error)
178-
raise SchemaError('%s(%r) should evaluate to True' % (f, data), e)
174+
raise SchemaError(f'{f}({data!r}) raised {x!r}', self._error)
175+
raise SchemaError(f'{f}({data!r}) should evaluate to True', e)
179176
if s == data:
180177
return data
181178
else:
182-
raise SchemaError('%r does not match %r' % (s, data), e)
179+
raise SchemaError(f'{s!r} does not match {data!r}', e)
183180

184181

185182
class Optional(Schema):

‎astroquery/utils/tap/conn/tapconn.py‎

Lines changed: 28 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ def __init__(self, ishttps,
9090
if(server_context.startswith("/")):
9191
self.__serverContext = server_context
9292
else:
93-
self.__serverContext = "/" + server_context
93+
self.__serverContext = f"/{server_context}"
9494
else:
9595
self.__serverContext = ""
9696
self.__tapContext = self.__create_context(tap_context)
@@ -108,9 +108,9 @@ def __init__(self, ishttps,
108108
def __create_context(self, context):
109109
if (context is not None and context != ""):
110110
if(str(context).startswith("/")):
111-
return self.__serverContext + str(context)
111+
return f"{self.__serverContext}{context}"
112112
else:
113-
return self.__serverContext + "/" + str(context)
113+
return f"{self.__serverContext}/{context}"
114114
else:
115115
return self.__serverContext
116116

@@ -132,14 +132,14 @@ def __interna_init(self):
132132
self.__currentReason = ""
133133

134134
def __get_tap_context(self, subContext):
135-
return self.__tapContext + "/" + subContext
135+
return f"{self.__tapContext}/{subContext}"
136136

137137
def __get_data_context(self, encodedData=None):
138138
if self.__dataContext is None:
139139
raise ValueError("data_context must be specified at TAP object " +
140140
"creation for this action to be performed")
141141
if encodedData is not None:
142-
return self.__dataContext + "?" + str(encodedData)
142+
return f"{self.__dataContext}?{encodedData}"
143143
else:
144144
return self.__dataContext
145145

@@ -149,10 +149,10 @@ def __get_datalink_context(self, subContext, encodedData=None):
149149
"object creation for this action to be " +
150150
"performed")
151151
if encodedData is not None:
152-
return self.__datalinkContext + "/" + subContext + "?" +\
153-
encodedData
152+
return f"{self.__datalinkContext}/{subContext}?{encodedData}"
153+
154154
else:
155-
return self.__datalinkContext + "/" + subContext
155+
return f"{self.__datalinkContext}/{subContext}"
156156

157157
def __get_upload_context(self):
158158
if self.__uploadContext is None:
@@ -169,7 +169,7 @@ def __get_table_edit_context(self):
169169
return self.__tableEditContext
170170

171171
def __get_server_context(self, subContext):
172-
return self.__serverContext + "/" + subContext
172+
return f"{self.__serverContext}/{subContext}"
173173

174174
def execute_tapget(self, subcontext, verbose=False):
175175
"""Executes a TAP GET request
@@ -238,8 +238,8 @@ def execute_datalinkget(self, subcontext, query, verbose=False):
238238
def __execute_get(self, context, verbose=False):
239239
conn = self.__get_connection(verbose)
240240
if verbose:
241-
print("host = " + str(conn.host) + ":" + str(conn.port))
242-
print("context = " + context)
241+
print(f"host = {conn.host}:{conn.port}")
242+
print(f"context = {context}")
243243
conn.request("GET", context, None, self.__getHeaders)
244244
response = conn.getresponse()
245245
self.__currentReason = response.reason
@@ -396,9 +396,9 @@ def __execute_post(self, context, data,
396396
verbose=False):
397397
conn = self.__get_connection(verbose)
398398
if verbose:
399-
print("host = " + str(conn.host) + ":" + str(conn.port))
400-
print("context = " + context)
401-
print("Content-type = " + str(content_type))
399+
print(f"host = {conn.host}:{conn.port}")
400+
print(f"context = {context}")
401+
print(f"Content-type = {content_type}")
402402
self.__postHeaders["Content-type"] = content_type
403403
conn.request("POST", context, data, self.__postHeaders)
404404
response = conn.getresponse()
@@ -614,8 +614,7 @@ def get_host_url(self):
614614
-------
615615
A string composed of: 'host:port/server_context'
616616
"""
617-
return str(self.__connHost) + ":" + str(self.__connPort) \
618-
+ str(self.__get_tap_context(""))
617+
return f'{self.__connHost}:{self.__connPort}{self.__get_tap_context("")}'
619618

620619
def get_host_url_secure(self):
621620
"""Returns the host+portSsl+serverContext
@@ -624,8 +623,7 @@ def get_host_url_secure(self):
624623
-------
625624
A string composed of: 'host:portSsl/server_context'
626625
"""
627-
return str(self.__connHost) + ":" + str(self.__connPortSsl) \
628-
+ str(self.__get_tap_context(""))
626+
return f'{self.__connHost}:{self.__connPortSsl}{self.__get_tap_context("")}'
629627

630628
def check_launch_response_status(self, response, debug,
631629
expected_response_status,
@@ -654,8 +652,7 @@ def check_launch_response_status(self, response, debug,
654652
isError = False
655653
if response.status != expected_response_status:
656654
if debug:
657-
print("ERROR: " + str(response.status) + ": " +
658-
str(response.reason))
655+
print(f"ERROR: {response.status}: {response.reason}")
659656
isError = True
660657
if isError and raise_exception:
661658
errMsg = taputils.get_http_response_error(response)
@@ -687,37 +684,33 @@ def encode_multipart(self, fields, files):
687684
The suitable content-type and the body for the request
688685
"""
689686
timeMillis = int(round(time.time() * 1000))
690-
boundary = '===%s===' % str(timeMillis)
687+
boundary = f'==={timeMillis}==='
691688
CRLF = '\r\n'
692689
multiparItems = []
693690
for key in fields:
694-
multiparItems.append('--' + boundary + CRLF)
691+
multiparItems.append(f'--{boundary}{CRLF}')
695692
multiparItems.append(
696-
'Content-Disposition: form-data; name="%s"%s' % (key, CRLF))
693+
f'Content-Disposition: form-data; name="{key}"{CRLF}')
697694
multiparItems.append(CRLF)
698-
multiparItems.append(fields[key]+CRLF)
695+
multiparItems.append(f'{fields[key]}{CRLF}')
699696
for (key, filename, value) in files:
700-
multiparItems.append('--' + boundary + CRLF)
697+
multiparItems.append(f'--{boundary}{CRLF}')
701698
multiparItems.append(
702-
'Content-Disposition: form-data; name="%s"; filename="%s"%s' %
703-
(key, filename, CRLF))
699+
f'Content-Disposition: form-data; name="{key}"; filename="{filename}"{CRLF}')
704700
multiparItems.append(
705-
'Content-Type: %s%s' %
706-
(mimetypes.guess_extension(filename), CRLF))
701+
f'Content-Type: {mimetypes.guess_extension(filename)}{CRLF}')
707702
multiparItems.append(CRLF)
708703
multiparItems.append(value)
709704
multiparItems.append(CRLF)
710-
multiparItems.append('--' + boundary + '--' + CRLF)
705+
multiparItems.append(f'--{boundary}--{CRLF}')
711706
multiparItems.append(CRLF)
712707
body = utils.util_create_string_from_buffer(multiparItems)
713-
contentType = 'multipart/form-data; boundary=%s' % boundary
708+
contentType = f'multipart/form-data; boundary={boundary}'
714709
return contentType, body.encode('utf-8')
715710

716711
def __str__(self):
717-
return "\tHost: " + str(self.__connHost) + "\n\tUse HTTPS: " \
718-
+ str(self.__isHttps) \
719-
+ "\n\tPort: " + str(self.__connPort) + "\n\tSSL Port: " \
720-
+ str(self.__connPortSsl)
712+
return f"\tHost: {self.__connHost}\n\tUse HTTPS: {self.__isHttps}" \
713+
f"\n\tPort: {self.__connPort}\n\tSSL Port: {self.__connPortSsl}"
721714

722715

723716
class ConnectionHandler(object):

0 commit comments

Comments
 (0)