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

Enable more ruff lints #7005

Merged
merged 7 commits into from
Mar 8, 2024
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: 1 addition & 1 deletion edb/common/markup/renderers/terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ def check_folded_fit(pos, data, width):
elif el == HEADER:
# ``item[1]`` -- text to output, ``item[2]`` -- its style,
#
_, text, style, level = el
_, text, style, _level = el
if item[2] is None:
result.append(item[1])
else:
Expand Down
2 changes: 1 addition & 1 deletion edb/common/parametric.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def _init_parametric_base(cls) -> None:
assert len(args) == 1

arg = args[0]
if typing_inspect.get_origin(arg) != type:
if typing_inspect.get_origin(arg) is not type:
continue

arg_args = typing_inspect.get_args(arg)
Expand Down
4 changes: 2 additions & 2 deletions edb/edgeql/compiler/inference/cardinality.py
Original file line number Diff line number Diff line change
Expand Up @@ -804,12 +804,12 @@ def __infer_oper_call(
elif str(ir.func_shortname) == 'std::EXCEPT':
# EXCEPT cardinality cannot be greater than the first argument, but
# the lower bound can be ZERO.
lower, upper = _card_to_bounds(cards[0])
_lower, upper = _card_to_bounds(cards[0])
return _bounds_to_card(CB_ZERO, upper)
elif str(ir.func_shortname) == 'std::INTERSECT':
# INTERSECT takes the minimum of cardinalities and makes the lower
# bound ZERO.
lower, upper = _card_to_bounds(min_cardinality(cards))
_lower, upper = _card_to_bounds(min_cardinality(cards))
return _bounds_to_card(CB_ZERO, upper)
elif str(ir.func_shortname) == 'std::??':
# Coalescing takes the maximum of both lower and upper bounds.
Expand Down
2 changes: 1 addition & 1 deletion edb/edgeql/compiler/schemactx.py
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,7 @@ def concretify(
return get_union_type(ts, ctx=ctx)
if els := t.get_intersection_of(ctx.env.schema):
ts = [concretify(e, ctx=ctx) for e in els.objects(ctx.env.schema)]
return get_intersection_type(ts , ctx=ctx)
return get_intersection_type(ts, ctx=ctx)
return t


Expand Down
2 changes: 1 addition & 1 deletion edb/edgeql/compiler/setgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -1944,7 +1944,7 @@ def should_materialize_type(


def get_global_param(
glob: s_globals.Global, * , ctx: context.ContextLevel) -> irast.Global:
glob: s_globals.Global, *, ctx: context.ContextLevel) -> irast.Global:
name = glob.get_name(ctx.env.schema)

if name not in ctx.env.query_globals:
Expand Down
2 changes: 1 addition & 1 deletion edb/edgeql/parser/grammar/ddl.py
Original file line number Diff line number Diff line change
Expand Up @@ -737,7 +737,7 @@ def reduce_CREATE_DATABASE_from_template(self, *kids):
CREATE DATABASE DatabaseName FROM AnyNodeName
OptCreateDatabaseCommandsBlock
"""
_, _, name, _, template, commands = kids
_, _, _name, _, _template, _commands = kids
self.val = qlast.CreateDatabase(
name=kids[2].val,
commands=kids[5].val,
Expand Down
2 changes: 1 addition & 1 deletion edb/edgeql/parser/grammar/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ def reduce_Insert(self, *kids):
shape = []

if isinstance(subj_path, qlast.Path) and \
len(subj_path.steps) == 1 and \
len(subj_path.steps) == 1 and \
isinstance(subj_path.steps[0], qlast.ObjectRef):
objtype = subj_path.steps[0]
elif isinstance(subj_path, qlast.IfElse):
Expand Down
2 changes: 1 addition & 1 deletion edb/graphql/translator.py
Original file line number Diff line number Diff line change
Expand Up @@ -532,7 +532,7 @@ def visit_FieldNode(self, node):
if self._is_duplicate_field(node):
return

is_top, path, prevt, target, steps = \
_is_top, _path, prevt, target, steps = \
self._prepare_field(node)

json_mode = False
Expand Down
2 changes: 1 addition & 1 deletion edb/pgsql/compiler/relgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -1817,7 +1817,7 @@ def process_set_as_coalesce(
with ctx.new() as newctx:
newctx.expr_exposed = False
left_ir, right_ir = (a.expr for a in expr.args)
left_card, right_card = (a.cardinality for a in expr.args)
_left_card, right_card = (a.cardinality for a in expr.args)
is_object = (
ir_set.path_id.is_objtype_path()
or ir_set.path_id.is_tuple_path()
Expand Down
4 changes: 2 additions & 2 deletions edb/pgsql/delta.py
Original file line number Diff line number Diff line change
Expand Up @@ -2679,7 +2679,7 @@ def _undo_everything(
pass

if prop.get_default(schema):
delta_alter, cmd_alter, alter_context = prop.init_delta_branch(
delta_alter, cmd_alter, _alter_context = prop.init_delta_branch(
schema, context, cmdtype=sd.AlterObject)
cmd_alter.set_attribute_value('default', None)
cmd.add(delta_alter)
Expand Down Expand Up @@ -2716,7 +2716,7 @@ def _undo_everything(
elif isinstance(obj, s_props.Property):
new_typ = props[obj]

delta_alter, cmd_alter, alter_context = obj.init_delta_branch(
delta_alter, cmd_alter, _alter_context = obj.init_delta_branch(
schema, context, cmdtype=sd.AlterObject)
cmd_alter.set_attribute_value('target', new_typ)
cmd_alter.set_attribute_value('default', None)
Expand Down
2 changes: 1 addition & 1 deletion edb/schema/pointers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1799,7 +1799,7 @@ def validate_object(
# because it's impossible to actually guarantee that any
# SELECT involving a path is non-empty
ptr_cardinality = scls.get_cardinality(schema)
default_required, default_cardinality = \
_default_required, default_cardinality = \
default_expr.irast.cardinality.to_schema_value()

if (ptr_cardinality is qltypes.SchemaCardinality.One
Expand Down
2 changes: 1 addition & 1 deletion edb/schema/reflection/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,7 @@ def generate_structure(
read_ptr = f'{read_ptr}[IS {rschema_name}]'

if field.reflection_proxy:
proxy_type, proxy_link = field.reflection_proxy
_proxy_type, proxy_link = field.reflection_proxy
read_ptr = (
f'{read_ptr}: {{name, value := .{proxy_link}.id}}'
)
Expand Down
3 changes: 2 additions & 1 deletion edb/schema/scalars.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,9 +339,10 @@ class AnonymousEnumTypeShell(s_types.TypeShell[ScalarType]):
def __init__(
self,
*,
name: s_name.Name = s_name.QualName(module='std', name='anyenum'),
name: Optional[s_name.Name] = None,
elements: Iterable[str],
) -> None:
name = name or s_name.QualName(module='std', name='anyenum')
super().__init__(name=name, schemaclass=ScalarType)
self.elements = list(elements)

Expand Down
7 changes: 4 additions & 3 deletions edb/server/compiler/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,8 +287,7 @@ def new_compiler_context(
bootstrap_mode: bool = False,
internal_schema_mode: bool = False,
protocol_version: defines.ProtocolVersion = defines.CURRENT_PROTOCOL,
backend_runtime_params: pg_params.BackendRuntimeParams = (
pg_params.get_default_runtime_params()),
backend_runtime_params: Optional[pg_params.BackendRuntimeParams] = None,
) -> CompileContext:
"""Create and return an ad-hoc compiler context."""

Expand All @@ -312,7 +311,9 @@ def new_compiler_context(
bootstrap_mode=bootstrap_mode,
internal_schema_mode=internal_schema_mode,
protocol_version=protocol_version,
backend_runtime_params=backend_runtime_params,
backend_runtime_params=(
backend_runtime_params or pg_params.get_default_runtime_params()
),
)

return ctx
Expand Down
4 changes: 2 additions & 2 deletions edb/server/compiler_pool/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,12 +381,12 @@ async def _call_for_client(
if status == 0:
worker.set_client_schema(client_id, client_schema)
if method_name == "compile":
units, new_pickled_state = data[0]
_units, new_pickled_state = data[0]
if new_pickled_state:
sid = worker._last_pickled_state = next_tx_state_id()
resp = pickle.dumps((0, (*data[0], sid)), -1)
elif status == 1:
exc, tb = data
exc, _tb = data
if not isinstance(exc, state_mod.FailedStateSync):
worker.set_client_schema(client_id, client_schema)
else:
Expand Down
4 changes: 2 additions & 2 deletions edb/server/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -863,15 +863,15 @@ def iter_environ():
except KeyError:
continue
choices = setting.enum_values
if setting.type == bool:
if setting.type is bool:
choices = ['true', 'false']
env_value = env_value.lower()
if choices is not None and env_value not in choices:
raise server.StartupError(
f"Environment variable {env_name!r} can only be one of: " +
", ".join(choices)
)
if setting.type == bool:
if setting.type is bool:
env_value = env_value == 'true'
elif not issubclass(setting.type, statypes.ScalarType): # type: ignore
env_value = setting.type(env_value) # type: ignore
Expand Down
2 changes: 1 addition & 1 deletion edb/server/pgcluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ async def _copy_database(
pg_restore = self._find_pg_binary('pg_restore')

src_conn_args, src_env = self._dump_restore_conn_args(src_dbname)
tgt_conn_args, tgt_env = self._dump_restore_conn_args(tgt_dbname)
tgt_conn_args, _tgt_env = self._dump_restore_conn_args(tgt_dbname)

dump_args = [
pg_dump, '--verbose', '--format=c', *src_conn_args, *src_args
Expand Down
2 changes: 1 addition & 1 deletion edb/server/protocol/auth_ext/ui/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -898,7 +898,7 @@ def render_password_reset_email(
</div>
</td>
</tr>
""" # noqa: E501
""" # noqa: E501
html_msg = mime_text.MIMEText(
render.base_default_email(
app_name=app_name,
Expand Down
4 changes: 2 additions & 2 deletions edb/server/protocol/auth_ext/ui/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -444,7 +444,7 @@ def base_default_email(
</table>
</div>
<!--[if mso | IE]></td></tr></table><table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" ><tr><td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"><![endif]-->
""" if logo_url else "" # noqa: E501
""" if logo_url else "" # noqa: E501

return f"""
<!doctype html>
Expand Down Expand Up @@ -601,4 +601,4 @@ def base_default_email(
</div>
</body>
</html>
""" # noqa: E501
""" # noqa: E501
2 changes: 1 addition & 1 deletion edb/testbase/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ async def _wait_for_db_config(
(
rdata,
_headers,
status,
_status,
) = cls.http_con_request(
http_con,
prefix="",
Expand Down
2 changes: 1 addition & 1 deletion edb/testbase/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -550,7 +550,7 @@ def http_con_binary_request(
(msize,) = uint32_unpack(content[1:5])
msg = protocol.ServerMessage.parse(mtype, content[5: msize + 1])
msgs.append(msg)
content = content[msize + 1 :]
content = content[msize + 1:]
return msgs, headers, status


Expand Down
4 changes: 2 additions & 2 deletions edb/tools/profiling/profiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@ def module(self) -> str:
result = self.func[0]
edgedb = str(EDGEDB_DIR) + os.sep
if result.startswith(edgedb):
return result[len(edgedb) :]
return result[len(edgedb):]

parts = []
maybe_stdlib = False
Expand Down Expand Up @@ -862,7 +862,7 @@ def build_svg_blocks_by_memory(
color=color,
level=level,
tooltip=(
f"{caller.size / 1024 :.2f} KiB / {caller.blocks}"
f"{caller.size / 1024:.2f} KiB / {caller.blocks}"
f" blocks \N{RIGHTWARDS DOUBLE ARROW} {line}"
),
w=caller.size,
Expand Down
2 changes: 1 addition & 1 deletion edb/tools/test/results.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ def _dataclass_from_dict(cls: typing.Type | None, data: typing.Any):
if not cls:
return data

if typing_inspect.get_origin(cls) == list:
if typing_inspect.get_origin(cls) is list:
args = typing_inspect.get_args(cls)
return [_dataclass_from_dict(args[0], e) for e in data]

Expand Down
26 changes: 18 additions & 8 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -212,16 +212,26 @@ ignore_errors = true
# CACHE-TAG: 1

[tool.ruff]
lint.select = ["E", "F", "B"]
lint.select = ["E", "F", "W", "B"]
lint.ignore = [
"F541",
"B008",
"B904",
"B905",
"B019",
"E731",
"E741",
"F541", # f-string without any placeholders
"B904", # Within an except clause, raise exceptions with raise ... from err
# or raise ... from None to distinguish them from errors in
# exception handling
"E731", # Do not assign a lambda expression, use a def
"E741", # Ambiguous variable name: l or i or I
"E252", # Missing whitespace around parameter equals

# TODO: enable this
"B905", # zip() without an explicit strict= parameter

# TODO: enable this (this was tried before - it is non-trivial)
"B019", # Use of functools.lru_cache or functools.cache on methods can lead
# to memory leaks
]
line-length = 80
indent-width = 4
exclude = ["postgres", ".github"]
lint.flake8-bugbear.extend-immutable-calls = [
"immutables.Map"
]
2 changes: 1 addition & 1 deletion tests/test_backend_connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ def get_connection_spec(cls, kwargs=None):
conn_spec = cls.cluster.get_connection_spec()
conn_spec['host'] = 'localhost'
if kwargs.get('dsn'):
addrs, params = pgconnparams.parse_dsn(kwargs['dsn'])
_addrs, params = pgconnparams.parse_dsn(kwargs['dsn'])
for k in (
'user',
'password',
Expand Down
2 changes: 1 addition & 1 deletion tests/test_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,7 @@ def test_doc_full_build(self):
f'STDOUT:\n{proc.stdout}\n\n'
f'STDERR:\n{proc.stderr}\n'
)

errors = []
ignored_errors = re.compile(
r'^.* WARNING: undefined label: edgedb-'
Expand Down
2 changes: 1 addition & 1 deletion tests/test_dump_v4.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ async def _ensure_schema_data_integrity(self, include_secrets):
'''
select ext::_conf::get_top_secret()
''',
['secret'] if include_secrets else [] ,
['secret'] if include_secrets else [],
)

# We took a version snapshot for 4.0, but then needed to
Expand Down
2 changes: 1 addition & 1 deletion tests/test_edgeql_data_migration.py
Original file line number Diff line number Diff line change
Expand Up @@ -6096,7 +6096,7 @@ async def test_edgeql_migration_rename_02(self):

await self.interact([
"did you rename property 'asdf' of object type 'test::Foo' to "
"'womp'?" ,
"'womp'?",

"did you create annotation 'std::title' of property 'womp'?",
])
Expand Down
2 changes: 1 addition & 1 deletion tests/test_edgeql_ddl.py
Original file line number Diff line number Diff line change
Expand Up @@ -9865,7 +9865,7 @@ async def test_edgeql_ddl_alias_11(self):
async def test_edgeql_ddl_alias_12(self):
await self.con.execute(
r"""
create alias X := 1;
create alias X := 1;
create type Y;
create global Z -> int64;
"""
Expand Down
2 changes: 1 addition & 1 deletion tests/test_edgeql_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -668,7 +668,7 @@ async def _check(_cfg_obj='Config', **kwargs):
async for tr in self.try_until_succeeds(ignore=AssertionError):
async with tr:
with self.http_con() as http_con:
rdata, _headers, status = self.http_con_request(
rdata, _headers, _status = self.http_con_request(
http_con,
prefix="",
path="server-info",
Expand Down
6 changes: 3 additions & 3 deletions tests/test_edgeql_for.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,9 +378,9 @@ async def test_edgeql_for_in_computable_02c(self):
} FILTER .name = 'Alice'
""",
[{
"select_deck" : [
{"name" : "Imp", "count" : 1},
{"name" : "Dragon", "count" : 2},
"select_deck": [
{"name": "Imp", "count": 1},
{"name": "Dragon", "count": 2},
],
}],
)
Expand Down
4 changes: 2 additions & 2 deletions tests/test_edgeql_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ async def test_edgeql_update_simple_05(self):
)

async def test_edgeql_update_returning_01(self):
orig1, orig2, orig3 = self.original
_orig1, orig2, _orig3 = self.original

await self.assert_query_result(
r"""
Expand Down Expand Up @@ -326,7 +326,7 @@ async def test_edgeql_update_returning_02(self):
)

async def test_edgeql_update_returning_03(self):
orig1, orig2, orig3 = self.original
_orig1, _orig2, _orig3 = self.original

await self.assert_query_result(
r"""
Expand Down
4 changes: 2 additions & 2 deletions tests/test_http_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,8 @@ def _scram_auth_expect_failure(self, user, password):
content,
headers,
status,
sid,
expected_server_sig,
_sid,
_expected_server_sig,
) = self._scram_auth(user, password)
self.assertEqual(status, 401)
self.assertEqual(content, b"Authentication failed")
Expand Down
Loading