Skip to content

Commit 61cb725

Browse files
Lendemormasenf
andauthored
enable PTH rule (#4476)
* enable PTH rule * fix import in test_call_script * fix units tests * reorder ruff rules * Update reflex/utils/build.py Co-authored-by: Masen Furer <[email protected]> * format pyproject.toml --------- Co-authored-by: Masen Furer <[email protected]>
1 parent 1444421 commit 61cb725

File tree

19 files changed

+95
-104
lines changed

19 files changed

+95
-104
lines changed

benchmarks/benchmark_compile_times.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import argparse
66
import json
77
import os
8+
from pathlib import Path
89

910
from utils import send_data_to_posthog
1011

@@ -18,7 +19,7 @@ def extract_stats_from_json(json_file: str) -> list[dict]:
1819
Returns:
1920
list[dict]: The stats for each test.
2021
"""
21-
with open(json_file, "r") as file:
22+
with Path(json_file).open() as file:
2223
json_data = json.load(file)
2324

2425
# Load the JSON data if it is a string, otherwise assume it's already a dictionary

benchmarks/benchmark_imports.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import argparse
66
import json
77
import os
8+
from pathlib import Path
89

910
from utils import send_data_to_posthog
1011

@@ -18,7 +19,7 @@ def extract_stats_from_json(json_file: str) -> dict:
1819
Returns:
1920
dict: The stats for each test.
2021
"""
21-
with open(json_file, "r") as file:
22+
with Path(json_file).open() as file:
2223
json_data = json.load(file)
2324

2425
# Load the JSON data if it is a string, otherwise assume it's already a dictionary

pyproject.toml

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,26 +4,19 @@ version = "0.6.7dev1"
44
description = "Web apps in pure Python."
55
license = "Apache-2.0"
66
authors = [
7-
"Nikhil Rao <[email protected]>",
8-
"Alek Petuskey <[email protected]>",
9-
"Masen Furer <[email protected]>",
10-
"Elijah Ahianyo <[email protected]>",
11-
"Thomas Brandého <[email protected]>",
7+
"Nikhil Rao <[email protected]>",
8+
"Alek Petuskey <[email protected]>",
9+
"Masen Furer <[email protected]>",
10+
"Elijah Ahianyo <[email protected]>",
11+
"Thomas Brandého <[email protected]>",
1212
]
1313
readme = "README.md"
1414
homepage = "https://reflex.dev"
1515
repository = "https://github.com/reflex-dev/reflex"
1616
documentation = "https://reflex.dev/docs/getting-started/introduction"
17-
keywords = [
18-
"web",
19-
"framework",
20-
]
21-
classifiers = [
22-
"Development Status :: 4 - Beta",
23-
]
24-
packages = [
25-
{include = "reflex"}
26-
]
17+
keywords = ["web", "framework"]
18+
classifiers = ["Development Status :: 4 - Beta"]
19+
packages = [{ include = "reflex" }]
2720

2821
[tool.poetry.dependencies]
2922
python = "^3.9"
@@ -42,11 +35,11 @@ uvicorn = ">=0.20.0"
4235
starlette-admin = ">=0.11.0,<1.0"
4336
alembic = ">=1.11.1,<2.0"
4437
platformdirs = ">=3.10.0,<5.0"
45-
distro = {version = ">=1.8.0,<2.0", platform = "linux"}
38+
distro = { version = ">=1.8.0,<2.0", platform = "linux" }
4639
python-engineio = "!=4.6.0"
4740
wrapt = [
48-
{version = ">=1.14.0,<2.0", python = ">=3.11"},
49-
{version = ">=1.11.0,<2.0", python = "<3.11"},
41+
{ version = ">=1.14.0,<2.0", python = ">=3.11" },
42+
{ version = ">=1.11.0,<2.0", python = "<3.11" },
5043
]
5144
packaging = ">=23.1,<25.0"
5245
reflex-hosting-cli = ">=0.1.29,<2.0"
@@ -93,7 +86,7 @@ build-backend = "poetry.core.masonry.api"
9386
[tool.ruff]
9487
target-version = "py39"
9588
lint.isort.split-on-trailing-comma = false
96-
lint.select = ["B", "C4", "D", "E", "ERA", "F", "FURB", "I", "RUF", "SIM", "W"]
89+
lint.select = ["B", "C4", "D", "E", "ERA", "F", "FURB", "I", "PTH", "RUF", "SIM", "W"]
9790
lint.ignore = ["B008", "D205", "E501", "F403", "SIM115", "RUF006", "RUF012"]
9891
lint.pydocstyle.convention = "google"
9992

reflex/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -873,7 +873,7 @@ def get_config(reload: bool = False) -> Config:
873873
with _config_lock:
874874
sys_path = sys.path.copy()
875875
sys.path.clear()
876-
sys.path.append(os.getcwd())
876+
sys.path.append(str(Path.cwd()))
877877
try:
878878
# Try to import the module with only the current directory in the path.
879879
return _get_config()

reflex/constants/custom_components.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ class CustomComponents(SimpleNamespace):
1010
"""Constants for the custom components."""
1111

1212
# The name of the custom components source directory.
13-
SRC_DIR = "custom_components"
13+
SRC_DIR = Path("custom_components")
1414
# The name of the custom components pyproject.toml file.
1515
PYPROJECT_TOML = Path("pyproject.toml")
1616
# The name of the custom components package README file.

reflex/custom_components/custom_components.py

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -150,27 +150,27 @@ def _populate_demo_app(name_variants: NameVariants):
150150
from reflex.compiler import templates
151151
from reflex.reflex import _init
152152

153-
demo_app_dir = name_variants.demo_app_dir
153+
demo_app_dir = Path(name_variants.demo_app_dir)
154154
demo_app_name = name_variants.demo_app_name
155155

156-
console.info(f"Creating app for testing: {demo_app_dir}")
156+
console.info(f"Creating app for testing: {demo_app_dir!s}")
157157

158-
os.makedirs(demo_app_dir)
158+
demo_app_dir.mkdir(exist_ok=True)
159159

160160
with set_directory(demo_app_dir):
161161
# We start with the blank template as basis.
162162
_init(name=demo_app_name, template=constants.Templates.DEFAULT)
163163
# Then overwrite the app source file with the one we want for testing custom components.
164164
# This source file is rendered using jinja template file.
165-
with open(f"{demo_app_name}/{demo_app_name}.py", "w") as f:
166-
f.write(
167-
templates.CUSTOM_COMPONENTS_DEMO_APP.render(
168-
custom_component_module_dir=name_variants.custom_component_module_dir,
169-
module_name=name_variants.module_name,
170-
)
165+
demo_file = Path(f"{demo_app_name}/{demo_app_name}.py")
166+
demo_file.write_text(
167+
templates.CUSTOM_COMPONENTS_DEMO_APP.render(
168+
custom_component_module_dir=name_variants.custom_component_module_dir,
169+
module_name=name_variants.module_name,
171170
)
171+
)
172172
# Append the custom component package to the requirements.txt file.
173-
with open(f"{constants.RequirementsTxt.FILE}", "a") as f:
173+
with Path(f"{constants.RequirementsTxt.FILE}").open(mode="a") as f:
174174
f.write(f"{name_variants.package_name}\n")
175175

176176

@@ -296,13 +296,14 @@ def _populate_custom_component_project(name_variants: NameVariants):
296296
)
297297

298298
console.info(
299-
f"Initializing the component directory: {CustomComponents.SRC_DIR}/{name_variants.custom_component_module_dir}"
299+
f"Initializing the component directory: {CustomComponents.SRC_DIR / name_variants.custom_component_module_dir}"
300300
)
301-
os.makedirs(CustomComponents.SRC_DIR)
301+
CustomComponents.SRC_DIR.mkdir(exist_ok=True)
302302
with set_directory(CustomComponents.SRC_DIR):
303-
os.makedirs(name_variants.custom_component_module_dir)
303+
module_dir = Path(name_variants.custom_component_module_dir)
304+
module_dir.mkdir(exist_ok=True, parents=True)
304305
_write_source_and_init_py(
305-
custom_component_src_dir=name_variants.custom_component_module_dir,
306+
custom_component_src_dir=module_dir,
306307
component_class_name=name_variants.component_class_name,
307308
module_name=name_variants.module_name,
308309
)
@@ -814,7 +815,7 @@ def _validate_project_info():
814815
)
815816
pyproject_toml["project"] = project
816817
try:
817-
with open(CustomComponents.PYPROJECT_TOML, "w") as f:
818+
with CustomComponents.PYPROJECT_TOML.open("w") as f:
818819
tomlkit.dump(pyproject_toml, f)
819820
except (OSError, TOMLKitError) as ex:
820821
console.error(f"Unable to write to pyproject.toml due to {ex}")
@@ -922,16 +923,15 @@ def _validate_url_with_protocol_prefix(url: str | None) -> bool:
922923
def _get_file_from_prompt_in_loop() -> Tuple[bytes, str] | None:
923924
image_file = file_extension = None
924925
while image_file is None:
925-
image_filepath = console.ask(
926-
"Upload a preview image of your demo app (enter to skip)"
926+
image_filepath = Path(
927+
console.ask("Upload a preview image of your demo app (enter to skip)")
927928
)
928929
if not image_filepath:
929930
break
930-
file_extension = image_filepath.split(".")[-1]
931+
file_extension = image_filepath.suffix
931932
try:
932-
with open(image_filepath, "rb") as f:
933-
image_file = f.read()
934-
return image_file, file_extension
933+
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

reflex/reflex.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
from __future__ import annotations
44

55
import atexit
6-
import os
76
from pathlib import Path
87
from typing import List, Optional
98

@@ -298,7 +297,7 @@ def export(
298297
True, "--frontend-only", help="Export only frontend.", show_default=False
299298
),
300299
zip_dest_dir: str = typer.Option(
301-
os.getcwd(),
300+
str(Path.cwd()),
302301
help="The directory to export the zip files to.",
303302
show_default=False,
304303
),

reflex/testing.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
import functools
99
import inspect
1010
import os
11-
import pathlib
1211
import platform
1312
import re
1413
import signal
@@ -20,6 +19,7 @@
2019
import time
2120
import types
2221
from http.server import SimpleHTTPRequestHandler
22+
from pathlib import Path
2323
from typing import (
2424
TYPE_CHECKING,
2525
Any,
@@ -100,7 +100,7 @@ def __init__(self, path):
100100

101101
def __enter__(self):
102102
"""Save current directory and perform chdir."""
103-
self._old_cwd.append(os.getcwd())
103+
self._old_cwd.append(Path.cwd())
104104
os.chdir(self.path)
105105

106106
def __exit__(self, *excinfo):
@@ -120,8 +120,8 @@ class AppHarness:
120120
app_source: Optional[
121121
Callable[[], None] | types.ModuleType | str | functools.partial[Any]
122122
]
123-
app_path: pathlib.Path
124-
app_module_path: pathlib.Path
123+
app_path: Path
124+
app_module_path: Path
125125
app_module: Optional[types.ModuleType] = None
126126
app_instance: Optional[reflex.App] = None
127127
frontend_process: Optional[subprocess.Popen] = None
@@ -136,7 +136,7 @@ class AppHarness:
136136
@classmethod
137137
def create(
138138
cls,
139-
root: pathlib.Path,
139+
root: Path,
140140
app_source: Optional[
141141
Callable[[], None] | types.ModuleType | str | functools.partial[Any]
142142
] = None,
@@ -814,7 +814,7 @@ def poll_for_clients(self, timeout: TimeoutType = None) -> dict[str, BaseState]:
814814
class SimpleHTTPRequestHandlerCustomErrors(SimpleHTTPRequestHandler):
815815
"""SimpleHTTPRequestHandler with custom error page handling."""
816816

817-
def __init__(self, *args, error_page_map: dict[int, pathlib.Path], **kwargs):
817+
def __init__(self, *args, error_page_map: dict[int, Path], **kwargs):
818818
"""Initialize the handler.
819819
820820
Args:
@@ -857,8 +857,8 @@ class Subdir404TCPServer(socketserver.TCPServer):
857857
def __init__(
858858
self,
859859
*args,
860-
root: pathlib.Path,
861-
error_page_map: dict[int, pathlib.Path] | None,
860+
root: Path,
861+
error_page_map: dict[int, Path] | None,
862862
**kwargs,
863863
):
864864
"""Initialize the server.

reflex/utils/build.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ def zip_app(
150150
_zip(
151151
component_name=constants.ComponentName.BACKEND,
152152
target=zip_dest_dir / constants.ComponentName.BACKEND.zip(),
153-
root_dir=Path("."),
153+
root_dir=Path.cwd(),
154154
dirs_to_exclude={"__pycache__"},
155155
files_to_exclude=files_to_exclude,
156156
top_level_dirs_to_exclude={"assets"},

reflex/utils/exec.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
frontend_process = None
2525

2626

27-
def detect_package_change(json_file_path: str) -> str:
27+
def detect_package_change(json_file_path: Path) -> str:
2828
"""Calculates the SHA-256 hash of a JSON file and returns it as a hexadecimal string.
2929
3030
Args:
@@ -37,7 +37,7 @@ def detect_package_change(json_file_path: str) -> str:
3737
>>> detect_package_change("package.json")
3838
'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6a7b8c9d0e1f2'
3939
"""
40-
with open(json_file_path, "r") as file:
40+
with json_file_path.open("r") as file:
4141
json_data = json.load(file)
4242

4343
# Calculate the hash
@@ -81,7 +81,7 @@ def run_process_and_launch_url(run_command: list[str], backend_present=True):
8181
from reflex.utils import processes
8282

8383
json_file_path = get_web_dir() / constants.PackageJson.PATH
84-
last_hash = detect_package_change(str(json_file_path))
84+
last_hash = detect_package_change(json_file_path)
8585
process = None
8686
first_run = True
8787

@@ -124,7 +124,7 @@ def run_process_and_launch_url(run_command: list[str], backend_present=True):
124124
"`REFLEX_USE_NPM=1 reflex init`\n"
125125
"`REFLEX_USE_NPM=1 reflex run`"
126126
)
127-
new_hash = detect_package_change(str(json_file_path))
127+
new_hash = detect_package_change(json_file_path)
128128
if new_hash != last_hash:
129129
last_hash = new_hash
130130
kill(process.pid)

0 commit comments

Comments
 (0)