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

Broken code example in docs under Advanced Patterns #2707

Closed
pbhuss opened this issue Apr 17, 2024 · 1 comment · Fixed by #2708
Closed

Broken code example in docs under Advanced Patterns #2707

pbhuss opened this issue Apr 17, 2024 · 1 comment · Fixed by #2708

Comments

@pbhuss
Copy link
Contributor

pbhuss commented Apr 17, 2024

In the Managing Resources section of Advanced Patterns, there is a code example where a Repo class is used as a context manager to be passed to Context.with_resource.

    class Repo:
        def __init__(self, home=None):
            self.home = os.path.abspath(home or ".")
            self.db = None

        def __enter__(self):
            path = os.path.join(self.home, "repo.db")
            self.db = open_database(path)

        def __exit__(self, exc_type, exc_value, tb):
            self.db.close()

The __enter__ method on Repo currently returns None, which means that the code snippet below is broken since repo is None (the result of __enter__()).

    with Repo() as repo:
        repo.db.query(...)

In the snippet below that, we are also assigning None to ctx.obj, since ctx.with_resource returns the result of calling the resource’s __enter__() method.

    @click.group()
    @click.option("--repo-home", default=".repo")
    @click.pass_context
    def cli(ctx, repo_home):
        ctx.obj = ctx.with_resource(Repo(repo_home))

The fix is to have Repo.__enter__ return self.

  • Click version: 8.1.7
@pyrito
Copy link

pyrito commented Aug 22, 2024

@davidism I think this issue should be marked as resolved 😄 (I was just combing through issues to solve as a first contribution and noticed this)

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Sep 7, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants