Skip to content

Commit 2855ed4

Browse files
authored
add some of the TRY rules (#4651)
1 parent 9c019a6 commit 2855ed4

File tree

7 files changed

+56
-38
lines changed

7 files changed

+56
-38
lines changed

pyproject.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,8 @@ build-backend = "poetry.core.masonry.api"
8686
target-version = "py39"
8787
output-format = "concise"
8888
lint.isort.split-on-trailing-comma = false
89-
lint.select = ["B", "C4", "D", "E", "ERA", "F", "FURB", "I", "PERF", "PTH", "RUF", "SIM", "T", "W"]
90-
lint.ignore = ["B008", "D205", "E501", "F403", "SIM115", "RUF006", "RUF012"]
89+
lint.select = ["B", "C4", "D", "E", "ERA", "F", "FURB", "I", "PERF", "PTH", "RUF", "SIM", "T", "TRY", "W"]
90+
lint.ignore = ["B008", "D205", "E501", "F403", "SIM115", "RUF006", "RUF012", "TRY0"]
9191
lint.pydocstyle.convention = "google"
9292

9393
[tool.ruff.lint.per-file-ignores]

reflex/app.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -463,14 +463,8 @@ def _generate_component(component: Component | ComponentCallable) -> Component:
463463
464464
Returns:
465465
The generated component.
466-
467-
Raises:
468-
exceptions.MatchTypeError: If the return types of match cases in rx.match are different.
469466
"""
470-
try:
471-
return component if isinstance(component, Component) else component()
472-
except exceptions.MatchTypeError:
473-
raise
467+
return component if isinstance(component, Component) else component()
474468

475469
def add_page(
476470
self,

reflex/components/component.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -429,20 +429,22 @@ def __init__(self, *args, **kwargs):
429429
else:
430430
continue
431431

432+
def determine_key(value):
433+
# Try to create a var from the value
434+
key = value if isinstance(value, Var) else LiteralVar.create(value)
435+
436+
# Check that the var type is not None.
437+
if key is None:
438+
raise TypeError
439+
440+
return key
441+
432442
# Check whether the key is a component prop.
433443
if types._issubclass(field_type, Var):
434444
# Used to store the passed types if var type is a union.
435445
passed_types = None
436446
try:
437-
# Try to create a var from the value.
438-
if isinstance(value, Var):
439-
kwargs[key] = value
440-
else:
441-
kwargs[key] = LiteralVar.create(value)
442-
443-
# Check that the var type is not None.
444-
if kwargs[key] is None:
445-
raise TypeError
447+
kwargs[key] = determine_key(value)
446448

447449
expected_type = fields[key].outer_type_.__args__[0]
448450
# validate literal fields.

reflex/custom_components/custom_components.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -421,12 +421,13 @@ def _run_commands_in_subprocess(cmds: list[str]) -> bool:
421421
console.debug(f"Running command: {' '.join(cmds)}")
422422
try:
423423
result = subprocess.run(cmds, capture_output=True, text=True, check=True)
424-
console.debug(result.stdout)
425-
return True
426424
except subprocess.CalledProcessError as cpe:
427425
console.error(cpe.stdout)
428426
console.error(cpe.stderr)
429427
return False
428+
else:
429+
console.debug(result.stdout)
430+
return True
430431

431432

432433
def _make_pyi_files():
@@ -931,10 +932,11 @@ def _get_file_from_prompt_in_loop() -> Tuple[bytes, str] | None:
931932
file_extension = image_filepath.suffix
932933
try:
933934
image_file = image_filepath.read_bytes()
934-
return image_file, file_extension
935935
except OSError as ose:
936936
console.error(f"Unable to read the {file_extension} file due to {ose}")
937937
raise typer.Exit(code=1) from ose
938+
else:
939+
return image_file, file_extension
938940

939941
console.debug(f"File extension detected: {file_extension}")
940942
return None

reflex/utils/prerequisites.py

Lines changed: 33 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,22 @@ def windows_npm_escape_hatch() -> bool:
278278
return environment.REFLEX_USE_NPM.get()
279279

280280

281+
def _check_app_name(config: Config):
282+
"""Check if the app name is set in the config.
283+
284+
Args:
285+
config: The config object.
286+
287+
Raises:
288+
RuntimeError: If the app name is not set in the config.
289+
"""
290+
if not config.app_name:
291+
raise RuntimeError(
292+
"Cannot get the app module because `app_name` is not set in rxconfig! "
293+
"If this error occurs in a reflex test case, ensure that `get_app` is mocked."
294+
)
295+
296+
281297
def get_app(reload: bool = False) -> ModuleType:
282298
"""Get the app module based on the default config.
283299
@@ -288,18 +304,16 @@ def get_app(reload: bool = False) -> ModuleType:
288304
The app based on the default config.
289305
290306
Raises:
291-
RuntimeError: If the app name is not set in the config.
307+
Exception: If an error occurs while getting the app module.
292308
"""
293309
from reflex.utils import telemetry
294310

295311
try:
296312
environment.RELOAD_CONFIG.set(reload)
297313
config = get_config()
298-
if not config.app_name:
299-
raise RuntimeError(
300-
"Cannot get the app module because `app_name` is not set in rxconfig! "
301-
"If this error occurs in a reflex test case, ensure that `get_app` is mocked."
302-
)
314+
315+
_check_app_name(config)
316+
303317
module = config.module
304318
sys.path.insert(0, str(Path.cwd()))
305319
app = (
@@ -315,11 +329,11 @@ def get_app(reload: bool = False) -> ModuleType:
315329

316330
# Reload the app module.
317331
importlib.reload(app)
318-
319-
return app
320332
except Exception as ex:
321333
telemetry.send_error(ex, context="frontend")
322334
raise
335+
else:
336+
return app
323337

324338

325339
def get_and_validate_app(reload: bool = False) -> AppInfo:
@@ -1189,11 +1203,12 @@ def ensure_reflex_installation_id() -> Optional[int]:
11891203
if installation_id is None:
11901204
installation_id = random.getrandbits(128)
11911205
installation_id_file.write_text(str(installation_id))
1192-
# If we get here, installation_id is definitely set
1193-
return installation_id
11941206
except Exception as e:
11951207
console.debug(f"Failed to ensure reflex installation id: {e}")
11961208
return None
1209+
else:
1210+
# If we get here, installation_id is definitely set
1211+
return installation_id
11971212

11981213

11991214
def initialize_reflex_user_directory():
@@ -1407,19 +1422,22 @@ def create_config_init_app_from_remote_template(app_name: str, template_url: str
14071422
except OSError as ose:
14081423
console.error(f"Failed to create temp directory for extracting zip: {ose}")
14091424
raise typer.Exit(1) from ose
1425+
14101426
try:
14111427
zipfile.ZipFile(zip_file_path).extractall(path=unzip_dir)
14121428
# The zip file downloaded from github looks like:
14131429
# repo-name-branch/**/*, so we need to remove the top level directory.
1414-
if len(subdirs := os.listdir(unzip_dir)) != 1:
1415-
console.error(f"Expected one directory in the zip, found {subdirs}")
1416-
raise typer.Exit(1)
1417-
template_dir = unzip_dir / subdirs[0]
1418-
console.debug(f"Template folder is located at {template_dir}")
14191430
except Exception as uze:
14201431
console.error(f"Failed to unzip the template: {uze}")
14211432
raise typer.Exit(1) from uze
14221433

1434+
if len(subdirs := os.listdir(unzip_dir)) != 1:
1435+
console.error(f"Expected one directory in the zip, found {subdirs}")
1436+
raise typer.Exit(1)
1437+
1438+
template_dir = unzip_dir / subdirs[0]
1439+
console.debug(f"Template folder is located at {template_dir}")
1440+
14231441
# Move the rxconfig file here first.
14241442
path_ops.mv(str(template_dir / constants.Config.FILE), constants.Config.FILE)
14251443
new_config = get_config(reload=True)

reflex/utils/telemetry.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,9 +156,10 @@ def _prepare_event(event: str, **kwargs) -> dict:
156156
def _send_event(event_data: dict) -> bool:
157157
try:
158158
httpx.post(POSTHOG_API_URL, json=event_data)
159-
return True
160159
except Exception:
161160
return False
161+
else:
162+
return True
162163

163164

164165
def _send(event, telemetry_enabled, **kwargs):

tests/integration/test_connection_banner.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,10 @@ def has_error_modal(driver: WebDriver) -> bool:
7171
"""
7272
try:
7373
driver.find_element(By.XPATH, CONNECTION_ERROR_XPATH)
74-
return True
7574
except NoSuchElementException:
7675
return False
76+
else:
77+
return True
7778

7879

7980
@pytest.mark.asyncio

0 commit comments

Comments
 (0)