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

🐛 Fix equality check for custom classes #979

Merged
merged 5 commits into from
Nov 7, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
32 changes: 32 additions & 0 deletions tests/test_annotated.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,35 @@ def cmd(force: Annotated[bool, typer.Option("--force")] = False):
result = runner.invoke(app, ["--force"])
assert result.exit_code == 0, result.output
assert "Forcing operation" in result.output


def test_default_with_class_with_custom_eq():
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tiangolo: we might want this test in a different location in the test suite?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point! I just moved it to another file. Not sure about the name, but it will work for now. 🤷

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
4 changes: 2 additions & 2 deletions typer/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading