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

__bool__ method on Results #1832

Closed
simonw opened this issue Oct 5, 2022 · 2 comments
Closed

__bool__ method on Results #1832

simonw opened this issue Oct 5, 2022 · 2 comments

Comments

@simonw
Copy link
Owner

simonw commented Oct 5, 2022

Wrote this code today: https://github.com/simonw/datasette-public/blob/1401bfae50e71c1dfd2bfb6954f2e86d5a7ab21b/datasette_public/__init__.py#L41

    results = await db.execute(
        "select 1 from _public_tables where table_name = ?", [table_name]
    )
    if len(results):
        return True

Would be nice if I could use if results there instead.

@simonw
Copy link
Owner Author

simonw commented Oct 5, 2022

Code can go here:

def __iter__(self):
return iter(self.rows)
def __len__(self):
return len(self.rows)

@simonw
Copy link
Owner Author

simonw commented Oct 5, 2022

Turns out this already works - __bool__ falls back on __len__: https://docs.python.org/3/reference/datamodel.html#object.__bool__

When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero.

I'll add a test to demonstrate this.

simonw added a commit that referenced this issue Oct 5, 2022
@simonw simonw closed this as completed in bbf33a7 Oct 5, 2022
simonw added a commit that referenced this issue Oct 24, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant