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):
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):