Skip to content

Commit

Permalink
Upgrade Pylint to 3.0.3 (#2488)
Browse files Browse the repository at this point in the history
Co-authored-by: Charles Beauville <[email protected]>
  • Loading branch information
danieljanes and charlesbvll authored Jan 17, 2024
1 parent 1fcb147 commit 66b3bbe
Show file tree
Hide file tree
Showing 25 changed files with 87 additions and 76 deletions.
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ isort = "==5.12.0"
black = { version = "==23.10.1", extras = ["jupyter"] }
docformatter = "==1.7.5"
mypy = "==1.6.1"
pylint = "==2.13.9"
pylint = "==3.0.3"
flake8 = "==5.0.4"
pytest = "==7.4.3"
pytest-cov = "==4.1.0"
Expand Down Expand Up @@ -137,7 +137,7 @@ line-length = 88
target-version = ["py38", "py39", "py310", "py311"]

[tool.pylint."MESSAGES CONTROL"]
disable = "bad-continuation,duplicate-code,too-few-public-methods,useless-import-alias"
disable = "duplicate-code,too-few-public-methods,useless-import-alias"

[tool.pytest.ini_options]
minversion = "6.2"
Expand Down
9 changes: 6 additions & 3 deletions src/py/flwr/client/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,10 +138,12 @@ def _check_actionable_client(
client: Optional[Client], client_fn: Optional[ClientFn]
) -> None:
if client_fn is None and client is None:
raise Exception("Both `client_fn` and `client` are `None`, but one is required")
raise ValueError(
"Both `client_fn` and `client` are `None`, but one is required"
)

if client_fn is not None and client is not None:
raise Exception(
raise ValueError(
"Both `client_fn` and `client` are provided, but only one is allowed"
)

Expand All @@ -150,6 +152,7 @@ def _check_actionable_client(
# pylint: disable=too-many-branches
# pylint: disable=too-many-locals
# pylint: disable=too-many-statements
# pylint: disable=too-many-arguments
def start_client(
*,
server_address: str,
Expand Down Expand Up @@ -299,7 +302,7 @@ def single_client_factory(
cid: str, # pylint: disable=unused-argument
) -> Client:
if client is None: # Added this to keep mypy happy
raise Exception(
raise ValueError(
"Both `client_fn` and `client` are `None`, but one is required"
)
return client # Always return the same instance
Expand Down
16 changes: 8 additions & 8 deletions src/py/flwr/client/app_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,43 +41,43 @@ class PlainClient(Client):

def get_properties(self, ins: GetPropertiesIns) -> GetPropertiesRes:
"""Raise an Exception because this method is not expected to be called."""
raise Exception()
raise NotImplementedError()

def get_parameters(self, ins: GetParametersIns) -> GetParametersRes:
"""Raise an Exception because this method is not expected to be called."""
raise Exception()
raise NotImplementedError()

def fit(self, ins: FitIns) -> FitRes:
"""Raise an Exception because this method is not expected to be called."""
raise Exception()
raise NotImplementedError()

def evaluate(self, ins: EvaluateIns) -> EvaluateRes:
"""Raise an Exception because this method is not expected to be called."""
raise Exception()
raise NotImplementedError()


class NeedsWrappingClient(NumPyClient):
"""Client implementation extending the high-level NumPyClient."""

def get_properties(self, config: Config) -> Dict[str, Scalar]:
"""Raise an Exception because this method is not expected to be called."""
raise Exception()
raise NotImplementedError()

def get_parameters(self, config: Config) -> NDArrays:
"""Raise an Exception because this method is not expected to be called."""
raise Exception()
raise NotImplementedError()

def fit(
self, parameters: NDArrays, config: Config
) -> Tuple[NDArrays, int, Dict[str, Scalar]]:
"""Raise an Exception because this method is not expected to be called."""
raise Exception()
raise NotImplementedError()

def evaluate(
self, parameters: NDArrays, config: Config
) -> Tuple[float, int, Dict[str, Scalar]]:
"""Raise an Exception because this method is not expected to be called."""
raise Exception()
raise NotImplementedError()


def test_to_client_with_client() -> None:
Expand Down
8 changes: 4 additions & 4 deletions src/py/flwr/client/dpfedavg_numpy_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,16 +117,16 @@ def fit(
update = [np.subtract(x, y) for (x, y) in zip(updated_params, original_params)]

if "dpfedavg_clip_norm" not in config:
raise Exception("Clipping threshold not supplied by the server.")
raise KeyError("Clipping threshold not supplied by the server.")
if not isinstance(config["dpfedavg_clip_norm"], float):
raise Exception("Clipping threshold should be a floating point value.")
raise TypeError("Clipping threshold should be a floating point value.")

# Clipping
update, clipped = clip_by_l2(update, config["dpfedavg_clip_norm"])

if "dpfedavg_noise_stddev" in config:
if not isinstance(config["dpfedavg_noise_stddev"], float):
raise Exception(
raise TypeError(
"Scale of noise to be added should be a floating point value."
)
# Noising
Expand All @@ -138,7 +138,7 @@ def fit(
# Calculating value of norm indicator bit, required for adaptive clipping
if "dpfedavg_adaptive_clip_enabled" in config:
if not isinstance(config["dpfedavg_adaptive_clip_enabled"], bool):
raise Exception(
raise TypeError(
"dpfedavg_adaptive_clip_enabled should be a boolean-valued flag."
)
metrics["dpfedavg_norm_bit"] = not clipped
Expand Down
3 changes: 1 addition & 2 deletions src/py/flwr/client/message_handler/task_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,7 @@ def validate_task_res(task_res: TaskRes) -> bool:
initialized_fields_in_task = {field.name for field, _ in task_res.task.ListFields()}

# Check if certain fields are already initialized
# pylint: disable-next=too-many-boolean-expressions
if (
if ( # pylint: disable-next=too-many-boolean-expressions
"task_id" in initialized_fields_in_task_res
or "group_id" in initialized_fields_in_task_res
or "run_id" in initialized_fields_in_task_res
Expand Down
4 changes: 2 additions & 2 deletions src/py/flwr/client/numpy_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ def _fit(self: Client, ins: FitIns) -> FitRes:
and isinstance(results[1], int)
and isinstance(results[2], dict)
):
raise Exception(EXCEPTION_MESSAGE_WRONG_RETURN_TYPE_FIT)
raise TypeError(EXCEPTION_MESSAGE_WRONG_RETURN_TYPE_FIT)

# Return FitRes
parameters_prime, num_examples, metrics = results
Expand All @@ -266,7 +266,7 @@ def _evaluate(self: Client, ins: EvaluateIns) -> EvaluateRes:
and isinstance(results[1], int)
and isinstance(results[2], dict)
):
raise Exception(EXCEPTION_MESSAGE_WRONG_RETURN_TYPE_EVALUATE)
raise TypeError(EXCEPTION_MESSAGE_WRONG_RETURN_TYPE_EVALUATE)

# Return EvaluateRes
loss, num_examples, metrics = results
Expand Down
4 changes: 4 additions & 0 deletions src/py/flwr/client/rest_client/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ def create_node() -> None:
},
data=create_node_req_bytes,
verify=verify,
timeout=None,
)

# Check status code and headers
Expand Down Expand Up @@ -185,6 +186,7 @@ def delete_node() -> None:
},
data=delete_node_req_req_bytes,
verify=verify,
timeout=None,
)

# Check status code and headers
Expand Down Expand Up @@ -225,6 +227,7 @@ def receive() -> Optional[TaskIns]:
},
data=pull_task_ins_req_bytes,
verify=verify,
timeout=None,
)

# Check status code and headers
Expand Down Expand Up @@ -303,6 +306,7 @@ def send(task_res: TaskRes) -> None:
},
data=push_task_res_request_bytes,
verify=verify,
timeout=None,
)

state[KEY_TASK_INS] = None
Expand Down
12 changes: 6 additions & 6 deletions src/py/flwr/client/secure_aggregation/secaggplus_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,22 +333,22 @@ def _share_keys(

# Check if the size is larger than threshold
if len(state.public_keys_dict) < state.threshold:
raise Exception("Available neighbours number smaller than threshold")
raise ValueError("Available neighbours number smaller than threshold")

# Check if all public keys are unique
pk_list: List[bytes] = []
for pk1, pk2 in state.public_keys_dict.values():
pk_list.append(pk1)
pk_list.append(pk2)
if len(set(pk_list)) != len(pk_list):
raise Exception("Some public keys are identical")
raise ValueError("Some public keys are identical")

# Check if public keys of this client are correct in the dictionary
if (
state.public_keys_dict[state.sid][0] != state.pk1
or state.public_keys_dict[state.sid][1] != state.pk2
):
raise Exception(
raise ValueError(
"Own public keys are displayed in dict incorrectly, should not happen!"
)

Expand Down Expand Up @@ -393,7 +393,7 @@ def _collect_masked_input(
ciphertexts = cast(List[bytes], named_values[KEY_CIPHERTEXT_LIST])
srcs = cast(List[int], named_values[KEY_SOURCE_LIST])
if len(ciphertexts) + 1 < state.threshold:
raise Exception("Not enough available neighbour clients.")
raise ValueError("Not enough available neighbour clients.")

# Decrypt ciphertexts, verify their sources, and store shares.
for src, ciphertext in zip(srcs, ciphertexts):
Expand All @@ -409,7 +409,7 @@ def _collect_masked_input(
f"from {actual_src} instead of {src}."
)
if dst != state.sid:
ValueError(
raise ValueError(
f"Client {state.sid}: received an encrypted message"
f"for Client {dst} from Client {src}."
)
Expand Down Expand Up @@ -476,7 +476,7 @@ def _unmask(state: SecAggPlusState, named_values: Dict[str, Value]) -> Dict[str,
# Send private mask seed share for every avaliable client (including itclient)
# Send first private key share for building pairwise mask for every dropped client
if len(active_sids) < state.threshold:
raise Exception("Available neighbours number smaller than threshold")
raise ValueError("Available neighbours number smaller than threshold")

sids, shares = [], []
sids += active_sids
Expand Down
1 change: 1 addition & 0 deletions src/py/flwr/common/retry_invoker.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ class RetryInvoker:
>>> invoker.invoke(my_func, arg1, arg2, kw1=kwarg1)
"""

# pylint: disable-next=too-many-arguments
def __init__(
self,
wait_factory: Callable[[], Generator[float, None, None]],
Expand Down
16 changes: 10 additions & 6 deletions src/py/flwr/common/serde.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ def server_message_to_proto(server_message: typing.ServerMessage) -> ServerMessa
server_message.evaluate_ins,
)
)
raise Exception("No instruction set in ServerMessage, cannot serialize to ProtoBuf")
raise ValueError(
"No instruction set in ServerMessage, cannot serialize to ProtoBuf"
)


def server_message_from_proto(
Expand Down Expand Up @@ -91,7 +93,7 @@ def server_message_from_proto(
server_message_proto.evaluate_ins,
)
)
raise Exception(
raise ValueError(
"Unsupported instruction in ServerMessage, cannot deserialize from ProtoBuf"
)

Expand Down Expand Up @@ -125,7 +127,9 @@ def client_message_to_proto(client_message: typing.ClientMessage) -> ClientMessa
client_message.evaluate_res,
)
)
raise Exception("No instruction set in ClientMessage, cannot serialize to ProtoBuf")
raise ValueError(
"No instruction set in ClientMessage, cannot serialize to ProtoBuf"
)


def client_message_from_proto(
Expand Down Expand Up @@ -157,7 +161,7 @@ def client_message_from_proto(
client_message_proto.evaluate_res,
)
)
raise Exception(
raise ValueError(
"Unsupported instruction in ClientMessage, cannot deserialize from ProtoBuf"
)

Expand Down Expand Up @@ -474,7 +478,7 @@ def scalar_to_proto(scalar: typing.Scalar) -> Scalar:
if isinstance(scalar, str):
return Scalar(string=scalar)

raise Exception(
raise ValueError(
f"Accepted types: {bool, bytes, float, int, str} (but not {type(scalar)})"
)

Expand Down Expand Up @@ -518,7 +522,7 @@ def _check_value(value: typing.Value) -> None:
for element in value:
if isinstance(element, data_type):
continue
raise Exception(
raise TypeError(
f"Inconsistent type: the types of elements in the list must "
f"be the same (expected {data_type}, but got {type(element)})."
)
Expand Down
1 change: 0 additions & 1 deletion src/py/flwr/driver/app_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
# limitations under the License.
# ==============================================================================
"""Flower Driver app tests."""
# pylint: disable=no-self-use


import threading
Expand Down
2 changes: 2 additions & 0 deletions src/py/flwr/driver/driver_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ def test_del_with_initialized_driver(self) -> None:
self.driver._get_grpc_driver_and_run_id()

# Execute
# pylint: disable-next=unnecessary-dunder-call
self.driver.__del__()

# Assert
Expand All @@ -147,6 +148,7 @@ def test_del_with_initialized_driver(self) -> None:
def test_del_with_uninitialized_driver(self) -> None:
"""Test cleanup behavior when Driver is not initialized."""
# Execute
# pylint: disable-next=unnecessary-dunder-call
self.driver.__del__()

# Assert
Expand Down
8 changes: 4 additions & 4 deletions src/py/flwr/driver/grpc_driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def create_run(self, req: CreateRunRequest) -> CreateRunResponse:
# Check if channel is open
if self.stub is None:
log(ERROR, ERROR_MESSAGE_DRIVER_NOT_CONNECTED)
raise Exception("`GrpcDriver` instance not connected")
raise ConnectionError("`GrpcDriver` instance not connected")

# Call Driver API
res: CreateRunResponse = self.stub.CreateRun(request=req)
Expand All @@ -100,7 +100,7 @@ def get_nodes(self, req: GetNodesRequest) -> GetNodesResponse:
# Check if channel is open
if self.stub is None:
log(ERROR, ERROR_MESSAGE_DRIVER_NOT_CONNECTED)
raise Exception("`GrpcDriver` instance not connected")
raise ConnectionError("`GrpcDriver` instance not connected")

# Call gRPC Driver API
res: GetNodesResponse = self.stub.GetNodes(request=req)
Expand All @@ -111,7 +111,7 @@ def push_task_ins(self, req: PushTaskInsRequest) -> PushTaskInsResponse:
# Check if channel is open
if self.stub is None:
log(ERROR, ERROR_MESSAGE_DRIVER_NOT_CONNECTED)
raise Exception("`GrpcDriver` instance not connected")
raise ConnectionError("`GrpcDriver` instance not connected")

# Call gRPC Driver API
res: PushTaskInsResponse = self.stub.PushTaskIns(request=req)
Expand All @@ -122,7 +122,7 @@ def pull_task_res(self, req: PullTaskResRequest) -> PullTaskResResponse:
# Check if channel is open
if self.stub is None:
log(ERROR, ERROR_MESSAGE_DRIVER_NOT_CONNECTED)
raise Exception("`GrpcDriver` instance not connected")
raise ConnectionError("`GrpcDriver` instance not connected")

# Call Driver API
res: PullTaskResResponse = self.stub.PullTaskRes(request=req)
Expand Down
Loading

0 comments on commit 66b3bbe

Please sign in to comment.