| 1 |
Defensive programming |
| 2 |
===================== |
| 3 |
|
| 4 |
One idea for Brian 2 is to make it so that it's more likely that errors are |
| 5 |
raised rather than silently causing weird bugs. Some ideas in this line: |
| 6 |
|
| 7 |
Synapses.source should be stored internally as a weakref Synapses._source, and |
| 8 |
Synapses.source should be a computed attribute that dereferences this weakref. |
| 9 |
Like this, if the source object isn't kept by the user, Synapses won't store a |
| 10 |
reference to it, and so won't stop it from being deallocated. |
| 11 |
|
| 12 |
We should write an automated test that takes a piece of correct code like:: |
| 13 |
|
| 14 |
NeuronGroup(N, eqs, reset='V>Vt') |
| 15 |
|
| 16 |
and tries replacing all arguments by nonsense arguments, it should always |
| 17 |
raise an error in this case (forcing us to write code to validate the inputs). |
| 18 |
For example, you could create a new NonsenseObject class, and do this:: |
| 19 |
|
| 20 |
nonsense = NonsenseObject() |
| 21 |
NeuronGroup(nonsense, eqs, reset='V>Vt') |
| 22 |
NeuronGroup(N, nonsense, reset='V>Vt') |
| 23 |
NeuronGroup(N, eqs, nonsense) |
| 24 |
|
| 25 |
In general, the idea should be to make it hard for something incorrect to run |
| 26 |
without raising an error, preferably at the point where the user makes the error |
| 27 |
and not in some obscure way several lines later. |
| 28 |
|
| 29 |
The preferred way to validate inputs is one that handles types in a Pythonic |
| 30 |
way. For example, instead of doing something like:: |
| 31 |
|
| 32 |
if not isinstance(arg, (float, int)): |
| 33 |
raise TypeError(...) |
| 34 |
|
| 35 |
Do something like:: |
| 36 |
|
| 37 |
arg = float(arg) |
| 38 |
|
| 39 |
(or use try/except to raise a more specific error). In contrast to the |
| 40 |
``isinstance`` check it does not make any assumptions about the type except for |
| 41 |
its ability to be converted to a float. |
| 42 |
|
| 43 |
This approach is particular useful for numpy arrays:: |
| 44 |
|
| 45 |
arr = np.asarray(arg) |
| 46 |
|
| 47 |
(or ``np.asanyarray`` if you want to allow for array subclasses like arrays |
| 48 |
with units or masked arrays). This approach has also the nice advantage that it |
| 49 |
allows all "array-like" arguments, e.g. a list of numbers. |