ruff-format: unify Black with Ruff v0.1 ()

* ruff-format: unify Black with Ruff

* ruff lint.

* v0.1.0

* run precommit

* hand fixing

* fix `not isinstance(...)`

Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>

* rev isinstance(...) with noqa

* exclude = ["*.pyi"]

* apply precommit

* apply format

* revert pyi

* fixing

* Fix or

Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>

* Update reflex/components/datadisplay/code.pyi

* Apply suggestions from code review

Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>

* Update tests/components/core/test_colors.py

* Update reflex/app.py

* Update reflex/app.py

* Update benchmarks/test_benchmark_compile_pages.py

* Update benchmarks/test_benchmark_compile_pages.py

* Update benchmarks/test_benchmark_compile_pages.py

---------

Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>
This commit is contained in:
Jirka Borovec 2024-04-23 23:40:06 +02:00 committed by GitHub
parent 8e4d6a4781
commit 4d567b7ec1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
34 changed files with 135 additions and 98 deletions

View File

@ -1,17 +1,14 @@
fail_fast: true
repos:
- repo: https://github.com/psf/black
rev: 22.10.0
hooks:
- id: black
args: [integration, reflex, tests]
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.244
rev: v0.1.0
hooks:
- id: ruff-format
args: [integration, reflex, tests]
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
args: ["--fix", "--exit-non-zero-on-fix"]
exclude: '^integration/benchmarks/'
- repo: https://github.com/RobertCraigie/pyright-python

View File

