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 C4 rule #4536

Merged
merged 1 commit into from
Dec 13, 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 pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ build-backend = "poetry.core.masonry.api"
[tool.ruff]
target-version = "py39"
lint.isort.split-on-trailing-comma = false
lint.select = ["B", "D", "E", "F", "I", "SIM", "W", "RUF", "FURB", "ERA"]
lint.select = ["B", "C4", "D", "E", "ERA", "F", "FURB", "I", "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/compiler/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def compile_imports(import_dict: ParsedImportDict) -> list[dict]:
default, rest = compile_import_statement(fields)

# prevent lib from being rendered on the page if all imports are non rendered kind
if not any({f.render for f in fields}): # type: ignore
if not any(f.render for f in fields): # type: ignore
continue

if not lib:
Expand Down
14 changes: 4 additions & 10 deletions reflex/components/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -1208,7 +1208,7 @@ def _iter_parent_classes_with_method(cls, method: str) -> Iterator[Type[Componen
Yields:
The parent classes that define the method (differently than the base).
"""
seen_methods = set([getattr(Component, method)])
seen_methods = {getattr(Component, method)}
for clz in cls.mro():
if clz is Component:
break
Expand Down Expand Up @@ -1390,15 +1390,9 @@ def _get_imports(self) -> ParsedImportDict:

# Collect imports from Vars used directly by this component.
var_datas = [var._get_all_var_data() for var in self._get_vars()]
var_imports: List[ImmutableParsedImportDict] = list(
map(
lambda var_data: var_data.imports,
filter(
None,
var_datas,
),
)
)
var_imports: List[ImmutableParsedImportDict] = [
var_data.imports for var_data in var_datas if var_data is not None
]

added_import_dicts: list[ParsedImportDict] = []
for clz in self._iter_parent_classes_with_method("add_imports"):
Expand Down
2 changes: 1 addition & 1 deletion reflex/components/radix/themes/components/icon_button.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def create(cls, *children, **props) -> Component:
else:
size_map_var = Match.create(
props["size"],
*[(size, px) for size, px in RADIX_TO_LUCIDE_SIZE.items()],
*list(RADIX_TO_LUCIDE_SIZE.items()),
12,
)
if not isinstance(size_map_var, Var):
Expand Down
8 changes: 4 additions & 4 deletions reflex/components/recharts/charts.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,10 @@ def create(cls, *children, **props) -> Component:
cls._ensure_valid_dimension("width", width)
cls._ensure_valid_dimension("height", height)

dim_props = dict(
width=width or "100%",
height=height or "100%",
)
dim_props = {
"width": width or "100%",
"height": height or "100%",
}
# Provide min dimensions so the graph always appears, even if the outer container is zero-size.
if width is None:
dim_props["min_width"] = 200
Expand Down
2 changes: 1 addition & 1 deletion reflex/constants/route.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class RouteVar(SimpleNamespace):


# This subset of router_data is included in chained on_load events.
ROUTER_DATA_INCLUDE = set((RouteVar.PATH, RouteVar.ORIGIN, RouteVar.QUERY))
ROUTER_DATA_INCLUDE = {RouteVar.PATH, RouteVar.ORIGIN, RouteVar.QUERY}


class RouteRegex(SimpleNamespace):
Expand Down
12 changes: 5 additions & 7 deletions reflex/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ def __init__(
handler: EventHandler,
event_actions: Dict[str, Union[bool, int]] | None = None,
client_handler_name: str = "",
args: Tuple[Tuple[Var, Var], ...] = tuple(),
args: Tuple[Tuple[Var, Var], ...] = (),
):
"""Initialize an EventSpec.

Expand All @@ -311,7 +311,7 @@ def __init__(
object.__setattr__(self, "event_actions", event_actions)
object.__setattr__(self, "handler", handler)
object.__setattr__(self, "client_handler_name", client_handler_name)
object.__setattr__(self, "args", args or tuple())
object.__setattr__(self, "args", args or ())

def with_args(self, args: Tuple[Tuple[Var, Var], ...]) -> EventSpec:
"""Copy the event spec, with updated args.
Expand Down Expand Up @@ -513,7 +513,7 @@ def no_args_event_spec() -> Tuple[()]:
Returns:
An empty tuple.
"""
return tuple() # type: ignore
return () # type: ignore


# These chains can be used for their side effects when no other events are desired.
Expand Down Expand Up @@ -1101,9 +1101,7 @@ def run_script(
Var(javascript_code) if isinstance(javascript_code, str) else javascript_code
)

return call_function(
ArgsFunctionOperation.create(tuple(), javascript_code), callback
)
return call_function(ArgsFunctionOperation.create((), javascript_code), callback)


def get_event(state, event):
Expand Down Expand Up @@ -1455,7 +1453,7 @@ def get_handler_args(
"""
args = inspect.getfullargspec(event_spec.handler.fn).args

return event_spec.args if len(args) > 1 else tuple()
return event_spec.args if len(args) > 1 else ()


def fix_events(
Expand Down
8 changes: 4 additions & 4 deletions reflex/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,12 @@ def get_engine_args(url: str | None = None) -> dict[str, Any]:
Returns:
The database engine arguments as a dict.
"""
kwargs: dict[str, Any] = dict(
kwargs: dict[str, Any] = {
# Print the SQL queries if the log level is INFO or lower.
echo=environment.SQLALCHEMY_ECHO.get(),
"echo": environment.SQLALCHEMY_ECHO.get(),
# Check connections before returning them.
pool_pre_ping=environment.SQLALCHEMY_POOL_PRE_PING.get(),
)
"pool_pre_ping": environment.SQLALCHEMY_POOL_PRE_PING.get(),
}
conf = get_config()
url = url or conf.db_url
if url is not None and url.startswith("sqlite"):
Expand Down
4 changes: 2 additions & 2 deletions reflex/reflex.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,13 +443,13 @@ def deploy(
hidden=True,
),
regions: List[str] = typer.Option(
list(),
[],
"-r",
"--region",
help="The regions to deploy to. `reflex cloud regions` For multiple envs, repeat this option, e.g. --region sjc --region iad",
),
envs: List[str] = typer.Option(
list(),
[],
"--env",
help="The environment variables to set: <key>=<value>. For multiple envs, repeat this option, e.g. --env k1=v2 --env k2=v2.",
),
Expand Down
83 changes: 38 additions & 45 deletions reflex/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,9 +437,7 @@ def __init__(
)

# Create a fresh copy of the backend variables for this instance
self._backend_vars = copy.deepcopy(
{name: item for name, item in self.backend_vars.items()}
)
self._backend_vars = copy.deepcopy(self.backend_vars)

def __repr__(self) -> str:
"""Get the string representation of the state.
Expand Down Expand Up @@ -523,9 +521,7 @@ def __init_subclass__(cls, mixin: bool = False, **kwargs):
cls.inherited_backend_vars = parent_state.backend_vars

# Check if another substate class with the same name has already been defined.
if cls.get_name() in set(
c.get_name() for c in parent_state.class_subclasses
):
if cls.get_name() in {c.get_name() for c in parent_state.class_subclasses}:
# This should not happen, since we have added module prefix to state names in #3214
raise StateValueError(
f"The substate class '{cls.get_name()}' has been defined multiple times. "
Expand Down Expand Up @@ -788,11 +784,11 @@ def _init_var_dependency_dicts(cls):
)

# ComputedVar with cache=False always need to be recomputed
cls._always_dirty_computed_vars = set(
cls._always_dirty_computed_vars = {
cvar_name
for cvar_name, cvar in cls.computed_vars.items()
if not cvar._cache
)
}

# Any substate containing a ComputedVar with cache=False always needs to be recomputed
if cls._always_dirty_computed_vars:
Expand Down Expand Up @@ -1862,11 +1858,11 @@ def _expired_computed_vars(self) -> set[str]:
Returns:
Set of computed vars to include in the delta.
"""
return set(
return {
cvar
for cvar in self.computed_vars
if self.computed_vars[cvar].needs_update(instance=self)
)
}

def _dirty_computed_vars(
self, from_vars: set[str] | None = None, include_backend: bool = True
Expand All @@ -1880,12 +1876,12 @@ def _dirty_computed_vars(
Returns:
Set of computed vars to include in the delta.
"""
return set(
return {
cvar
for dirty_var in from_vars or self.dirty_vars
for cvar in self._computed_var_dependencies[dirty_var]
if include_backend or not self.computed_vars[cvar]._backend
)
}

@classmethod
def _potentially_dirty_substates(cls) -> set[Type[BaseState]]:
Expand All @@ -1895,16 +1891,16 @@ def _potentially_dirty_substates(cls) -> set[Type[BaseState]]:
Set of State classes that may need to be fetched to recalc computed vars.
"""
# _always_dirty_substates need to be fetched to recalc computed vars.
fetch_substates = set(
fetch_substates = {
cls.get_class_substate((cls.get_name(), *substate_name.split(".")))
for substate_name in cls._always_dirty_substates
)
}
for dependent_substates in cls._substate_var_dependencies.values():
fetch_substates.update(
set(
{
cls.get_class_substate((cls.get_name(), *substate_name.split(".")))
for substate_name in dependent_substates
)
}
)
return fetch_substates

Expand Down Expand Up @@ -2206,7 +2202,7 @@ def _field_tuple(

return md5(
pickle.dumps(
list(sorted(_field_tuple(field_name) for field_name in cls.base_vars))
sorted(_field_tuple(field_name) for field_name in cls.base_vars)
)
).hexdigest()

Expand Down Expand Up @@ -3654,33 +3650,30 @@ class MutableProxy(wrapt.ObjectProxy):
"""A proxy for a mutable object that tracks changes."""

# Methods on wrapped objects which should mark the state as dirty.
__mark_dirty_attrs__ = set(
[
"add",
"append",
"clear",
"difference_update",
"discard",
"extend",
"insert",
"intersection_update",
"pop",
"popitem",
"remove",
"reverse",
"setdefault",
"sort",
"symmetric_difference_update",
"update",
]
)
__mark_dirty_attrs__ = {
"add",
"append",
"clear",
"difference_update",
"discard",
"extend",
"insert",
"intersection_update",
"pop",
"popitem",
"remove",
"reverse",
"setdefault",
"sort",
"symmetric_difference_update",
"update",
}

# Methods on wrapped objects might return mutable objects that should be tracked.
__wrap_mutable_attrs__ = set(
[
"get",
"setdefault",
]
)
__wrap_mutable_attrs__ = {
"get",
"setdefault",
}

# These internal attributes on rx.Base should NOT be wrapped in a MutableProxy.
__never_wrap_base_attrs__ = set(Base.__dict__) - {"set"} | set(
Expand Down Expand Up @@ -3723,7 +3716,7 @@ def _mark_dirty(
self,
wrapped=None,
instance=None,
args=tuple(),
args=(),
kwargs=None,
) -> Any:
"""Mark the state as dirty, then call a wrapped function.
Expand Down Expand Up @@ -3979,7 +3972,7 @@ def _mark_dirty(
self,
wrapped=None,
instance=None,
args=tuple(),
args=(),
kwargs=None,
) -> Any:
"""Raise an exception when an attempt is made to modify the object.
Expand Down
2 changes: 1 addition & 1 deletion reflex/utils/exec.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def run_process_and_launch_url(run_command: list[str], backend_present=True):
console.print("New packages detected: Updating app...")
else:
if any(
[x in line for x in ("bin executable does not exist on disk",)]
x in line for x in ("bin executable does not exist on disk",)
):
console.error(
"Try setting `REFLEX_USE_NPM=1` and re-running `reflex init` and `reflex run` to use npm instead of bun:\n"
Expand Down
6 changes: 3 additions & 3 deletions reflex/utils/prerequisites.py
Original file line number Diff line number Diff line change
Expand Up @@ -699,7 +699,7 @@ def _update_next_config(
}
if transpile_packages:
next_config["transpilePackages"] = list(
set((format_library_name(p) for p in transpile_packages))
{format_library_name(p) for p in transpile_packages}
)
if export:
next_config["output"] = "export"
Expand Down Expand Up @@ -925,7 +925,7 @@ def _inner(*args, **kwargs):

@cached_procedure(
cache_file=str(get_web_dir() / "reflex.install_frontend_packages.cached"),
payload_fn=lambda p, c: f"{sorted(list(p))!r},{c.json()}",
payload_fn=lambda p, c: f"{sorted(p)!r},{c.json()}",
)
def install_frontend_packages(packages: set[str], config: Config):
"""Installs the base and custom frontend packages.
Expand Down Expand Up @@ -1300,7 +1300,7 @@ def get_release_by_tag(tag: str) -> dict | None:
for tp in templates_data:
if tp["hidden"] or tp["code_url"] is None:
continue
known_fields = set(f.name for f in dataclasses.fields(Template))
known_fields = {f.name for f in dataclasses.fields(Template)}
filtered_templates[tp["name"]] = Template(
**{k: v for k, v in tp.items() if k in known_fields}
)
Expand Down
Loading
Loading