Skip to content

Commit

Permalink
enable PTH rule (#4476)
Browse files Browse the repository at this point in the history
* 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 <m_github@0x26.net>

* format pyproject.toml

---------

Co-authored-by: Masen Furer <m_github@0x26.net>
  • Loading branch information
Lendemor and masenf authored Dec 13, 2024
1 parent 1444421 commit 61cb725
Show file tree
Hide file tree
Showing 19 changed files with 95 additions and 104 deletions.
3 changes: 2 additions & 1 deletion benchmarks/benchmark_compile_times.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import argparse
import json
import os
from pathlib import Path

from utils import send_data_to_posthog

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

# Load the JSON data if it is a string, otherwise assume it's already a dictionary
Expand Down
3 changes: 2 additions & 1 deletion benchmarks/benchmark_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import argparse
import json
import os
from pathlib import Path

from utils import send_data_to_posthog

Expand All @@ -18,7 +19,7 @@ def extract_stats_from_json(json_file: str) -> dict:
Returns:
dict: The stats for each test.
"""
with open(json_file, "r") as file:
with Path(json_file).open() as file:
json_data = json.load(file)

# Load the JSON data if it is a string, otherwise assume it's already a dictionary
Expand Down
31 changes: 12 additions & 19 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,19 @@ version = "0.6.7dev1"
description = "Web apps in pure Python."
license = "Apache-2.0"
authors = [
"Nikhil Rao <nikhil@reflex.dev>",
"Alek Petuskey <alek@reflex.dev>",
"Masen Furer <masen@reflex.dev>",
"Elijah Ahianyo <elijah@reflex.dev>",
"Thomas Brandého <thomas@reflex.dev>",
"Nikhil Rao <nikhil@reflex.dev>",
"Alek Petuskey <alek@reflex.dev>",
"Masen Furer <masen@reflex.dev>",
"Elijah Ahianyo <elijah@reflex.dev>",
"Thomas Brandého <thomas@reflex.dev>",
]
readme = "README.md"
homepage = "https://reflex.dev"
repository = "https://github.com/reflex-dev/reflex"
documentation = "https://reflex.dev/docs/getting-started/introduction"
keywords = [
"web",
"framework",
]
classifiers = [
"Development Status :: 4 - Beta",
]
packages = [
{include = "reflex"}
]
keywords = ["web", "framework"]
classifiers = ["Development Status :: 4 - Beta"]
packages = [{ include = "reflex" }]

[tool.poetry.dependencies]
python = "^3.9"
Expand All @@ -42,11 +35,11 @@ uvicorn = ">=0.20.0"
starlette-admin = ">=0.11.0,<1.0"
alembic = ">=1.11.1,<2.0"
platformdirs = ">=3.10.0,<5.0"
distro = {version = ">=1.8.0,<2.0", platform = "linux"}
distro = { version = ">=1.8.0,<2.0", platform = "linux" }
python-engineio = "!=4.6.0"
wrapt = [
{version = ">=1.14.0,<2.0", python = ">=3.11"},
{version = ">=1.11.0,<2.0", python = "<3.11"},
{ version = ">=1.14.0,<2.0", python = ">=3.11" },
{ version = ">=1.11.0,<2.0", python = "<3.11" },
]
packaging = ">=23.1,<25.0"
reflex-hosting-cli = ">=0.1.29,<2.0"
Expand Down Expand Up @@ -93,7 +86,7 @@ build-backend = "poetry.core.masonry.api"
[tool.ruff]
target-version = "py39"
lint.isort.split-on-trailing-comma = false
lint.select = ["B", "C4", "D", "E", "ERA", "F", "FURB", "I", "RUF", "SIM", "W"]
lint.select = ["B", "C4", "D", "E", "ERA", "F", "FURB", "I", "PTH", "RUF", "SIM", "W"]
lint.ignore = ["B008", "D205", "E501", "F403", "SIM115", "RUF006", "RUF012"]
lint.pydocstyle.convention = "google"

Expand Down
2 changes: 1 addition & 1 deletion reflex/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -873,7 +873,7 @@ def get_config(reload: bool = False) -> Config:
with _config_lock:
sys_path = sys.path.copy()
sys.path.clear()
sys.path.append(os.getcwd())
sys.path.append(str(Path.cwd()))
try:
# Try to import the module with only the current directory in the path.
return _get_config()
Expand Down
2 changes: 1 addition & 1 deletion reflex/constants/custom_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class CustomComponents(SimpleNamespace):
"""Constants for the custom components."""

# The name of the custom components source directory.
SRC_DIR = "custom_components"
SRC_DIR = Path("custom_components")
# The name of the custom components pyproject.toml file.
PYPROJECT_TOML = Path("pyproject.toml")
# The name of the custom components package README file.
Expand Down
42 changes: 21 additions & 21 deletions reflex/custom_components/custom_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,27 +150,27 @@ def _populate_demo_app(name_variants: NameVariants):
from reflex.compiler import templates
from reflex.reflex import _init

demo_app_dir = name_variants.demo_app_dir
demo_app_dir = Path(name_variants.demo_app_dir)
demo_app_name = name_variants.demo_app_name

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

os.makedirs(demo_app_dir)
demo_app_dir.mkdir(exist_ok=True)

with set_directory(demo_app_dir):
# We start with the blank template as basis.
_init(name=demo_app_name, template=constants.Templates.DEFAULT)
# Then overwrite the app source file with the one we want for testing custom components.
# This source file is rendered using jinja template file.
with open(f"{demo_app_name}/{demo_app_name}.py", "w") as f:
f.write(
templates.CUSTOM_COMPONENTS_DEMO_APP.render(
custom_component_module_dir=name_variants.custom_component_module_dir,
module_name=name_variants.module_name,
)
demo_file = Path(f"{demo_app_name}/{demo_app_name}.py")
demo_file.write_text(
templates.CUSTOM_COMPONENTS_DEMO_APP.render(
custom_component_module_dir=name_variants.custom_component_module_dir,
module_name=name_variants.module_name,
)
)
# Append the custom component package to the requirements.txt file.
with open(f"{constants.RequirementsTxt.FILE}", "a") as f:
with Path(f"{constants.RequirementsTxt.FILE}").open(mode="a") as f:
f.write(f"{name_variants.package_name}\n")


Expand Down Expand Up @@ -296,13 +296,14 @@ def _populate_custom_component_project(name_variants: NameVariants):
)

console.info(
f"Initializing the component directory: {CustomComponents.SRC_DIR}/{name_variants.custom_component_module_dir}"
f"Initializing the component directory: {CustomComponents.SRC_DIR / name_variants.custom_component_module_dir}"
)
os.makedirs(CustomComponents.SRC_DIR)
CustomComponents.SRC_DIR.mkdir(exist_ok=True)
with set_directory(CustomComponents.SRC_DIR):
os.makedirs(name_variants.custom_component_module_dir)
module_dir = Path(name_variants.custom_component_module_dir)
module_dir.mkdir(exist_ok=True, parents=True)
_write_source_and_init_py(
custom_component_src_dir=name_variants.custom_component_module_dir,
custom_component_src_dir=module_dir,
component_class_name=name_variants.component_class_name,
module_name=name_variants.module_name,
)
Expand Down Expand Up @@ -814,7 +815,7 @@ def _validate_project_info():
)
pyproject_toml["project"] = project
try:
with open(CustomComponents.PYPROJECT_TOML, "w") as f:
with CustomComponents.PYPROJECT_TOML.open("w") as f:
tomlkit.dump(pyproject_toml, f)
except (OSError, TOMLKitError) as ex:
console.error(f"Unable to write to pyproject.toml due to {ex}")
Expand Down Expand Up @@ -922,16 +923,15 @@ def _validate_url_with_protocol_prefix(url: str | None) -> bool:
def _get_file_from_prompt_in_loop() -> Tuple[bytes, str] | None:
image_file = file_extension = None
while image_file is None:
image_filepath = console.ask(
"Upload a preview image of your demo app (enter to skip)"
image_filepath = Path(
console.ask("Upload a preview image of your demo app (enter to skip)")
)
if not image_filepath:
break
file_extension = image_filepath.split(".")[-1]
file_extension = image_filepath.suffix
try:
with open(image_filepath, "rb") as f:
image_file = f.read()
return image_file, file_extension
image_file = image_filepath.read_bytes()
return image_file, file_extension
except OSError as ose:
console.error(f"Unable to read the {file_extension} file due to {ose}")
raise typer.Exit(code=1) from ose
Expand Down
3 changes: 1 addition & 2 deletions reflex/reflex.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from __future__ import annotations

import atexit
import os
from pathlib import Path
from typing import List, Optional

Expand Down Expand Up @@ -298,7 +297,7 @@ def export(
True, "--frontend-only", help="Export only frontend.", show_default=False
),
zip_dest_dir: str = typer.Option(
os.getcwd(),
str(Path.cwd()),
help="The directory to export the zip files to.",
show_default=False,
),
Expand Down
16 changes: 8 additions & 8 deletions reflex/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import functools
import inspect
import os
import pathlib
import platform
import re
import signal
Expand All @@ -20,6 +19,7 @@
import time
import types
from http.server import SimpleHTTPRequestHandler
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Expand Down Expand Up @@ -100,7 +100,7 @@ def __init__(self, path):

def __enter__(self):
"""Save current directory and perform chdir."""
self._old_cwd.append(os.getcwd())
self._old_cwd.append(Path.cwd())
os.chdir(self.path)

def __exit__(self, *excinfo):
Expand All @@ -120,8 +120,8 @@ class AppHarness:
app_source: Optional[
Callable[[], None] | types.ModuleType | str | functools.partial[Any]
]
app_path: pathlib.Path
app_module_path: pathlib.Path
app_path: Path
app_module_path: Path
app_module: Optional[types.ModuleType] = None
app_instance: Optional[reflex.App] = None
frontend_process: Optional[subprocess.Popen] = None
Expand All @@ -136,7 +136,7 @@ class AppHarness:
@classmethod
def create(
cls,
root: pathlib.Path,
root: Path,
app_source: Optional[
Callable[[], None] | types.ModuleType | str | functools.partial[Any]
] = None,
Expand Down Expand Up @@ -814,7 +814,7 @@ def poll_for_clients(self, timeout: TimeoutType = None) -> dict[str, BaseState]:
class SimpleHTTPRequestHandlerCustomErrors(SimpleHTTPRequestHandler):
"""SimpleHTTPRequestHandler with custom error page handling."""

def __init__(self, *args, error_page_map: dict[int, pathlib.Path], **kwargs):
def __init__(self, *args, error_page_map: dict[int, Path], **kwargs):
"""Initialize the handler.
Args:
Expand Down Expand Up @@ -857,8 +857,8 @@ class Subdir404TCPServer(socketserver.TCPServer):
def __init__(
self,
*args,
root: pathlib.Path,
error_page_map: dict[int, pathlib.Path] | None,
root: Path,
error_page_map: dict[int, Path] | None,
**kwargs,
):
"""Initialize the server.
Expand Down
2 changes: 1 addition & 1 deletion reflex/utils/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def zip_app(
_zip(
component_name=constants.ComponentName.BACKEND,
target=zip_dest_dir / constants.ComponentName.BACKEND.zip(),
root_dir=Path("."),
root_dir=Path.cwd(),
dirs_to_exclude={"__pycache__"},
files_to_exclude=files_to_exclude,
top_level_dirs_to_exclude={"assets"},
Expand Down
8 changes: 4 additions & 4 deletions reflex/utils/exec.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
frontend_process = None


def detect_package_change(json_file_path: str) -> str:
def detect_package_change(json_file_path: Path) -> str:
"""Calculates the SHA-256 hash of a JSON file and returns it as a hexadecimal string.
Args:
Expand All @@ -37,7 +37,7 @@ def detect_package_change(json_file_path: str) -> str:
>>> detect_package_change("package.json")
'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6a7b8c9d0e1f2'
"""
with open(json_file_path, "r") as file:
with json_file_path.open("r") as file:
json_data = json.load(file)

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

json_file_path = get_web_dir() / constants.PackageJson.PATH
last_hash = detect_package_change(str(json_file_path))
last_hash = detect_package_change(json_file_path)
process = None
first_run = True

Expand Down Expand Up @@ -124,7 +124,7 @@ def run_process_and_launch_url(run_command: list[str], backend_present=True):
"`REFLEX_USE_NPM=1 reflex init`\n"
"`REFLEX_USE_NPM=1 reflex run`"
)
new_hash = detect_package_change(str(json_file_path))
new_hash = detect_package_change(json_file_path)
if new_hash != last_hash:
last_hash = new_hash
kill(process.pid)
Expand Down
3 changes: 1 addition & 2 deletions reflex/utils/export.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"""Export utilities."""

import os
from pathlib import Path
from typing import Optional

Expand All @@ -15,7 +14,7 @@ def export(
zipping: bool = True,
frontend: bool = True,
backend: bool = True,
zip_dest_dir: str = os.getcwd(),
zip_dest_dir: str = str(Path.cwd()),
upload_db_file: bool = False,
api_url: Optional[str] = None,
deploy_url: Optional[str] = None,
Expand Down
4 changes: 2 additions & 2 deletions reflex/utils/path_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,14 +205,14 @@ def update_json_file(file_path: str | Path, update_dict: dict[str, int | str]):
# Read the existing json object from the file.
json_object = {}
if fp.stat().st_size:
with open(fp) as f:
with fp.open() as f:
json_object = json.load(f)

# Update the json object with the new data.
json_object.update(update_dict)

# Write the updated json object to the file
with open(fp, "w") as f:
with fp.open("w") as f:
json.dump(json_object, f, ensure_ascii=False)


Expand Down
Loading

0 comments on commit 61cb725

Please sign in to comment.