@ -162,7 +162,8 @@ def app_with_10_components(
yield AppHarness.create(
root=root,
app_source=functools.partial(
AppWithTenComponentsOnePage, render_component=render_component # type: ignore
AppWithTenComponentsOnePage,
render_component=render_component, # type: ignore
),
) # type: ignore
@ -184,7 +185,8 @@ def app_with_100_components(
yield AppHarness.create(
root=root,
app_source=functools.partial(
AppWithHundredComponentOnePage, render_component=render_component # type: ignore
AppWithHundredComponentOnePage,
render_component=render_component, # type: ignore
),
) # type: ignore
@ -206,7 +208,8 @@ def app_with_1000_components(
yield AppHarness.create(
root=root,
app_source=functools.partial(
AppWithThousandComponentsOnePage, render_component=render_component # type: ignore
AppWithThousandComponentsOnePage,
render_component=render_component, # type: ignore
),
) # type: ignore

View File

@ -225,7 +225,13 @@ def app_with_ten_pages(
an AppHarness instance
"""
root = tmp_path_factory.mktemp(f"app10")
yield AppHarness.create(root=root, app_source=functools.partial(AppWithTenPages, render_comp=render_multiple_pages)) # type: ignore
yield AppHarness.create(
root=root,
app_source=functools.partial(
AppWithTenPages,
render_comp=render_multiple_pages, # type: ignore
),
)
@pytest.fixture(scope="session")
@ -245,7 +251,8 @@ def app_with_hundred_pages(
yield AppHarness.create(
root=root,
app_source=functools.partial(
AppWithHundredPages, render_comp=render_multiple_pages # type: ignore
AppWithHundredPages,
render_comp=render_multiple_pages, # type: ignore
),
) # type: ignore
@ -267,7 +274,8 @@ def app_with_thousand_pages(
yield AppHarness.create(
root=root,
app_source=functools.partial( # type: ignore
AppWithThousandPages, render_comp=render_multiple_pages # type: ignore
AppWithThousandPages,
render_comp=render_multiple_pages, # type: ignore
),
) # type: ignore
@ -289,7 +297,8 @@ def app_with_ten_thousand_pages(
yield AppHarness.create(
root=root,
app_source=functools.partial(
AppWithTenThousandPages, render_comp=render_multiple_pages # type: ignore
AppWithTenThousandPages,
render_comp=render_multiple_pages, # type: ignore
),
) # type: ignore

View File

@ -324,12 +324,14 @@ def test_call_script(
yield_callback_button.click()
update_counter_button.click()
assert call_script.poll_for_value(counter, exp_not_equal="0") == "4"
assert call_script.poll_for_value(
results, exp_not_equal="[]"
) == '["%s1",null,{"%s3":42,"a":[1,2,3],"s":"js","o":{"a":1,"b":2}},"async %s4"]' % (
script,
script,
script,
assert (
call_script.poll_for_value(results, exp_not_equal="[]")
== '["%s1",null,{"%s3":42,"a":[1,2,3],"s":"js","o":{"a":1,"b":2}},"async %s4"]'
% (
script,
script,
script,
)
)
reset_button.click()
assert call_script.poll_for_value(counter, exp_not_equal="4") == "0"

View File

@ -55,11 +55,16 @@ def DynamicRoute():
rx.link("index", href="/", id="link_index"),
rx.link("page_X", href="/static/x", id="link_page_x"),
rx.link(
"next", href="/page/" + DynamicState.next_page, id="link_page_next" # type: ignore
"next",
href="/page/" + DynamicState.next_page,
id="link_page_next", # type: ignore
),
rx.link("missing", href="/missing", id="link_missing"),
rx.chakra.list(
rx.foreach(DynamicState.order, lambda i: rx.chakra.list_item(rx.text(i))), # type: ignore
rx.foreach(
DynamicState.order, # type: ignore
lambda i: rx.chakra.list_item(rx.text(i)),
),
),
)

View File

@ -79,7 +79,11 @@ def Table():
),
),
rx.chakra.tfoot( # type: ignore
rx.chakra.tr(rx.chakra.td("footer1"), rx.chakra.td("footer2"), rx.chakra.td("footer3")) # type: ignore
rx.chakra.tr(
rx.chakra.td("footer1"),
rx.chakra.td("footer2"),
rx.chakra.td("footer3"),
) # type: ignore
),
rx.chakra.table_caption("random caption"),
variant="striped",

View File

@ -97,16 +97,12 @@ build-backend = "poetry.core.masonry.api"
[tool.pyright]
[tool.ruff]
select = ["B", "D", "E", "F", "I", "SIM", "W"]
ignore = ["B008", "D203", "D205", "D213", "D401", "D406", "D407", "E501", "F403", "F405", "F541"]
exclude = ["*.pyi"]
target-version = "py37"
[tool.ruff.per-file-ignores]
lint.select = ["B", "D", "E", "F", "I", "SIM", "W"]
lint.ignore = ["B008", "D203", "D205", "D213", "D401", "D406", "D407", "E501", "F403", "F405", "F541"]
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]
"tests/*.py" = ["D100", "D103", "D104"]
"tests/*.py" = ["D100", "D103", "D104", "B018"]
"reflex/.templates/*.py" = ["D100", "D103", "D104"]
"*.pyi" = ["ALL"]

View File

@ -201,10 +201,10 @@ state_show = """class DataTableState(State):
data_show = """[
["1", "Harry James Potter", "31 July 1980", True, "Gryffindor", "11' Holly phoenix feather", "Stag", "Half-blood"],
["2", "Ronald Bilius Weasley", "1 March 1980", True,"Gryffindor", "12' Ash unicorn tail hair", "Jack Russell terrier", "Pure-blood"],
["3", "Hermione Jean Granger", "19 September, 1979", True, "Gryffindor", "10¾' vine wood dragon heartstring", "Otter", "Muggle-born"],
["4", "Albus Percival Wulfric Brian Dumbledore", "Late August 1881", True, "Gryffindor", "15' Elder Thestral tail hair core", "Phoenix", "Half-blood"],
["5", "Rubeus Hagrid", "6 December 1928", False, "Gryffindor", "16' Oak unknown core", "None", "Part-Human (Half-giant)"],
["6", "Fred Weasley", "1 April, 1978", True, "Gryffindor", "Unknown", "Unknown", "Pure-blood"],
["3", "Hermione Jean Granger", "19 September, 1979", True, "Gryffindor", "10¾' vine wood dragon heartstring", "Otter", "Muggle-born"],
["4", "Albus Percival Wulfric Brian Dumbledore", "Late August 1881", True, "Gryffindor", "15' Elder Thestral tail hair core", "Phoenix", "Half-blood"],
["5", "Rubeus Hagrid", "6 December 1928", False, "Gryffindor", "16' Oak unknown core", "None", "Part-Human (Half-giant)"],
["6", "Fred Weasley", "1 April, 1978", True, "Gryffindor", "Unknown", "Unknown", "Pure-blood"],
["7", "George Weasley", "1 April, 1978", True, "Gryffindor", "Unknown", "Unknown", "Pure-blood"],
]"""

View File

@ -18,8 +18,8 @@ forms_1_code = """rx.chakra.vstack(
rx.chakra.checkbox("Checked", id="check"),
rx.chakra.switch("Switched", id="switch"),
),
rx.chakra.button("Submit",
type_="submit",
rx.chakra.button("Submit",
type_="submit",
bg="#ecfdf5",
color="#047857",
border_radius="lg",

View File

@ -349,11 +349,17 @@ class App(Base):
for middleware in self.middleware:
if asyncio.iscoroutinefunction(middleware.postprocess):
out = await middleware.postprocess(
app=self, state=state, event=event, update=update # type: ignore
app=self, # type: ignore
state=state,
event=event,
update=update,
)
else:
out = middleware.postprocess(
app=self, state=state, event=event, update=update # type: ignore
app=self, # type: ignore
state=state,
event=event,
update=update,
)
if out is not None:
return out # type: ignore

View File

@ -35,7 +35,7 @@ class Accordion(ChakraComponent):
icon_pos="right",
allow_multiple: Optional[Var[bool]] = None,
allow_toggle: Optional[Var[bool]] = None,
**props
**props,
) -> Component:
"""Create an accordion component.

View File

@ -37,9 +37,9 @@ class Icon(ChakraIconComponent):
raise AttributeError(
f"Passing children to Icon component is not allowed: remove positional arguments {children} to fix"
)
if "tag" not in props.keys():
if "tag" not in props:
raise AttributeError("Missing 'tag' keyword-argument for Icon")
if type(props["tag"]) != str or props["tag"].lower() not in ICON_LIST:
if not isinstance(props["tag"], str) or props["tag"].lower() not in ICON_LIST:
raise ValueError(
f"Invalid icon tag: {props['tag']}. Please use one of the following: {sorted(ICON_LIST)}"
)

View File

@ -1404,7 +1404,7 @@ class CustomComponent(Component):
else:
value = base_value
else:
value = Var.create(value, _var_is_string=type(value) is str)
value = Var.create(value, _var_is_string=isinstance(value, str))
# Set the prop.
self.props[format.to_camel_case(key)] = value
@ -1590,9 +1590,7 @@ class NoSSRComponent(Component):
library_import = f"const {self.alias if self.alias else self.tag} = dynamic(() => import('{import_name}')"
mod_import = (
# https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#with-named-exports
f".then((mod) => mod.{self.tag})"
if not self.is_default
else ""
f".then((mod) => mod.{self.tag})" if not self.is_default else ""
)
return "".join((library_import, mod_import, opts_fragment))

View File

@ -172,7 +172,7 @@ def cond(condition: Any, c1: Any, c2: Any = None):
def create_var(cond_part):
return Var.create_safe(
cond_part,
_var_is_string=type(cond_part) is str or isinstance(cond_part, Color),
_var_is_string=isinstance(cond_part, (str, Color)),
)
# convert the truth and false cond parts into vars so the _var_data can be obtained.

View File

@ -67,7 +67,7 @@ class Match(MemoizationLeaf):
Raises:
ValueError: If the condition is not provided.
"""
match_cond_var = Var.create(cond, _var_is_string=type(cond) is str)
match_cond_var = Var.create(cond, _var_is_string=isinstance(cond, str))
if match_cond_var is None:
raise ValueError("The condition must be set")
@ -119,7 +119,7 @@ class Match(MemoizationLeaf):
_var_data = case_element._var_data if isinstance(case_element, Style) else None # type: ignore
case_element = Var.create(
case_element,
_var_is_string=type(case_element) is str or isinstance(case_element, Color),
_var_is_string=isinstance(case_element, (str, Color)),
)
if _var_data is not None:
case_element._var_data = VarData.merge(case_element._var_data, _var_data) # type: ignore

View File

@ -51,18 +51,18 @@ class Icon(LucideIconComponent):
return tag
if children:
if len(children) == 1 and type(children[0]) == str:
if len(children) == 1 and isinstance(children[0], str):
props["tag"] = children[0]
children = []
else:
raise AttributeError(
f"Passing multiple children to Icon component is not allowed: remove positional arguments {children[1:]} to fix"
)
if "tag" not in props.keys():
if "tag" not in props:
raise AttributeError("Missing 'tag' keyword-argument for Icon")
if (
type(props["tag"]) != str
not isinstance(props["tag"], str)
or map_deprecated_icon_names_05(format.to_snake_case(props["tag"]))
not in LUCIDE_ICON_LIST
):

View File

@ -102,8 +102,8 @@ class Markdown(Component):
Returns:
The markdown component.
"""
assert len(children) == 1 and types._isinstance(
children[0], Union[str, Var]
assert (
len(children) == 1 and types._isinstance(children[0], Union[str, Var])
), "Markdown component must have exactly one child containing the markdown source."
# Custom styles are deprecated.
@ -257,9 +257,7 @@ class Markdown(Component):
}
# Separate out inline code and code blocks.
components[
"code"
] = f"""{{({{node, inline, className, {_CHILDREN._var_name}, {_PROPS._var_name}}}) => {{
components["code"] = f"""{{({{node, inline, className, {_CHILDREN._var_name}, {_PROPS._var_name}}}) => {{
const match = (className || '').match(/language-(?<lang>.*)/);
const language = match ? match[1] : '';
if (language) {{
@ -277,9 +275,7 @@ class Markdown(Component):
) : (
{self.format_component("codeblock", language=Var.create_safe("language", _var_is_local=False))}
);
}}}}""".replace(
"\n", " "
)
}}}}""".replace("\n", " ")
return components

View File

@ -57,7 +57,7 @@ class IconButton(el.Button, RadixThemesComponent):
The IconButton component.
"""
if children:
if type(children[0]) == str:
if isinstance(children[0], str):
children = [
Icon.create(
children[0],
@ -68,7 +68,7 @@ class IconButton(el.Button, RadixThemesComponent):
"IconButton requires a child icon. Pass a string as the first child or a rx.icon."
)
if "size" in props:
if type(props["size"]) == str:
if isinstance(props["size"], str):
RADIX_TO_LUCIDE_SIZE = {
"1": "12px",
"2": "24px",

View File

@ -145,10 +145,8 @@ class HighLevelRadioGroup(RadixThemesComponent):
# convert only non-strings to json(JSON.stringify) so quotes are not rendered
# for string literal types.
if (
type(default_value) is str
or isinstance(default_value, Var)
and default_value._var_type is str
if isinstance(default_value, str) or (
isinstance(default_value, Var) and default_value._var_type is str
):
default_value = Var.create(default_value, _var_is_string=True) # type: ignore
else:

View File

@ -555,7 +555,6 @@ def _ensure_dist_dir(version_to_publish: str, build: bool):
if build:
# Need to check if the files here are for the version to be published.
if dist_dir.exists():
# Check if the distribution files are for the version to be published.
needs_rebuild = False
for suffix in CustomComponents.DISTRIBUTION_FILE_SUFFIXES:

View File

@ -169,7 +169,7 @@ class EventHandler(EventActionsMixin):
# Otherwise, convert to JSON.
try:
values.append(Var.create(arg, _var_is_string=type(arg) is str))
values.append(Var.create(arg, _var_is_string=isinstance(arg, str)))
except TypeError as e:
raise TypeError(
f"Arguments to event handlers must be Vars or JSON-serializable. Got {arg} of type {type(arg)}."
@ -350,7 +350,9 @@ class FileUpload(Base):
]
elif isinstance(on_upload_progress, Callable):
# Call the lambda to get the event chain.
events = call_event_fn(on_upload_progress, self.on_upload_progress_args_spec) # type: ignore
events = call_event_fn(
on_upload_progress, self.on_upload_progress_args_spec
) # type: ignore
else:
raise ValueError(f"{on_upload_progress} is not a valid event handler.")
on_upload_progress_chain = EventChain(
@ -400,7 +402,7 @@ def server_side(name: str, sig: inspect.Signature, **kwargs) -> EventSpec:
return EventSpec(
handler=EventHandler(fn=fn),
args=tuple(
(Var.create_safe(k), Var.create_safe(v, _var_is_string=type(v) is str))
(Var.create_safe(k), Var.create_safe(v, _var_is_string=isinstance(v, str)))
for k, v in kwargs.items()
),
)

View File

@ -528,7 +528,12 @@ def deploy(
hosting_cli.deploy(
app_name=app_name,
export_fn=lambda zip_dest_dir, api_url, deploy_url, frontend, backend, zipping: export_utils.export(
export_fn=lambda zip_dest_dir,
api_url,
deploy_url,
frontend,
backend,
zipping: export_utils.export(
zip_dest_dir=zip_dest_dir,
api_url=api_url,
deploy_url=deploy_url,

View File

@ -174,7 +174,9 @@ def ask(
Returns:
A string with the user input.
"""
return Prompt.ask(question, choices=choices, default=default, show_choices=show_choices) # type: ignore
return Prompt.ask(
question, choices=choices, default=default, show_choices=show_choices
) # type: ignore
def progress():

View File

@ -330,7 +330,7 @@ def format_cond(
cond = f"isTrue({cond})"
def create_var(cond_part):
return Var.create_safe(cond_part, _var_is_string=type(cond_part) is str)
return Var.create_safe(cond_part, _var_is_string=isinstance(cond_part, str))
# Format prop conds.
if is_prop:

View File

@ -66,7 +66,9 @@ class ImportVar(Base):
The name(tag name with alias) of tag.
"""
if self.alias:
return self.alias if self.is_default else " as ".join([self.tag, self.alias]) # type: ignore
return (
self.alias if self.is_default else " as ".join([self.tag, self.alias]) # type: ignore
)
else:
return self.tag or ""

View File

@ -1186,19 +1186,19 @@ def _get_rx_chakra_component_to_migrate() -> set[str]:
rx_chakra_object = getattr(reflex.chakra, rx_chakra_name)
try:
if (
inspect.ismethod(rx_chakra_object)
and inspect.isclass(rx_chakra_object.__self__)
and issubclass(rx_chakra_object.__self__, ChakraComponent)
(
inspect.ismethod(rx_chakra_object)
and inspect.isclass(rx_chakra_object.__self__)
and issubclass(rx_chakra_object.__self__, ChakraComponent)
)
or (
inspect.isclass(rx_chakra_object)
and issubclass(rx_chakra_object, ChakraComponent)
)
or rx_chakra_name in whitelist
):
names_to_migrate.add(rx_chakra_name)
elif inspect.isclass(rx_chakra_object) and issubclass(
rx_chakra_object, ChakraComponent
):
names_to_migrate.add(rx_chakra_name)
elif rx_chakra_name in whitelist:
names_to_migrate.add(rx_chakra_name)
except Exception:
raise
return names_to_migrate

View File

@ -137,7 +137,9 @@ def new_process(args, run: bool = False, show_logs: bool = False, **kwargs):
# Add the node bin path to the PATH environment variable.
env = {
**os.environ,
"PATH": os.pathsep.join([node_bin_path if node_bin_path else "", os.environ["PATH"]]), # type: ignore
"PATH": os.pathsep.join(
[node_bin_path if node_bin_path else "", os.environ["PATH"]]
), # type: ignore
**kwargs.pop("env", {}),
}
kwargs = {

View File

@ -738,9 +738,7 @@ class PyiGenerator:
mode=black.mode.Mode(is_pyi=True),
).splitlines():
# Bit of a hack here, since the AST cannot represent comments.
if "def create(" in formatted_line:
pyi_content.append(formatted_line + " # type: ignore")
elif "Figure" in formatted_line:
if "def create(" in formatted_line or "Figure" in formatted_line:
pyi_content.append(formatted_line + " # type: ignore")
else:
pyi_content.append(formatted_line)

View File

@ -359,7 +359,7 @@ try:
mime_type = MIME[image_format]
except KeyError:
# Unknown mime_type: warn and return image/png and hope the browser can sort it out.
warnings.warn(
warnings.warn( # noqa: B028
f"Unknown mime type for {image} {image_format}. Defaulting to image/png"
)
mime_type = "image/png"

View File

@ -193,7 +193,7 @@ def get_attribute_access_type(cls: GenericType, name: str) -> GenericType | None
insp = sqlalchemy.inspect(cls)
if name in insp.columns:
return insp.columns[name].type.python_type
if name not in insp.all_orm_descriptors.keys():
if name not in insp.all_orm_descriptors:
return None
descriptor = insp.all_orm_descriptors[name]
if hint := get_property_hint(descriptor):

View File

@ -818,14 +818,20 @@ class Var:
if fn is not None:
if invoke_fn:
# invoke the function on left operand.
operation_name = f"{left_operand_full_name}.{fn}({right_operand_full_name})" # type: ignore
operation_name = (
f"{left_operand_full_name}.{fn}({right_operand_full_name})"
) # type: ignore
else:
# pass the operands as arguments to the function.
operation_name = f"{left_operand_full_name} {op} {right_operand_full_name}" # type: ignore
operation_name = (
f"{left_operand_full_name} {op} {right_operand_full_name}"
) # type: ignore
operation_name = f"{fn}({operation_name})"
else:
# apply operator to operands (left operand <operator> right_operand)
operation_name = f"{left_operand_full_name} {op} {right_operand_full_name}" # type: ignore
operation_name = (
f"{left_operand_full_name} {op} {right_operand_full_name}"
) # type: ignore
operation_name = format.wrap(operation_name, "(")
else:
# apply operator to left operand (<operator> left_operand)

View File

@ -208,7 +208,11 @@ def test_create_document_root():
utils.NextScript.create(src="foo.js"),
utils.NextScript.create(src="bar.js"),
]
root = utils.create_document_root(head_components=comps, html_lang="rx", html_custom_attrs={"project": "reflex"}) # type: ignore
root = utils.create_document_root(
head_components=comps, # type: ignore
html_lang="rx",
html_custom_attrs={"project": "reflex"},
)
# Two children in head.
assert isinstance(root, utils.Html)
assert len(root.children[0].children) == 2

View File

@ -31,7 +31,9 @@ def create_color_var(color):
"var(--${state__color_state.color}-${state__color_state.shade})",
),
(
create_color_var(rx.color(f"{ColorState.color_part}ato", f"{ColorState.shade}")), # type: ignore
create_color_var(
rx.color(f"{ColorState.color_part}ato", f"{ColorState.shade}") # type: ignore
),
"var(--${state__color_state.color_part}ato-${state__color_state.shade})",
),
(
@ -39,7 +41,9 @@ def create_color_var(color):
"var(--${state__color_state.color}-${state__color_state.shade})",
),
(
create_color_var(f'{rx.color(f"{ColorState.color}", f"{ColorState.shade}")}'), # type: ignore
create_color_var(
f'{rx.color(f"{ColorState.color}", f"{ColorState.shade}")}' # type: ignore
),
"var(--${state__color_state.color}-${state__color_state.shade})",
),
],

View File

@ -13,7 +13,6 @@ from reflex.utils import types
],
)
def test_validate_literal_error_msg(params, allowed_value_str, value_str):
with pytest.raises(ValueError) as err:
types.validate_literal(*params)