1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-17 14:08:01 +00:00

Compare commits

...

4 Commits

Author SHA1 Message Date
Bob Conan
ab8b7f4eee Merge 5615da920f into b492a9d765 2024-11-17 10:47:38 -05:00
jbranchaud
b492a9d765 Add Override The Boolean Context Of A Class as a Python TIL 2024-11-17 09:44:55 -06:00
Bob Conan
5615da920f Update README.md, fix typos 2024-11-15 16:16:31 -06:00
BobConanDev
c60c63f554 Updated README.md, fix typo(s) 2024-11-15 16:42:57 -05:00
2 changed files with 90 additions and 3 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1509 TILs and counting..._
_1510 TILs and counting..._
---
@@ -190,7 +190,7 @@ _1509 TILs and counting..._
- [Aliasing An Ansible Host](devops/aliasing-an-ansible-host.md)
- [Allow Cross-Origin Requests To Include Cookies](devops/allow-cross-origin-requests-to-include-cookies.md)
- [Allow HTTPS Through Your UFW Firewall](devops/allow-https-through-your-ufw-firewall.md)
- [Check For Cached Site Assocation File For iOS](devops/check-for-cached-site-association-file-for-ios.md)
- [Check For Cached Site Association File For iOS](devops/check-for-cached-site-association-file-for-ios.md)
- [Check The Status of All Services](devops/check-the-status-of-all-services.md)
- [Check The Syntax Of nginx Files](devops/check-the-syntax-of-nginx-files.md)
- [Connect To An RDS PostgreSQL Database](devops/connect-to-an-rds-postgresql-database.md)
@@ -723,7 +723,7 @@ _1509 TILs and counting..._
- [Check If Clusters Are Upgrade Compatible](postgres/check-if-clusters-are-upgrade-compatible.md)
- [Check If The Local Server Is Running](postgres/check-if-the-local-server-is-running.md)
- [Check If User Role Exists For Database](postgres/check-if-user-role-exists-for-database.md)
- [Check Table For Any Oprhaned Records](postgres/check-table-for-any-orphaned-records.md)
- [Check Table For Any Orphaned Records](postgres/check-table-for-any-orphaned-records.md)
- [Checking Inequality](postgres/checking-inequality.md)
- [Checking The Type Of A Value](postgres/checking-the-type-of-a-value.md)
- [Clear The Screen In psql](postgres/clear-the-screen-in-psql.md)
@@ -888,6 +888,7 @@ _1509 TILs and counting..._
- [Access Instance Variables](python/access-instance-variables.md)
- [Create A Dummy DataFrame In Pandas](python/create-a-dummy-dataframe-in-pandas.md)
- [Dunder Methods](python/dunder-methods.md)
- [Override The Boolean Context Of A Class](python/override-the-boolean-context-of-a-class.md)
- [Store And Access Immutable Data In A Tuple](python/store-and-access-immutable-data-in-a-tuple.md)
- [Test A Function With Pytest](python/test-a-function-with-pytest.md)
- [Use pipx To Install End User Apps](python/use-pipx-to-install-end-user-apps.md)

View File

@@ -0,0 +1,86 @@
# Override The Boolean Context Of A Class
Everything in Python has a truthiness that can be checked with `bool()`. An
empty list (`[]`) is falsy. A non-empty list (`[1,2,3]`) is truthy. Similar
with numbers:
```python
>>> bool(0)
False
>>> bool(1)
True
```
Any instance of an object is going to be truthy by default. If you want to
control in what context an instance is considered truthy or falsy, you can
override
[`__bool__()`](https://docs.python.org/3/reference/datamodel.html#object.__bool__).
If that's not implemented, but
[`__len__()`](https://docs.python.org/3/reference/datamodel.html#object.__len__)
is, then it will fallback to that.
Let's look at a few example classes:
```python
class CartZero:
def __init__(self, items=[]):
self.items = items or []
class CartBool:
def __init__(self, items=[]):
self.items = items or []
def __bool__(self):
print("__bool__() override")
return bool(self.items)
class CartLen:
def __init__(self, items=[]):
self.items = items or []
def __len__(self):
print("__len__() override")
return len(self.items)
class CartBoolAndLen:
def __init__(self, items=[]):
self.items = items or []
def __len__(self):
print("__len__() override")
return len(self.items)
def __bool__(self):
print("__bool__() override")
return bool(self.items)
cart1 = CartZero()
cart2 = CartBool()
cart3 = CartLen()
cart4 = CartBoolAndLen()
print("CartZero() -> %s" %(bool(cart1)))
print('')
print("CartBool() -> %s" %(bool(cart2)))
print('')
print("CartLen() -> %s" %(bool(cart3)))
print('')
print("CartBoolAndLen() -> %s" %(bool(cart4)))
```
An 'empty' `Cart` be default is truthy. However, we can override some
combination of `__bool__()` or `__len__()` to give it a boolean context that
goes `false` when "empty".
```
CartZero() -> True
__bool__() override
CartBool() -> False
__len__() override
CartLen() -> False
__bool__() override
CartBoolAndLen() -> False
```