Skip to content

Commit d7956c1

Browse files
Lendemormasenf
andauthored
enable PERF rules (#4469)
* enable PERF rules * fix scripts folder * Update reflex/compiler/utils.py Co-authored-by: Masen Furer <[email protected]> --------- Co-authored-by: Masen Furer <[email protected]>
1 parent 61cb725 commit d7956c1

File tree

12 files changed

+48
-49
lines changed

12 files changed

+48
-49
lines changed

pyproject.toml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,14 +85,15 @@ build-backend = "poetry.core.masonry.api"
8585

8686
[tool.ruff]
8787
target-version = "py39"
88+
output-format = "concise"
8889
lint.isort.split-on-trailing-comma = false
89-
lint.select = ["B", "C4", "D", "E", "ERA", "F", "FURB", "I", "PTH", "RUF", "SIM", "W"]
90+
lint.select = ["B", "C4", "D", "E", "ERA", "F", "FURB", "I", "PERF", "PTH", "RUF", "SIM", "W"]
9091
lint.ignore = ["B008", "D205", "E501", "F403", "SIM115", "RUF006", "RUF012"]
9192
lint.pydocstyle.convention = "google"
9293

9394
[tool.ruff.lint.per-file-ignores]
9495
"__init__.py" = ["F401"]
95-
"tests/*.py" = ["D100", "D103", "D104", "B018"]
96+
"tests/*.py" = ["D100", "D103", "D104", "B018", "PERF"]
9697
"reflex/.templates/*.py" = ["D100", "D103", "D104"]
9798
"*.pyi" = ["D301", "D415", "D417", "D418", "E742"]
9899
"*/blank.py" = ["I001"]

reflex/base.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,16 @@ def validate_field_name(bases: List[Type["BaseModel"]], field_name: str) -> None
3030

3131
# can't use reflex.config.environment here cause of circular import
3232
reload = os.getenv("__RELOAD_CONFIG", "").lower() == "true"
33-
for base in bases:
34-
try:
33+
base = None
34+
try:
35+
for base in bases:
3536
if not reload and getattr(base, field_name, None):
3637
pass
37-
except TypeError as te:
38-
raise VarNameError(
39-
f'State var "{field_name}" in {base} has been shadowed by a substate var; '
40-
f'use a different field name instead".'
41-
) from te
38+
except TypeError as te:
39+
raise VarNameError(
40+
f'State var "{field_name}" in {base} has been shadowed by a substate var; '
41+
f'use a different field name instead".'
42+
) from te
4243

4344

4445
# monkeypatch pydantic validate_field_name method to skip validating

reflex/compiler/utils.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,8 +123,7 @@ def compile_imports(import_dict: ParsedImportDict) -> list[dict]:
123123
raise ValueError("No default field allowed for empty library.")
124124
if rest is None or len(rest) == 0:
125125
raise ValueError("No fields to import.")
126-
for module in sorted(rest):
127-
import_dicts.append(get_import_dict(module))
126+
import_dicts.extend(get_import_dict(module) for module in sorted(rest))
128127
continue
129128

130129
# remove the version before rendering the package imports

reflex/components/component.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1403,8 +1403,9 @@ def _get_imports(self) -> ParsedImportDict:
14031403
if not isinstance(list_of_import_dict, list):
14041404
list_of_import_dict = [list_of_import_dict]
14051405

1406-
for import_dict in list_of_import_dict:
1407-
added_import_dicts.append(parse_imports(import_dict))
1406+
added_import_dicts.extend(
1407+
[parse_imports(import_dict) for import_dict in list_of_import_dict]
1408+
)
14081409

14091410
return imports.merge_imports(
14101411
*self._get_props_imports(),
@@ -1586,8 +1587,7 @@ def _get_all_hooks(self) -> dict[str, None]:
15861587
if hooks is not None:
15871588
code[hooks] = None
15881589

1589-
for hook, var_data in self._get_added_hooks().items():
1590-
code[hook] = var_data
1590+
code.update(self._get_added_hooks())
15911591

15921592
# Add the hook code for the children.
15931593
for child in self.children:

reflex/components/el/elements/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@
127127

128128

129129
EXCLUDE = ["del_", "Del", "image"]
130-
for _, v in _MAPPING.items():
130+
for v in _MAPPING.values():
131131
v.extend([mod.capitalize() for mod in v if mod not in EXCLUDE])
132132

133133
_SUBMOD_ATTRS: dict[str, list[str]] = _MAPPING

reflex/components/el/elements/__init__.pyi

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -339,5 +339,5 @@ _MAPPING = {
339339
],
340340
}
341341
EXCLUDE = ["del_", "Del", "image"]
342-
for _, v in _MAPPING.items():
342+
for v in _MAPPING.values():
343343
v.extend([mod.capitalize() for mod in v if mod not in EXCLUDE])

reflex/event.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -350,13 +350,14 @@ def add_args(self, *args: Var) -> EventSpec:
350350

351351
# Construct the payload.
352352
values = []
353-
for arg in args:
354-
try:
355-
values.append(LiteralVar.create(arg))
356-
except TypeError as e:
357-
raise EventHandlerTypeError(
358-
f"Arguments to event handlers must be Vars or JSON-serializable. Got {arg} of type {type(arg)}."
359-
) from e
353+
arg = None
354+
try:
355+
for arg in args:
356+
values.append(LiteralVar.create(value=arg)) # noqa: PERF401
357+
except TypeError as e:
358+
raise EventHandlerTypeError(
359+
f"Arguments to event handlers must be Vars or JSON-serializable. Got {arg} of type {type(arg)}."
360+
) from e
360361
new_payload = tuple(zip(fn_args, values))
361362
return self.with_args(self.args + new_payload)
362363

reflex/model.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import re
66
from collections import defaultdict
7+
from contextlib import suppress
78
from typing import Any, ClassVar, Optional, Type, Union
89

910
import alembic.autogenerate
@@ -290,11 +291,10 @@ def dict(self, **kwargs):
290291
relationships = {}
291292
# SQLModel relationships do not appear in __fields__, but should be included if present.
292293
for name in self.__sqlmodel_relationships__:
293-
try:
294+
with suppress(
295+
sqlalchemy.orm.exc.DetachedInstanceError # This happens when the relationship was never loaded and the session is closed.
296+
):
294297
relationships[name] = self._dict_recursive(getattr(self, name))
295-
except sqlalchemy.orm.exc.DetachedInstanceError:
296-
# This happens when the relationship was never loaded and the session is closed.
297-
continue
298298
return {
299299
**base_fields,
300300
**relationships,

reflex/state.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3438,17 +3438,16 @@ async def set_state(
34383438
)
34393439

34403440
# Recursively set_state on all known substates.
3441-
tasks = []
3442-
for substate in state.substates.values():
3443-
tasks.append(
3444-
asyncio.create_task(
3445-
self.set_state(
3446-
token=_substate_key(client_token, substate),
3447-
state=substate,
3448-
lock_id=lock_id,
3449-
)
3441+
tasks = [
3442+
asyncio.create_task(
3443+
self.set_state(
3444+
_substate_key(client_token, substate),
3445+
substate,
3446+
lock_id,
34503447
)
34513448
)
3449+
for substate in state.substates.values()
3450+
]
34523451
# Persist only the given state (parents or substates are excluded by BaseState.__getstate__).
34533452
if state._get_was_touched():
34543453
pickle_state = state._serialize()

reflex/utils/processes.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,16 +58,16 @@ def get_process_on_port(port) -> Optional[psutil.Process]:
5858
The process on the given port.
5959
"""
6060
for proc in psutil.process_iter(["pid", "name", "cmdline"]):
61-
try:
61+
with contextlib.suppress(
62+
psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess
63+
):
6264
if importlib.metadata.version("psutil") >= "6.0.0":
6365
conns = proc.net_connections(kind="inet") # type: ignore
6466
else:
6567
conns = proc.connections(kind="inet")
6668
for conn in conns:
6769
if conn.laddr.port == int(port):
6870
return proc
69-
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
70-
pass
7171
return None
7272

7373

0 commit comments

Comments
 (0)