Implement __radd__ on ModelList to make addition commutative

Because ModelList implements `__add__` we can do the following:

```python
ImmediateJobs() + ScheduledJobs()
ImmediateJobs() + []
```

Both of these call the `__add__` method of `ImmediateJobs`.

What we can’t do is this:
```python
[] + ScheduledJobs()
```

That tries to call the `__add__` method of list, which doesn’t know what
to do with an instance of `ModelList`.

The Pythonic way to deal with this is to implement `__radd__` (right
add) which is invoked when our instance is on the right hand side of the
addition operator.
This commit is contained in:
Chris Hill-Scott
2020-03-03 10:11:42 +00:00
parent 57c5c298d4
commit b1a97b0d69
2 changed files with 5 additions and 10 deletions

View File

@@ -75,13 +75,8 @@ class ModelList(ABC, Sequence):
def __add__(self, other): def __add__(self, other):
return list(self) + list(other) return list(self) + list(other)
def __radd__(self, other):
class EmptyModelList(ModelList): return list(other) + list(self)
client_method = model = None
def __init__(self, *args):
self.items = []
class InviteTokenError(Exception): class InviteTokenError(Exception):

View File

@@ -5,7 +5,7 @@ from flask import abort, current_app
from notifications_utils.timezones import local_timezone from notifications_utils.timezones import local_timezone
from werkzeug.utils import cached_property from werkzeug.utils import cached_property
from app.models import EmptyModelList, JSONModel from app.models import JSONModel
from app.models.job import ( from app.models.job import (
ImmediateJobs, ImmediateJobs,
PaginatedJobs, PaginatedJobs,
@@ -123,13 +123,13 @@ class Service(JSONModel):
@cached_property @cached_property
def immediate_jobs(self): def immediate_jobs(self):
if not self.has_jobs: if not self.has_jobs:
return EmptyModelList() return []
return ImmediateJobs(self.id) return ImmediateJobs(self.id)
@cached_property @cached_property
def scheduled_jobs(self): def scheduled_jobs(self):
if not self.has_jobs: if not self.has_jobs:
return EmptyModelList() return []
return ScheduledJobs(self.id) return ScheduledJobs(self.id)
@cached_property @cached_property