From dc1bf3cff6b2f696f3904db355ade3d70aa6c009 Mon Sep 17 00:00:00 2001 From: Aryaz Eghbali <64126826+AryazE@users.noreply.github.com> Date: Thu, 7 Nov 2024 18:24:38 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Fix=20equality=20check=20for=20c?= =?UTF-8?q?ustom=20classes=20(#979)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sofie Van Landeghem Co-authored-by: svlandeg Co-authored-by: Sebastián Ramírez --- tests/test_param_meta_empty.py | 36 ++++++++++++++++++++++++++++++++++ typer/main.py | 4 ++-- 2 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 tests/test_param_meta_empty.py diff --git a/tests/test_param_meta_empty.py b/tests/test_param_meta_empty.py new file mode 100644 index 0000000000..49f94dd3b4 --- /dev/null +++ b/tests/test_param_meta_empty.py @@ -0,0 +1,36 @@ +import typer +from typer.testing import CliRunner + +runner = CliRunner() + + +def test_default_with_class_with_custom_eq(): + app = typer.Typer() + + from typer.models import ParamMeta + + class StupidClass: + def __init__(self, a): + self.a = a + + def __eq__(self, other) -> bool: + if other is ParamMeta.empty: + return True + try: + return self.a == other.a + except Exception: + return False + + def __ne__(self, other: object) -> bool: + return not self.__eq__(other) + + @app.command() + def cmd(val=StupidClass(42)): + print(val) + + assert StupidClass(666) == ParamMeta.empty + assert StupidClass(666) != StupidClass(1) + + result = runner.invoke(app) + assert result.exit_code == 0, result.output + assert "StupidClass" in result.output diff --git a/typer/main.py b/typer/main.py index 0b1837389f..e12cec0f99 100644 --- a/typer/main.py +++ b/typer/main.py @@ -821,14 +821,14 @@ def get_click_param( required = True else: default_value = parameter_info.default - elif param.default == Required or param.default == param.empty: + elif param.default == Required or param.default is param.empty: required = True parameter_info = ArgumentInfo() else: default_value = param.default parameter_info = OptionInfo() annotation: Any - if not param.annotation == param.empty: + if param.annotation is not param.empty: annotation = param.annotation else: annotation = str