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

Open
pbhuss opened this issue Apr 17, 2024 · 0 comments · May be fixed by #2708
Open

Broken code example in docs under Advanced Patterns #2707

pbhuss opened this issue Apr 17, 2024 · 0 comments · May be fixed by #2708

Comments

@pbhuss
Copy link

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
pbhuss added a commit to pbhuss/click that referenced this issue Apr 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant