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

Modernize code with pyupgrade --py37-plus #930

Merged
merged 1 commit into from
May 28, 2023
Merged
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
2 changes: 2 additions & 0 deletions CHANGES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ next (unreleased)

* Fix debug log level with sha256_password authentication #863

* Modernized code with `pyupgrade <https://github.com/asottile/pyupgrade>`_ to Python 3.7+ syntax #930

0.1.1 (2022-05-08)
^^^^^^^^^^^^^^^^^^

Expand Down
24 changes: 12 additions & 12 deletions aiomysql/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@
self.connected_time = self._loop.time()

if self.sql_mode is not None:
await self.query("SET sql_mode=%s" % (self.sql_mode,))
await self.query(f"SET sql_mode={self.sql_mode}")

if self.init_command is not None:
await self.query(self.init_command)
Expand Down Expand Up @@ -659,8 +659,8 @@
msg = "Lost connection to MySQL server during query"
self.close()
raise OperationalError(CR.CR_SERVER_LOST, msg) from e
except (IOError, OSError) as e:
msg = "Lost connection to MySQL server during query (%s)" % (e,)
except OSError as e:
msg = f"Lost connection to MySQL server during query ({e})"

Check warning on line 663 in aiomysql/connection.py

View check run for this annotation

Codecov / codecov/patch

aiomysql/connection.py#L663

Added line #L663 was not covered by tests
self.close()
raise OperationalError(CR.CR_SERVER_LOST, msg) from e
return data
Expand Down Expand Up @@ -899,7 +899,7 @@
data = self._password.encode('latin1') + b'\0'
else:
raise OperationalError(
2059, "Authentication plugin '{0}'"
2059, "Authentication plugin '{}'"
" not configured".format(plugin_name)
)

Expand Down Expand Up @@ -936,7 +936,7 @@
if not pkt.is_extra_auth_data():
raise OperationalError(
"caching sha2: Unknown packet "
"for fast auth: {0}".format(pkt._data[:1])
"for fast auth: {}".format(pkt._data[:1])
)

# magic numbers:
Expand All @@ -955,7 +955,7 @@

if n != 4:
raise OperationalError("caching sha2: Unknown "
"result for fast auth: {0}".format(n))
"result for fast auth: {}".format(n))

logger.debug("caching sha2: Trying full auth...")

Expand All @@ -975,7 +975,7 @@
if not pkt.is_extra_auth_data():
raise OperationalError(
"caching sha2: Unknown packet "
"for public key: {0}".format(pkt._data[:1])
"for public key: {}".format(pkt._data[:1])
)

self.server_public_key = pkt._data[1:]
Expand Down Expand Up @@ -1126,7 +1126,7 @@

def __del__(self):
if self._writer:
warnings.warn("Unclosed connection {!r}".format(self),
warnings.warn(f"Unclosed connection {self!r}",
ResourceWarning)
self.close()

Expand Down Expand Up @@ -1351,7 +1351,7 @@
self.description = tuple(description)


class LoadLocalFile(object):
class LoadLocalFile:
def __init__(self, filename, connection):
self.filename = filename
self.connection = connection
Expand All @@ -1364,8 +1364,8 @@
def opener(filename):
try:
self._file_object = open(filename, 'rb')
except IOError as e:
msg = "Can't find file '{0}'".format(filename)
except OSError as e:
msg = f"Can't find file '{filename}'"
raise OperationalError(1017, msg) from e

fut = self._loop.run_in_executor(self._executor, opener, self.filename)
Expand All @@ -1384,7 +1384,7 @@
except Exception as e:
self._file_object.close()
self._file_object = None
msg = "Error reading file {}".format(self.filename)
msg = f"Error reading file {self.filename}"
raise OperationalError(1024, msg) from e
return chunk

Expand Down
4 changes: 2 additions & 2 deletions aiomysql/cursors.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ def _escape_args(self, args, conn):
if isinstance(args, (tuple, list)):
return tuple(conn.escape(arg) for arg in args)
elif isinstance(args, dict):
return dict((key, conn.escape(val)) for (key, val) in args.items())
return {key: conn.escape(val) for (key, val) in args.items()}
else:
# If it's not a dictionary let's try escaping it anyways.
# Worst case it will throw a Value error
Expand Down Expand Up @@ -357,7 +357,7 @@ async def callproc(self, procname, args=()):
await self.nextset()

_args = ','.join('@_%s_%d' % (procname, i) for i in range(len(args)))
q = "CALL %s(%s)" % (procname, _args)
q = f"CALL {procname}({_args})"
await self._query(q)
self._executed = q
return args
Expand Down
4 changes: 2 additions & 2 deletions aiomysql/sa/transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from . import exc


class Transaction(object):
class Transaction:
"""Represent a database transaction in progress.

The Transaction object is procured by
Expand Down Expand Up @@ -114,7 +114,7 @@ class NestedTransaction(Transaction):
_savepoint = None

def __init__(self, connection, parent):
super(NestedTransaction, self).__init__(connection, parent)
super().__init__(connection, parent)

async def _do_rollback(self):
assert self._savepoint is not None, "Broken transaction logic"
Expand Down
1 change: 0 additions & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# aiomysql documentation build configuration file, created by
# sphinx-quickstart on Sun Jan 18 22:02:31 2015.
Expand Down
6 changes: 3 additions & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
ids.append(label)
else:
mysql_addresses.append(opt_mysql_unix_socket[i])
ids.append("unix{}".format(i))
ids.append(f"unix{i}")

Check warning on line 43 in tests/conftest.py

View check run for this annotation

Codecov / codecov/patch

tests/conftest.py#L43

Added line #L43 was not covered by tests

opt_mysql_address = list(metafunc.config.getoption("mysql_address"))
for i in range(len(opt_mysql_address)):
Expand All @@ -49,7 +49,7 @@
ids.append(label)
else:
addr = opt_mysql_address[i]
ids.append("tcp{}".format(i))
ids.append(f"tcp{i}")

Check warning on line 52 in tests/conftest.py

View check run for this annotation

Codecov / codecov/patch

tests/conftest.py#L52

Added line #L52 was not covered by tests

if ":" in addr:
addr = addr.split(":", 1)
Expand Down Expand Up @@ -232,7 +232,7 @@
yield _register_table
for t in table_list:
# TODO: probably this is not safe code
sql = "DROP TABLE IF EXISTS {};".format(t)
sql = f"DROP TABLE IF EXISTS {t};"
loop.run_until_complete(cursor.execute(sql))


Expand Down
6 changes: 3 additions & 3 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async def test_datatypes(connection, cursor, datatype_table):
# insert values
v = (
True, -3, 123456789012, 5.7, "hello'\" world",
u"Espa\xc3\xb1ol",
"Espa\xc3\xb1ol",
"binary\x00data".encode(encoding),
datetime.date(1988, 2, 2),
datetime.datetime.now().replace(microsecond=0),
Expand Down Expand Up @@ -148,10 +148,10 @@ async def test_binary_data(cursor, table_cleanup):
async def test_untyped_convertion_to_null_and_empty_string(cursor):
await cursor.execute("select null,''")
r = await cursor.fetchone()
assert (None, u'') == r
assert (None, '') == r
await cursor.execute("select '',null")
r = await cursor.fetchone()
assert (u'', None) == r
assert ('', None) == r


@pytest.mark.run_loop
Expand Down
8 changes: 4 additions & 4 deletions tests/test_issues.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,10 +122,10 @@ async def test_issue_15(connection):
await c.execute("create table issue15 (t varchar(32))")
try:
await c.execute("insert into issue15 (t) values (%s)",
(u'\xe4\xf6\xfc',))
('\xe4\xf6\xfc',))
await c.execute("select t from issue15")
r = await c.fetchone()
assert u'\xe4\xf6\xfc' == r[0]
assert '\xe4\xf6\xfc' == r[0]
finally:
await c.execute("drop table issue15")

Expand Down Expand Up @@ -412,8 +412,8 @@ async def test_issue_175(connection):
conn = connection
cur = await conn.cursor()
for length in (200, 300):
cols = ', '.join('c{0} integer'.format(i) for i in range(length))
sql = 'create table test_field_count ({0})'.format(cols)
cols = ', '.join(f'c{i} integer' for i in range(length))
sql = f'create table test_field_count ({cols})'
try:
await cur.execute(sql)
await cur.execute('select * from test_field_count')
Expand Down
2 changes: 1 addition & 1 deletion tests/test_sha_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
def ensure_mysql_version(mysql_server):
if mysql_server["db_type"] != "mysql" \
or mysql_server["server_version_tuple_short"] != (8, 0):
pytest.skip("Not applicable for {0} version: {1}"
pytest.skip("Not applicable for {} version: {}"
.format(mysql_server["db_type"],
mysql_server["server_version_tuple_short"]))

Expand Down
8 changes: 4 additions & 4 deletions tests/test_sscursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@ async def test_ssursor(connection):
cursor = await conn.cursor(SSCursor)
# Create table
await cursor.execute('DROP TABLE IF EXISTS tz_data;')
await cursor.execute(('CREATE TABLE tz_data ('
'region VARCHAR(64),'
'zone VARCHAR(64),'
'name VARCHAR(64))'))
await cursor.execute('CREATE TABLE tz_data ('
'region VARCHAR(64),'
'zone VARCHAR(64),'
'name VARCHAR(64))')

# Test INSERT
for i in DATA:
Expand Down
Loading