Skip to content

Commit e545185

Browse files
committed
refactor(mode): validate mode property in Python class
1 parent 2ef6468 commit e545185

File tree

2 files changed

+32
-23
lines changed

2 files changed

+32
-23
lines changed

spidev/_cspi.c

Lines changed: 1 addition & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1012,28 +1012,8 @@ SpiDev_set_mode(SpiDevObject *self, PyObject *val, void *closure)
10121012
"Cannot delete attribute");
10131013
return -1;
10141014
}
1015-
#if PY_MAJOR_VERSION < 3
1016-
if (PyInt_Check(val)) {
1017-
mode = PyInt_AS_LONG(val);
1018-
} else
1019-
#endif
1020-
{
1021-
if (PyLong_Check(val)) {
1022-
mode = PyLong_AS_LONG(val);
1023-
} else {
1024-
PyErr_SetString(PyExc_TypeError,
1025-
"The mode attribute must be an integer");
1026-
return -1;
1027-
}
1028-
}
1029-
10301015

1031-
if ( mode > 3 ) {
1032-
PyErr_SetString(PyExc_TypeError,
1033-
"The mode attribute must be an integer"
1034-
"between 0 and 3.");
1035-
return -1;
1036-
}
1016+
mode = PyLong_AS_LONG(val);
10371017

10381018
// clean and set CPHA and CPOL bits
10391019
tmp = ( self->mode & ~(SPI_CPHA | SPI_CPOL) ) | mode ;

spidev/_spi.py

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,40 @@
55

66

77
class SpiDev(_cspi.SpiDev):
8-
def __init__(self, bus: int | None, client: int | None, device: int | None = None):
8+
def __init__(
9+
self,
10+
bus: int | None,
11+
client: int | None,
12+
device: int | None = None,
13+
mode: int | None = None,
14+
):
15+
super().__init__(bus, client)
916
self.bus = bus
1017
self.client = client
1118
self.device = device
12-
super().__init__(bus, client)
19+
if mode is not None:
20+
self.mode = mode
21+
22+
@property
23+
def mode(self) -> int:
24+
"""SPI mode.
25+
26+
A two bit pattern of clock polarity and phase [CPOL|CPHA],
27+
min: 0b00 = 0, max: 0b11 = 3
28+
"""
29+
return super().mode
30+
31+
@mode.setter
32+
def mode(self, value: int) -> None:
33+
try:
34+
v = int(value)
35+
except (TypeError, ValueError):
36+
raise TypeError(f"mode must be an integer, but is {value}")
37+
38+
if not 0 <= v <= 3:
39+
raise ValueError(f"mode must be between 0 and 3, but is {v}")
40+
41+
super().__setattr__("mode", v)
1342

1443
def fileno(self) -> int:
1544
"""Return the file descriptor if it exists.

0 commit comments

Comments
 (0)