mirror of
https://github.com/GSA/notifications-admin.git
synced 2026-04-20 17:20:46 -04:00
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:
@@ -75,13 +75,8 @@ class ModelList(ABC, Sequence):
|
||||
def __add__(self, other):
|
||||
return list(self) + list(other)
|
||||
|
||||
|
||||
class EmptyModelList(ModelList):
|
||||
|
||||
client_method = model = None
|
||||
|
||||
def __init__(self, *args):
|
||||
self.items = []
|
||||
def __radd__(self, other):
|
||||
return list(other) + list(self)
|
||||
|
||||
|
||||
class InviteTokenError(Exception):
|
||||
|
||||
@@ -5,7 +5,7 @@ from flask import abort, current_app
|
||||
from notifications_utils.timezones import local_timezone
|
||||
from werkzeug.utils import cached_property
|
||||
|
||||
from app.models import EmptyModelList, JSONModel
|
||||
from app.models import JSONModel
|
||||
from app.models.job import (
|
||||
ImmediateJobs,
|
||||
PaginatedJobs,
|
||||
@@ -123,13 +123,13 @@ class Service(JSONModel):
|
||||
@cached_property
|
||||
def immediate_jobs(self):
|
||||
if not self.has_jobs:
|
||||
return EmptyModelList()
|
||||
return []
|
||||
return ImmediateJobs(self.id)
|
||||
|
||||
@cached_property
|
||||
def scheduled_jobs(self):
|
||||
if not self.has_jobs:
|
||||
return EmptyModelList()
|
||||
return []
|
||||
return ScheduledJobs(self.id)
|
||||
|
||||
@cached_property
|
||||
|
||||
Reference in New Issue
Block a user