Skip to content

Commit 906b4d2

Browse files
fix: Ruff formatting errors (#2306)
1 parent f937d53 commit 906b4d2

File tree

18 files changed

+53
-56
lines changed

18 files changed

+53
-56
lines changed

awswrangler/_arrow.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def _extract_partitions_from_path(path_root: str, path: str) -> Dict[str, str]:
1919
raise Exception(f"Object {path} is not under the root path ({path_root}).")
2020
path_wo_filename: str = path.rpartition("/")[0] + "/"
2121
path_wo_prefix: str = path_wo_filename.replace(f"{path_root}/", "")
22-
dirs: Tuple[str, ...] = tuple(x for x in path_wo_prefix.split("/") if (x != "") and (x.count("=") > 0))
22+
dirs: Tuple[str, ...] = tuple(x for x in path_wo_prefix.split("/") if x and (x.count("=") > 0))
2323
if not dirs:
2424
return {}
2525
values_tups = cast(Tuple[Tuple[str, str]], tuple(tuple(x.split("=", maxsplit=1)[:2]) for x in dirs))

awswrangler/_data_types.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -342,9 +342,7 @@ def athena2pyarrow(dtype: str) -> pa.DataType: # pylint: disable=too-many-retur
342342
raise exceptions.UnsupportedType(f"Unsupported Athena type: {dtype}")
343343

344344

345-
def athena2pandas(
346-
dtype: str, dtype_backend: Optional[str] = None
347-
) -> str: # pylint: disable=too-many-branches,too-many-return-statements
345+
def athena2pandas(dtype: str, dtype_backend: Optional[str] = None) -> str: # pylint: disable=too-many-return-statements
348346
"""Athena to Pandas data types conversion."""
349347
dtype = dtype.lower()
350348
if dtype == "tinyint":
@@ -493,24 +491,24 @@ def pyarrow_types_from_pandas( # pylint: disable=too-many-branches,too-many-sta
493491
cols: List[str] = []
494492
cols_dtypes: Dict[str, Optional[pa.DataType]] = {}
495493
for name, dtype in df.dtypes.to_dict().items():
496-
dtype = str(dtype)
494+
dtype_str = str(dtype)
497495
if name in ignore_cols:
498496
cols_dtypes[name] = None
499-
elif dtype == "Int8":
497+
elif dtype_str == "Int8":
500498
cols_dtypes[name] = pa.int8()
501-
elif dtype == "Int16":
499+
elif dtype_str == "Int16":
502500
cols_dtypes[name] = pa.int16()
503-
elif dtype == "Int32":
501+
elif dtype_str == "Int32":
504502
cols_dtypes[name] = pa.int32()
505-
elif dtype == "Int64":
503+
elif dtype_str == "Int64":
506504
cols_dtypes[name] = pa.int64()
507-
elif dtype == "float32":
505+
elif dtype_str == "float32":
508506
cols_dtypes[name] = pa.float32()
509-
elif dtype == "float64":
507+
elif dtype_str == "float64":
510508
cols_dtypes[name] = pa.float64()
511-
elif dtype == "string":
509+
elif dtype_str == "string":
512510
cols_dtypes[name] = pa.string()
513-
elif dtype == "boolean":
511+
elif dtype_str == "boolean":
514512
cols_dtypes[name] = pa.bool_()
515513
else:
516514
cols.append(name)

awswrangler/_databases.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ def _records2df(
160160
for col_values, col_name in zip(tuple(zip(*records)), cols_names): # Transposing
161161
if (dtype is None) or (col_name not in dtype):
162162
if _oracledb_found:
163-
col_values = oracle.handle_oracle_objects(col_values, col_name)
163+
col_values = oracle.handle_oracle_objects(col_values, col_name) # ruff: noqa: PLW2901
164164
try:
165165
array: pa.Array = pa.array(obj=col_values, safe=safe) # Creating Arrow array
166166
except pa.ArrowInvalid as ex:

awswrangler/athena/_read.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def _extract_ctas_manifest_paths(path: str, boto3_session: Optional[boto3.Sessio
4040
bucket_name, key_path = _utils.parse_path(path)
4141
client_s3 = _utils.client(service_name="s3", session=boto3_session)
4242
body: bytes = client_s3.get_object(Bucket=bucket_name, Key=key_path)["Body"].read()
43-
paths = [x for x in body.decode("utf-8").split("\n") if x != ""]
43+
paths = [x for x in body.decode("utf-8").split("\n") if x]
4444
_logger.debug("Read %d paths from manifest file in: %s", len(paths), path)
4545
return paths
4646

@@ -58,7 +58,7 @@ def _add_query_metadata_generator(
5858
) -> Iterator[pd.DataFrame]:
5959
"""Add Query Execution metadata to every DF in iterator."""
6060
for df in dfs:
61-
df = _apply_query_metadata(df=df, query_metadata=query_metadata)
61+
df = _apply_query_metadata(df=df, query_metadata=query_metadata) # ruff: noqa: PLW2901
6262
yield df
6363

6464

awswrangler/athena/_utils.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -97,11 +97,10 @@ def _start_query_execution(
9797
args["ResultConfiguration"]["EncryptionConfiguration"] = {"EncryptionOption": wg_config.encryption}
9898
if wg_config.kms_key is not None:
9999
args["ResultConfiguration"]["EncryptionConfiguration"]["KmsKey"] = wg_config.kms_key
100-
else:
101-
if encryption is not None:
102-
args["ResultConfiguration"]["EncryptionConfiguration"] = {"EncryptionOption": encryption}
103-
if kms_key is not None:
104-
args["ResultConfiguration"]["EncryptionConfiguration"]["KmsKey"] = kms_key
100+
elif encryption is not None:
101+
args["ResultConfiguration"]["EncryptionConfiguration"] = {"EncryptionOption": encryption}
102+
if kms_key is not None:
103+
args["ResultConfiguration"]["EncryptionConfiguration"]["KmsKey"] = kms_key
105104

106105
# database
107106
if database is not None:
@@ -187,8 +186,8 @@ def _parse_describe_table(df: pd.DataFrame) -> pd.DataFrame:
187186
origin_df_dict = df.to_dict()
188187
target_df_dict: Dict[str, List[Union[str, bool]]] = {"Column Name": [], "Type": [], "Partition": [], "Comment": []}
189188
for index, col_name in origin_df_dict["col_name"].items():
190-
col_name = col_name.strip()
191-
if col_name.startswith("#") or col_name == "":
189+
col_name = col_name.strip() # ruff: noqa: PLW2901
190+
if col_name.startswith("#") or not col_name:
192191
pass
193192
elif col_name in target_df_dict["Column Name"]:
194193
index_col_name = target_df_dict["Column Name"].index(col_name)

awswrangler/data_api/_connector.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,9 @@ def _get_statement_result(self, request_id: str) -> pd.DataFrame:
107107
pass
108108

109109
@staticmethod
110-
def _get_column_value(column_value: Dict[str, Any], col_type: Optional[str] = None) -> Any:
110+
def _get_column_value( # pylint: disable=too-many-return-statements
111+
column_value: Dict[str, Any], col_type: Optional[str] = None
112+
) -> Any:
111113
"""Return the first non-null key value for a given dictionary.
112114
113115
The key names for a given record depend on the column type: stringValue, longValue, etc.

awswrangler/data_api/rds.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -313,7 +313,9 @@ def _create_table(
313313
con.execute(sql, database=database, transaction_id=transaction_id)
314314

315315

316-
def _create_value_dict(value: Any) -> Tuple[Dict[str, Any], Optional[str]]:
316+
def _create_value_dict( # pylint: disable=too-many-return-statements
317+
value: Any,
318+
) -> Tuple[Dict[str, Any], Optional[str]]:
317319
if value is None or pd.isnull(value):
318320
return {"isNull": True}, None
319321

@@ -351,7 +353,7 @@ def _generate_parameters(columns: List[str], values: List[Any]) -> List[Dict[str
351353
parameter_list = []
352354

353355
for col, value in zip(columns, values):
354-
value, type_hint = _create_value_dict(value)
356+
value, type_hint = _create_value_dict(value) # ruff: noqa: PLW2901
355357

356358
parameter = {
357359
"name": col,

awswrangler/data_api/redshift.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,13 +87,13 @@ def rollback_transaction(self, transaction_id: str) -> str:
8787
raise NotImplementedError("Redshift Data API does not support transactions.")
8888

8989
def _validate_redshift_target(self) -> None:
90-
if self.database == "":
90+
if not self.database:
9191
raise ValueError("`database` must be set for connection")
92-
if self.cluster_id == "" and self.workgroup_name == "":
92+
if not self.cluster_id and not self.workgroup_name:
9393
raise ValueError("Either `cluster_id` or `workgroup_name`(Redshift Serverless) must be set for connection")
9494

9595
def _validate_auth_method(self) -> None:
96-
if self.workgroup_name == "" and self.secret_arn == "" and self.db_user == "":
96+
if not self.workgroup_name and not self.secret_arn and not self.db_user:
9797
raise ValueError("Either `secret_arn` or `db_user` must be set for authentication")
9898

9999
def _execute_statement(

awswrangler/dynamodb/_utils.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -165,19 +165,17 @@ def _serialize_kwargs(kwargs: Dict[str, Any]) -> Dict[str, Any]:
165165

166166
if "ExpressionAttributeNames" in kwargs:
167167
kwargs["ExpressionAttributeNames"].update(names)
168-
else:
169-
if names:
170-
kwargs["ExpressionAttributeNames"] = names
168+
elif names:
169+
kwargs["ExpressionAttributeNames"] = names
171170

172171
values = {k: serializer.serialize(v) for k, v in values.items()}
173172
if "ExpressionAttributeValues" in kwargs:
174173
kwargs["ExpressionAttributeValues"] = {
175174
k: serializer.serialize(v) for k, v in kwargs["ExpressionAttributeValues"].items()
176175
}
177176
kwargs["ExpressionAttributeValues"].update(values)
178-
else:
179-
if values:
180-
kwargs["ExpressionAttributeValues"] = values
177+
elif values:
178+
kwargs["ExpressionAttributeValues"] = values
181179

182180
return kwargs
183181

awswrangler/neptune/_gremlin_parser.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def _parse_dict(data: Any) -> Any:
6868
for k, v in data.items():
6969
# If the key is a Vertex or an Edge do special processing
7070
if isinstance(k, (gremlin.Vertex, gremlin.Edge)):
71-
k = k.id
71+
k = k.id # ruff: noqa: PLW2901
7272

7373
# If the value is a list do special processing to make it a scalar if the list is of length 1
7474
if isinstance(v, list) and len(v) == 1:

0 commit comments

Comments
 (0)