Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adodbapi: prefer f-string > format > printf-style autofixes #2241

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 36 additions & 68 deletions adodbapi/adodbapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def connect(*args, **kwargs): # --> a db-api connection object
co.connect(kwargs)
return co
except Exception as e:
message = 'Error opening connection to "%s"' % co.connection_string
message = f'Error opening connection to "{co.connection_string}"'
raise api.OperationalError(e, message)


Expand Down Expand Up @@ -124,8 +124,7 @@ def format_parameters(ADOparameters, show_value=False):
try:
if show_value:
desc = [
'Name: %s, Dir.: %s, Type: %s, Size: %s, Value: "%s", Precision: %s, NumericScale: %s'
% (
'Name: {}, Dir.: {}, Type: {}, Size: {}, Value: "{}", Precision: {}, NumericScale: {}'.format(
p.Name,
adc.directions[p.Direction],
adc.adTypeNames.get(p.Type, str(p.Type) + " (unknown type)"),
Expand All @@ -138,8 +137,7 @@ def format_parameters(ADOparameters, show_value=False):
]
else:
desc = [
"Name: %s, Dir.: %s, Type: %s, Size: %s, Precision: %s, NumericScale: %s"
% (
"Name: {}, Dir.: {}, Type: {}, Size: {}, Precision: {}, NumericScale: {}".format(
p.Name,
adc.directions[p.Direction],
adc.adTypeNames.get(p.Type, str(p.Type) + " (unknown type)"),
Expand Down Expand Up @@ -256,7 +254,7 @@ def connect(self, kwargs, connection_maker=make_COM_connecter):
self.mode = kwargs.get("mode", adc.adModeUnknown)
self.kwargs = kwargs
if verbose:
print('%s attempting: "%s"' % (version, self.connection_string))
print(f'{version} attempting: "{self.connection_string}"')
self.connector = connection_maker()
self.connector.ConnectionTimeout = self.timeout
self.connector.ConnectionString = self.connection_string
Expand All @@ -267,7 +265,7 @@ def connect(self, kwargs, connection_maker=make_COM_connecter):
except api.Error:
self._raiseConnectionError(
api.DatabaseError,
"ADO error trying to Open=%s" % self.connection_string,
f"ADO error trying to Open={self.connection_string}",
)

try: # Stefan Fuchs; support WINCCOLEDBProvider
Expand Down Expand Up @@ -296,7 +294,7 @@ def connect(self, kwargs, connection_maker=make_COM_connecter):
self.paramstyle = kwargs["paramstyle"] # let setattr do the error checking
self.messages = []
if verbose:
print("adodbapi New connection at %X" % id(self))
print(f"adodbapi New connection at {id(self):X}")

def _raiseConnectionError(self, errorclass, errorvalue):
eh = self.errorhandler
Expand All @@ -317,7 +315,7 @@ def _closeAdoConnection(self): # all v2.1 Rose
pass
self.connector.Close()
if verbose:
print("adodbapi Closed connection at %X" % id(self))
print(f"adodbapi Closed connection at {id(self):X}")

def close(self):
"""Close the connection now (rather than whenever __del__ is called).
Expand Down Expand Up @@ -354,7 +352,7 @@ def commit(self):
try:
self.transaction_level = self.connector.CommitTrans()
if verbose > 1:
print("commit done on connection at %X" % id(self))
print(f"commit done on connection at {id(self):X}")
if not (
self._autocommit
or (self.connector.Attributes & adc.adXactAbortRetaining)
Expand Down Expand Up @@ -388,7 +386,7 @@ def _rollback(self):
try:
self.transaction_level = self.connector.RollbackTrans()
if verbose > 1:
print("rollback done on connection at %X" % id(self))
print(f"rollback done on connection at {id(self):X}")
if not self._autocommit and not (
self.connector.Attributes & adc.adXactAbortRetaining
):
Expand Down Expand Up @@ -437,7 +435,7 @@ def __getattr__(self, item):
return self._autocommit
else:
raise AttributeError(
'no such attribute in ADO connection object as="%s"' % item
f'no such attribute in ADO connection object as="{item}"'
)

def cursor(self):
Expand All @@ -463,15 +461,17 @@ def printADOerrors(self):
if j:
print("ADO Errors:(%i)" % j)
for e in self.connector.Errors:
print("Description: %s" % e.Description)
print("Error: %s %s " % (e.Number, adc.adoErrors.get(e.Number, "unknown")))
print(f"Description: {e.Description}")
print(
"Error: {} {} ".format(e.Number, adc.adoErrors.get(e.Number, "unknown"))
)
if e.Number == adc.ado_error_TIMEOUT:
print(
"Timeout Error: Try using adodbpi.connect(constr,timeout=Nseconds)"
)
print("Source: %s" % e.Source)
print("NativeError: %s" % e.NativeError)
print("SQL State: %s" % e.SQLState)
print(f"Source: {e.Source}")
print(f"NativeError: {e.NativeError}")
print(f"SQL State: {e.SQLState}")

def _suggest_error_class(self):
"""Introspect the current ADO Errors and determine an appropriate error class.
Expand Down Expand Up @@ -563,8 +563,7 @@ def __init__(self, connection):
connection._i_am_here(self)
if verbose:
print(
"%s New cursor at %X on conn %X"
% (version, id(self), id(self.connection))
f"{version} New cursor at {id(self):X} on conn {id(self.connection):X}"
)

def __iter__(self): # [2.1 Zamarev]
Expand Down Expand Up @@ -620,7 +619,7 @@ def build_column_info(self, recordset):
) # conversion function for this column
except KeyError:
self._raiseCursorError(
api.InternalError, "Data column of Unknown ADO type=%s" % f.Type
api.InternalError, f"Data column of Unknown ADO type={f.Type}"
)
self.columnNames[f.Name.lower()] = i # columnNames lookup

Expand Down Expand Up @@ -670,17 +669,14 @@ def format_description(self, d):
self._makeDescriptionFromRS()
if isinstance(d, int):
d = self.description[d]
desc = (
"Name= %s, Type= %s, DispSize= %s, IntSize= %s, Precision= %s, Scale= %s NullOK=%s"
% (
d[0],
adc.adTypeNames.get(d[1], str(d[1]) + " (unknown type)"),
d[2],
d[3],
d[4],
d[5],
d[6],
)
desc = "Name= {}, Type= {}, DispSize= {}, IntSize= {}, Precision= {}, Scale= {} NullOK={}".format(
d[0],
adc.adTypeNames.get(d[1], str(d[1]) + " (unknown type)"),
d[2],
d[3],
d[4],
d[5],
d[6],
)
return desc

Expand All @@ -705,7 +701,7 @@ def close(self, dont_tell_me=False):
None # this will make all future method calls on me throw an exception
)
if verbose:
print("adodbapi Closed cursor at %X" % id(self))
print(f"adodbapi Closed cursor at {id(self):X}")

def __del__(self):
try:
Expand Down Expand Up @@ -739,7 +735,7 @@ def _execute_command(self):
recordset = None
count = -1 # default value
if verbose:
print('Executing command="%s"' % self.commandText)
print(f'Executing command="{self.commandText}"')
try:
# ----- the actual SQL is executed here ---
recordset, count = self.cmd.Execute()
Expand All @@ -748,10 +744,7 @@ def _execute_command(self):
_message = ""
if hasattr(e, "args"):
_message += str(e.args) + "\n"
_message += "Command:\n%s\nParameters:\n%s" % (
self.commandText,
format_parameters(self.cmd.Parameters, True),
)
_message += f"Command:\n{self.commandText}\nParameters:\n{format_parameters(self.cmd.Parameters, True)}"
klass = self.connection._suggest_error_class()
self._raiseCursorError(klass, _message)
try:
Expand Down Expand Up @@ -781,9 +774,8 @@ def get_returned_parameters(self):
for p in tuple(self.cmd.Parameters):
if verbose > 2:
print(
'Returned=Name: %s, Dir.: %s, Type: %s, Size: %s, Value: "%s",'
" Precision: %s, NumericScale: %s"
% (
'Returned=Name: {}, Dir.: {}, Type: {}, Size: {}, Value: "{}",'
" Precision: {}, NumericScale: {}".format(
p.Name,
adc.directions[p.Direction],
adc.adTypeNames.get(p.Type, str(p.Type) + " (unknown type)"),
Expand Down Expand Up @@ -877,12 +869,7 @@ def _buildADOparameterList(self, parameters, sproc=False):
p, parameters[pm_name], p.Type, parameters_known
)
except Exception as e:
_message = "Error Converting Parameter {}: {}, {} <- {!r}\n".format(
p.Name,
adc.ado_type_name(p.Type),
p.Value,
parameters[pm_name],
)
_message = f"Error Converting Parameter {p.Name}: {adc.ado_type_name(p.Type)}, {p.Value} <- {parameters[pm_name]!r}\n"
self._raiseCursorError(
api.DataError, f"{_message}->{e.args!r}"
)
Expand All @@ -897,12 +884,7 @@ def _buildADOparameterList(self, parameters, sproc=False):
try:
_configure_parameter(p, value, p.Type, parameters_known)
except Exception as e:
_message = "Error Converting Parameter {}: {}, {} <- {!r}\n".format(
p.Name,
adc.ado_type_name(p.Type),
p.Value,
value,
)
_message = f"Error Converting Parameter {p.Name}: {adc.ado_type_name(p.Type)}, {p.Value} <- {value!r}\n"
self._raiseCursorError(
api.DataError, f"{_message}->{e.args!r}"
)
Expand All @@ -921,14 +903,7 @@ def _buildADOparameterList(self, parameters, sproc=False):
try:
self.cmd.Parameters.Append(p)
except Exception as e:
_message = (
"Error Building Parameter {}: {}, {} <- {!r}\n".format(
p.Name,
adc.ado_type_name(p.Type),
p.Value,
elem,
)
)
_message = f"Error Building Parameter {p.Name}: {adc.ado_type_name(p.Type)}, {p.Value} <- {elem!r}\n"
self._raiseCursorError(
api.DataError, f"{_message}->{e.args!r}"
)
Expand All @@ -949,14 +924,7 @@ def _buildADOparameterList(self, parameters, sproc=False):
try:
self.cmd.Parameters.Append(p)
except Exception as e:
_message = (
"Error Building Parameter {}: {}, {} <- {!r}\n".format(
p.Name,
adc.ado_type_name(p.Type),
p.Value,
elem,
)
)
_message = f"Error Building Parameter {p.Name}: {adc.ado_type_name(p.Type)}, {p.Value} <- {elem!r}\n"
self._raiseCursorError(
api.DataError, f"{_message}->{e.args!r}"
)
Expand Down
4 changes: 2 additions & 2 deletions adodbapi/apibase.py
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,7 @@ def __getattr__(self, name): # used for row.columnName type of value access
try:
return self._getValue(self.rows.columnNames[name.lower()])
except KeyError:
raise AttributeError('Unknown column name "{}"'.format(name))
raise AttributeError(f'Unknown column name "{name}"')

def _getValue(self, key): # key must be an integer
if (
Expand Down Expand Up @@ -702,7 +702,7 @@ def changeFormatToQmark(
s, chunk = sp[1].split(")s", 1) # find the ')s'
except ValueError:
raise ProgrammingError(
'Pyformat SQL has incorrect format near "%s"' % chunk
f'Pyformat SQL has incorrect format near "{chunk}"'
)
outparams.append(s)
outOp += "?" # put in the Qmark
Expand Down
4 changes: 2 additions & 2 deletions adodbapi/examples/db_print.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@
# make a cursor on the connection
with con.cursor() as c:
# run an SQL statement on the cursor
sql = "select * from %s" % kw_args["table_name"]
print('performing query="%s"' % sql)
sql = "select * from {}".format(kw_args["table_name"])
print(f'performing query="{sql}"')
c.execute(sql)

# check the results
Expand Down
2 changes: 1 addition & 1 deletion adodbapi/examples/db_table_names.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
# create the connection
con = adodbapi.connect(constr, db=databasename, macro_is64bit=provider)

print("Table names in= %s" % databasename)
print(f"Table names in= {databasename}")

for table in con.get_table_names():
print(table)
6 changes: 3 additions & 3 deletions adodbapi/examples/xls_read.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
except IndexError:
filename = "xx.xls"

constr = "Provider=%s;Data Source=%s;%s" % (driver, filename, extended)
constr = f"Provider={driver};Data Source={filename};{extended}"

conn = adodbapi.connect(constr)

Expand All @@ -30,10 +30,10 @@
# use ADO feature to get the name of the first worksheet
sheet = conn.get_table_names()[0]

print("Shreadsheet=%s Worksheet=%s" % (filename, sheet))
print(f"Shreadsheet={filename} Worksheet={sheet}")
print("------------------------------------------------------------")
crsr = conn.cursor()
sql = "SELECT * from [%s]" % sheet
sql = f"SELECT * from [{sheet}]"
crsr.execute(sql)
for row in crsr.fetchmany(10):
print(repr(row))
Expand Down
4 changes: 2 additions & 2 deletions adodbapi/examples/xls_write.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
filename = "xx.xls" # file will be created if it does not exist
extended = 'Extended Properties="Excel 8.0;Readonly=False;"'

constr = "Provider=%s;Data Source=%s;%s" % (driver, filename, extended)
constr = f"Provider={driver};Data Source={filename};{extended}"

conn = adodbapi.connect(constr)
with conn: # will auto commit if no errors
Expand All @@ -38,4 +38,4 @@
sql, ["John Jones", "Pvt", 987654321, 140.0, datetime.date(1921, 7, 4)]
) # another row of data
conn.close()
print("Created spreadsheet=%s worksheet=%s" % (filename, "SheetOne"))
print("Created spreadsheet={} worksheet={}".format(filename, "SheetOne"))
2 changes: 1 addition & 1 deletion adodbapi/process_connect_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def macro_call(macro_name, args, kwargs):
not "user" in kwargs or not kwargs["user"]
): # missing, blank, or Null username
return new_key, "Integrated Security=SSPI"
return new_key, "User ID=%(user)s; Password=%(password)s" % kwargs
return new_key, "User ID={user}; Password={password}".format(**kwargs)

elif (
macro_name == "find_temp_test_path"
Expand Down
2 changes: 1 addition & 1 deletion adodbapi/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
for line in a:
if "__version__" in line:
VERSION = line.split("'")[1]
print('adodbapi version="%s"' % VERSION)
print(f'adodbapi version="{VERSION}"')
break
a.close()

Expand Down
Loading
Loading