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

Better error message when trying to use Optional[...] in a type parameter #2484

Closed
angus-lherrou opened this issue Apr 6, 2023 · 2 comments

Comments

@angus-lherrou
Copy link
Contributor

Click should raise a clear error when a user tries to pass a generic type such as Optional[int] as the type parameter to an option, for example:

@click.command()
@click.option("--number", "-n", type=Optional[int], default=None)
def cmd(number):
    ...

This is incorrect code, but a very reasonable mistake to make.

Currently, code like this emits a rather cryptic error like so:

Traceback (most recent call last):
  File "cmd.py", line 3, in <module>
    def cmd(number):
  File ".../lib/python3.8/site-packages/click/decorators.py", line 308, in decorator
    _param_memo(f, OptionClass(param_decls, **option_attrs))
  File ".../lib/python3.8/site-packages/click/core.py", line 2495, in __init__
    super().__init__(param_decls, type=type, multiple=multiple, **attrs)
  File ".../lib/python3.8/site-packages/click/core.py", line 2075, in __init__
    self.type = types.convert_type(type, default)
  File ".../lib/python3.8/site-packages/click/types.py", line 1040, in convert_type
    return FuncParamType(ty)
  File ".../lib/python3.8/site-packages/click/types.py", line 165, in __init__
    self.name = func.__name__
  File ".../lib/python3.8/typing.py", line 760, in __getattr__
    raise AttributeError(attr)
AttributeError: __name__

This is a fairly cryptic error, and it would be better to intercept this and raise a more descriptive error to explain the problem.

@davidism
Copy link
Member

davidism commented Apr 6, 2023

Type checking should be done using a static type checking tool. I don't plan to add more setup/runtime checks.

@angus-lherrou
Copy link
Contributor Author

@davidism this is not really about type checking. This is about emitting a better error message in a case of very reasonable incorrect usage of the library. Could you look at my example again and reconsider?

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Apr 21, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
2 participants