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
Make click.Context
generic for obj
#2493
Comments
I would welcome a generic as described by the OP. However, I would discourage allowing "any user defined object" since the click docs clearly indicate that Alternatively, the typing could allow any subclass of import click
from typing import TypedDict
class MyContextObj(TypedDict):
foo: int
bar: str
class MyContext(click.Context)
obj: MyContextObj
@click.command()
@click.pass_context
def my_command(ctx: MyContext):
ctx.obj # Type checkers can tell that this has keys `foo: int` and `bar: str` Unfortunately, this code currently throws the following typing error when checked by
|
Pleasantly surprised to see some people are also looking for this. I'll look into this this week and will come with a PR that will hopefully be accepted. |
This can be fixed by using a
I couldn't find anything stating this. Do you know in which section of the docs this is described? The type hint for |
You appear to be correct. I was looking at the code example for Nested Handling and Contexts which includes an assertion that |
To add some type safety to the
obj
attribute of theContext
class, I was thinking maybe it could be made generic with respect toobj
attribute. It could then be used this way (with aTypedDict
but it could be any user defined object):That might be a bit cumbersome, so I'd understand if this is rejected (but I'm open to alternatives). Otherwise, I will be happy to implement this
The text was updated successfully, but these errors were encountered: