Skip to content

Commit

Permalink
adodbapi: Remove redundant str and repr calls, preferring !r fo…
Browse files Browse the repository at this point in the history
…rmatting marker (#2276)
  • Loading branch information
Avasam authored Jun 1, 2024
1 parent aa59486 commit ad5779b
Show file tree
Hide file tree
Showing 8 changed files with 77 additions and 89 deletions.
4 changes: 2 additions & 2 deletions adodbapi/ado_consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def ado_direction_name(ado_dir):
try:
return "adParam" + directions[ado_dir]
except:
return "unknown direction (" + str(ado_dir) + ")"
return f"unknown direction ({ado_dir})"


# ObjectStateEnum
Expand Down Expand Up @@ -166,7 +166,7 @@ def ado_direction_name(ado_dir):


def ado_type_name(ado_type):
return adTypeNames.get(ado_type, "unknown type (" + str(ado_type) + ")")
return adTypeNames.get(ado_type, f"unknown type ({ado_type})")


# here in decimal, sorted by value
Expand Down
70 changes: 33 additions & 37 deletions adodbapi/adodbapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ def __init__(self): # now define the instance attributes

def connect(self, kwargs, connection_maker=make_COM_connecter):
if verbose > 9:
print("kwargs=", repr(kwargs))
print(f"kwargs={kwargs!r}")
try:
self.connection_string = (
kwargs["connection_string"] % kwargs
Expand Down Expand Up @@ -415,8 +415,7 @@ def __setattr__(self, name, value):
if value not in api.accepted_paramstyles:
self._raiseConnectionError(
api.NotSupportedError,
'paramstyle="%s" not in:%s'
% (value, repr(api.accepted_paramstyles)),
f"paramstyle={value!r} not in:{api.accepted_paramstyles!r}",
)
elif name == "variantConversions":
value = copy.copy(
Expand Down Expand Up @@ -731,8 +730,7 @@ def _new_command(self, command_type=adc.adCmdText):
except:
self._raiseCursorError(
api.DatabaseError,
'Error creating new ADODB.Command object for "%s"'
% repr(self.commandText),
f"Error creating new ADODB.Command object for {self.commandText!r}",
)

def _execute_command(self):
Expand Down Expand Up @@ -856,7 +854,7 @@ def _buildADOparameterList(self, parameters, sproc=False):
"ADO detected Params=",
format_parameters(self.cmd.Parameters, True),
)
print("Program Parameters=", repr(parameters))
print(f"Program Parameters={parameters!r}")
parameters_known = True
except api.Error:
if verbose:
Expand All @@ -879,17 +877,14 @@ def _buildADOparameterList(self, parameters, sproc=False):
p, parameters[pm_name], p.Type, parameters_known
)
except Exception as e:
_message = (
"Error Converting Parameter %s: %s, %s <- %s\n"
% (
p.Name,
adc.ado_type_name(p.Type),
p.Value,
repr(parameters[pm_name]),
)
_message = "Error Converting Parameter {}: {}, {} <- {!r}\n".format(
p.Name,
adc.ado_type_name(p.Type),
p.Value,
parameters[pm_name],
)
self._raiseCursorError(
api.DataError, _message + "->" + repr(e.args)
api.DataError, f"{_message}->{e.args!r}"
)
else: # regular sequence of parameters
for value in parameters:
Expand All @@ -902,17 +897,14 @@ def _buildADOparameterList(self, parameters, sproc=False):
try:
_configure_parameter(p, value, p.Type, parameters_known)
except Exception as e:
_message = (
"Error Converting Parameter %s: %s, %s <- %s\n"
% (
p.Name,
adc.ado_type_name(p.Type),
p.Value,
repr(value),
)
_message = "Error Converting Parameter {}: {}, {} <- {!r}\n".format(
p.Name,
adc.ado_type_name(p.Type),
p.Value,
value,
)
self._raiseCursorError(
api.DataError, _message + "->" + repr(e.args)
api.DataError, f"{_message}->{e.args!r}"
)
i += 1
else: # -- build own parameter list
Expand All @@ -929,14 +921,16 @@ def _buildADOparameterList(self, parameters, sproc=False):
try:
self.cmd.Parameters.Append(p)
except Exception as e:
_message = "Error Building Parameter %s: %s, %s <- %s\n" % (
p.Name,
adc.ado_type_name(p.Type),
p.Value,
repr(elem),
_message = (
"Error Building Parameter {}: {}, {} <- {!r}\n".format(
p.Name,
adc.ado_type_name(p.Type),
p.Value,
elem,
)
)
self._raiseCursorError(
api.DataError, _message + "->" + repr(e.args)
api.DataError, f"{_message}->{e.args!r}"
)
else: # expecting the usual sequence of parameters
if sproc:
Expand All @@ -955,14 +949,16 @@ def _buildADOparameterList(self, parameters, sproc=False):
try:
self.cmd.Parameters.Append(p)
except Exception as e:
_message = "Error Building Parameter %s: %s, %s <- %s\n" % (
p.Name,
adc.ado_type_name(p.Type),
p.Value,
repr(elem),
_message = (
"Error Building Parameter {}: {}, {} <- {!r}\n".format(
p.Name,
adc.ado_type_name(p.Type),
p.Value,
elem,
)
)
self._raiseCursorError(
api.DataError, _message + "->" + repr(e.args)
api.DataError, f"{_message}->{e.args!r}"
)
i += 1
if self._ado_prepared == "setup":
Expand Down Expand Up @@ -1150,7 +1146,7 @@ def _last_query(self): # let the programmer see what query we actually used
if self.parameters is None:
ret = self.commandText
else:
ret = "%s,parameters=%s" % (self.commandText, repr(self.parameters))
ret = f"{self.commandText},parameters={self.parameters!r}"
except:
ret = None
return ret
Expand Down
16 changes: 7 additions & 9 deletions adodbapi/apibase.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ def COMDate(self, obj):
try:
return self.ComDateFromTuple(obj)
except:
raise ValueError('Cannot convert "%s" to COMdate.' % repr(obj))
raise ValueError(f'Cannot convert "{obj!r}" to COMdate.')

def ComDateFromTuple(self, t, microseconds=0):
d = datetime.date(t[0], t[1], t[2])
Expand Down Expand Up @@ -207,7 +207,7 @@ def DateObjectToIsoFormatString(self, obj):
try: # but may be time.struct_time
s = time.strftime("%Y-%m-%d %H:%M:%S", obj)
except:
raise ValueError('Cannot convert "%s" to isoformat' % repr(obj))
raise ValueError(f'Cannot convert "{obj!r}" to isoformat')
return s


Expand Down Expand Up @@ -389,7 +389,7 @@ def pyTypeToADOType(d):
return adc.adBigInt
if isinstance(d, numbers.Real):
return adc.adDouble
raise DataError('cannot convert "%s" (type=%s) to ADO' % (repr(d), tp))
raise DataError(f'cannot convert "{d!r}" (type={tp}) to ADO')


# # # # # # # # # # # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Expand Down Expand Up @@ -451,7 +451,7 @@ def identity(x):

def cvtUnusual(variant):
if verbose > 1:
sys.stderr.write("Conversion called for Unusual data=%s\n" % repr(variant))
sys.stderr.write(f"Conversion called for Unusual data={variant!r}\n")
return variant # cannot find conversion function -- just give the data to the user


Expand Down Expand Up @@ -545,9 +545,7 @@ def __getitem__(self, key): # used for row[key] type of value access
) # extension row[columnName] designation
except (KeyError, TypeError):
er, st, tr = sys.exc_info()
raise er(
'No such key as "%s" in %s' % (repr(key), self.__repr__())
).with_traceback(tr)
raise er(f'No such key as "{key!r}" in {self!r}').with_traceback(tr)

def __iter__(self):
return iter(self.__next__())
Expand All @@ -560,7 +558,7 @@ def __repr__(self): # create a human readable representation
taglist = sorted(list(self.rows.columnNames.items()), key=lambda x: x[1])
s = "<SQLrow={"
for name, i in taglist:
s += name + ":" + repr(self._getValue(i)) + ", "
s += f"{name}:{self._getValue(i)!r}, "
return s[:-2] + "}>"

def __str__(self): # create a pretty human readable representation
Expand Down Expand Up @@ -609,7 +607,7 @@ def __getitem__(self, item): # used for row or row,column access
try:
j = self.columnNames[j.lower()] # convert named column to numeric
except KeyError:
raise KeyError('adodbapi: no such column name as "%s"' % repr(j))
raise KeyError(f"adodbapi: no such column name as {j!r}")
if self.recordset_format == RS_ARRAY: # retrieve from two-dimensional array
v = self.ado_results[j, i]
elif self.recordset_format == RS_REMOTE:
Expand Down
4 changes: 2 additions & 2 deletions adodbapi/process_connect_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,9 @@ def macro_call(macro_name, args, kwargs):
tempfile.gettempdir(), "adodbapi_test", args[1]
)

raise ValueError("Unknown connect string macro=%s" % macro_name)
raise ValueError(f"Unknown connect string macro={macro_name}")
except:
raise ValueError("Error in macro processing %s %s" % (macro_name, repr(args)))
raise ValueError(f"Error in macro processing {macro_name} {args!r}")


def process(
Expand Down
62 changes: 28 additions & 34 deletions adodbapi/test/adodbapitest.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ def helpTestDataType(
ok = False
self.assertTrue(
rs[0] in allowedReturnValues,
'Value "%s" not in %s' % (repr(rs[0]), allowedReturnValues),
f'Value "{rs[0]!r}" not in {allowedReturnValues}',
)
else:
self.assertEqual(
Expand Down Expand Up @@ -697,17 +697,15 @@ def testRowIterator(self):
rec[j] == inParam[j]
), 'returned value:"%s" != test value:"%s"' % (rec[j], inParam[j])
# check that we can get a complete tuple from a row
assert tuple(rec) == inParam, 'returned value:"%s" != test value:"%s"' % (
repr(rec),
repr(inParam),
)
assert (
tuple(rec) == inParam
), f'returned value:"{rec!r}" != test value:"{inParam!r}"'
# test that slices of rows work
slice1 = tuple(rec[:-1])
slice2 = tuple(inParam[0:2])
assert slice1 == slice2, 'returned value:"%s" != test value:"%s"' % (
repr(slice1),
repr(slice2),
)
assert (
slice1 == slice2
), f'returned value:"{slice1!r}" != test value:"{slice2!r}"'
# now test named column retrieval
assert rec["fldTwo"] == inParam[0]
assert rec.fldThree == inParam[1]
Expand Down Expand Up @@ -1027,10 +1025,9 @@ def testAutoRollback(self):
row = crsr.fetchone()
except api.DatabaseError:
row = None # if the entire table disappeared the rollback was perfect and the test passed
assert row is None, (
"cursor.fetchone should return None if a query retrieves no rows. Got %s"
% repr(row)
)
assert (
row is None
), f"cursor.fetchone should return None if a query retrieves no rows. Got {row!r}"
self.helpRollbackTblTemp()

def testAutoCommit(self):
Expand Down Expand Up @@ -1164,11 +1161,11 @@ def testVariableReturningStoredProcedure(self):
retvalues = crsr.callproc(
"sp_DeleteMeOnlyForTesting", ("Dodsworth", "Anne", " ")
)
assert retvalues[0] == "Dodsworth", '%s is not "Dodsworth"' % repr(retvalues[0])
assert retvalues[1] == "Anne", '%s is not "Anne"' % repr(retvalues[1])
assert retvalues[2] == "DodsworthAnne", '%s is not "DodsworthAnne"' % repr(
retvalues[2]
)
assert retvalues[0] == "Dodsworth", f'{retvalues[0]!r} is not "Dodsworth"'
assert retvalues[1] == "Anne", f'{retvalues[1]!r} is not "Anne"'
assert (
retvalues[2] == "DodsworthAnne"
), f'{retvalues[2]!r} is not "DodsworthAnne"'
self.conn.rollback()

def testMultipleSetReturn(self):
Expand Down Expand Up @@ -1344,19 +1341,16 @@ def testOkConnect(self):
# /* (SELECT 'a small string' as result; */
# END $$
# """
#
# crsr.execute(spdef)
#
# retvalues = crsr.callproc(
# "DeleteMeOnlyForTesting", ("Dodsworth", "Anne", " ")
# )
# print("return value (mysql)=", repr(crsr.returnValue))
# assert retvalues[0] == "Dodsworth", '%s is not "Dodsworth"' % repr(retvalues[0])
# assert retvalues[1] == "Anne", '%s is not "Anne"' % repr(retvalues[1])
# assert retvalues[2] == "DodsworthAnne", '%s is not "DodsworthAnne"' % repr(
# retvalues[2]
# )
#
# # print(f"return value (mysql)={crsr.returnValue!r}")
# assert retvalues[0] == "Dodsworth", f'{retvalues[0]!r} is not "Dodsworth"'
# assert retvalues[1] == "Anne", f'{retvalues[1]!r} is not "Anne"'
# assert (
# retvalues[2] == "DodsworthAnne"
# ), f'{retvalues[2]!r} is not "DodsworthAnne"'
# try:
# crsr.execute("DROP PROCEDURE, DeleteMeOnlyForTesting")
# self.conn.commit()
Expand Down Expand Up @@ -1413,12 +1407,12 @@ def testOkConnect(self):
# retvalues = crsr.callproc(
# "DeleteMeOnlyForTesting", ("Dodsworth", "Anne", " ")
# )
# # print("return value (pg)=", repr(crsr.returnValue))
# assert retvalues[0] == "Dodsworth", '%s is not "Dodsworth"' % repr(retvalues[0])
# assert retvalues[1] == "Anne", '%s is not "Anne"' % repr(retvalues[1])
# assert retvalues[2] == "Dodsworth Anne", '%s is not "Dodsworth Anne"' % repr(
# retvalues[2]
# )
# # print(f"return value (pg)={crsr.returnValue!r}")
# assert retvalues[0] == "Dodsworth", f'{retvalues[0]!r} is not "Dodsworth"'
# assert retvalues[1] == "Anne", f'{retvalues[1]!r} is not "Anne"'
# assert (
# retvalues[2] == "DodsworthAnne"
# ), f'{retvalues[2]!r} is not "DodsworthAnne"'
# self.conn.rollback()
# try:
# crsr.execute("DROP PROCEDURE, DeleteMeOnlyForTesting")
Expand Down Expand Up @@ -1490,7 +1484,7 @@ def testDateObjectFromCOMDate(self):
t2 = time.gmtime(
time.mktime((2002, 6, 29, 12, 14, 2, 4, 31 + 28 + 31 + 30 + 31 + 28, -1))
)
assert t1 < cmd < t2, '"%s" should be about 2002-6-28 12:15:01' % repr(cmd)
assert t1 < cmd < t2, f'"{cmd}" should be about 2002-6-28 12:15:01'

def testDate(self):
t1 = time.mktime((2002, 6, 28, 18, 15, 1, 4, 31 + 28 + 31 + 30 + 31 + 30, 0))
Expand Down
4 changes: 2 additions & 2 deletions adodbapi/test/dbapi20.py
Original file line number Diff line number Diff line change
Expand Up @@ -465,13 +465,13 @@ def _paraminsert(self, cur):
res[0][1],
trouble,
"cursor.fetchall retrieved incorrect data, or data inserted "
"incorrectly. Got=%s, Expected=%s" % (repr(res[0][1]), repr(trouble)),
f"incorrectly. Got={res[0][1]!r}, Expected={trouble!r}",
)
self.assertEqual(
res[1][1],
trouble,
"cursor.fetchall retrieved incorrect data, or data inserted "
"incorrectly. Got=%s, Expected=%s" % (repr(res[1][1]), repr(trouble)),
f"incorrectly. Got={res[1][1]!r}, Expected={trouble!r}",
)

def test_executemany(self):
Expand Down
4 changes: 2 additions & 2 deletions adodbapi/test/test_adodbapi_dbapi20.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@
testmdb = setuptestframework.makemdb(testfolder)
connStr = r"Provider=%s;Data Source=%s" % (driver, testmdb)

print("Using Connection String like=%s" % connStr)
print("Keywords=%s" % repr(conn_kws))
print(f"Using Connection String like={connStr}")
print(f"Keywords={conn_kws!r}")


class test_adodbapi(dbapi20.DatabaseAPI20Test):
Expand Down
2 changes: 1 addition & 1 deletion adodbapi/test/tryconnection.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def try_connection(verbose, *args, **kwargs):
s.close() # thanks, it worked, goodbye
except adodbapi.DatabaseError as inst:
print(inst.args[0]) # should be the error message
print("***Failed getting connection using=", repr(args), repr(kwargs))
print(f"***Failed getting connection using= {args!r} {kwargs!r}")
return False, (args, kwargs), None

print(" (successful)")
Expand Down

0 comments on commit ad5779b

Please sign in to comment.