Skip to content

Commit f184d22

Browse files
author
David Miguel Susano Pinto
committed
Use 'from typing import X' to make type annotations less verbose
1 parent e091c6b commit f184d22

File tree

18 files changed

+125
-134
lines changed

18 files changed

+125
-134
lines changed

microscope/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
## along with Microscope. If not, see <http://www.gnu.org/licenses/>.
1919

2020
import enum
21-
import typing
21+
from typing import NamedTuple
2222

2323

2424
class MicroscopeError(Exception):
@@ -127,21 +127,21 @@ class LibraryLoadError(MicroscopeError):
127127
pass
128128

129129

130-
class AxisLimits(typing.NamedTuple):
130+
class AxisLimits(NamedTuple):
131131
"""Limits of a :class:`microscope.abc.StageAxis`."""
132132

133133
lower: float
134134
upper: float
135135

136136

137-
class Binning(typing.NamedTuple):
137+
class Binning(NamedTuple):
138138
"""A tuple containing parameters for horizontal and vertical binning."""
139139

140140
h: int
141141
v: int
142142

143143

144-
class ROI(typing.NamedTuple):
144+
class ROI(NamedTuple):
145145
"""A tuple that defines a region of interest.
146146
147147
This rectangle format completely defines the ROI without reference

microscope/_utils.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,13 @@
2121
import os
2222
import sys
2323
import threading
24-
import typing
24+
from typing import List, Optional, Type
2525

2626
import serial
2727

2828
import microscope
2929
import microscope.abc
3030

31-
3231
# Both pySerial and serial distribution packages install an import
3332
# package named serial. If both are installed we may have imported
3433
# the wrong one. Check it to provide a better error message. See
@@ -47,7 +46,7 @@
4746

4847

4948
def library_loader(
50-
libname: str, dlltype: typing.Type[ctypes.CDLL] = ctypes.CDLL, **kwargs
49+
libname: str, dlltype: Type[ctypes.CDLL] = ctypes.CDLL, **kwargs
5150
) -> ctypes.CDLL:
5251
"""Load shared library.
5352
@@ -156,14 +155,14 @@ def readline(self) -> bytes:
156155
with self._lock:
157156
return self._serial.readline()
158157

159-
def readlines(self, hint: int = -1) -> typing.List[bytes]:
158+
def readlines(self, hint: int = -1) -> List[bytes]:
160159
with self._lock:
161160
return self._serial.readlines(hint)
162161

163162
# Beware: pySerial 3.5 changed the named of its first argument
164163
# from terminator to expected. See issue #233.
165164
def read_until(
166-
self, terminator: bytes = b"\n", size: typing.Optional[int] = None
165+
self, terminator: bytes = b"\n", size: Optional[int] = None
167166
) -> bytes:
168167
with self._lock:
169168
return self._serial.read_until(terminator, size=size)

microscope/abc.py

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -28,16 +28,15 @@
2828
import queue
2929
import threading
3030
import time
31-
import typing
3231
from enum import EnumMeta
3332
from threading import Thread
33+
from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple
3434

3535
import numpy
3636
import Pyro4
3737

3838
import microscope
3939

40-
4140
_logger = logging.getLogger(__name__)
4241

4342

@@ -99,10 +98,10 @@ def __init__(
9998
self,
10099
name: str,
101100
dtype: str,
102-
get_func: typing.Optional[typing.Callable[[], typing.Any]],
103-
set_func: typing.Optional[typing.Callable[[typing.Any], None]] = None,
104-
values: typing.Any = None,
105-
readonly: typing.Optional[typing.Callable[[], bool]] = None,
101+
get_func: Optional[Callable[[], Any]],
102+
set_func: Optional[Callable[[Any], None]] = None,
103+
values: Any = None,
104+
readonly: Optional[Callable[[], bool]] = None,
106105
) -> None:
107106
self.name = name
108107
if dtype not in DTYPES:
@@ -286,7 +285,7 @@ class Device(metaclass=abc.ABCMeta):
286285

287286
def __init__(self) -> None:
288287
self.enabled = False
289-
self._settings: typing.Dict[str, _Setting] = {}
288+
self._settings: Dict[str, _Setting] = {}
290289

291290
def __del__(self) -> None:
292291
self.shutdown()
@@ -402,7 +401,7 @@ def add_setting(
402401
get_func,
403402
set_func,
404403
values,
405-
readonly: typing.Optional[typing.Callable[[], bool]] = None,
404+
readonly: Optional[Callable[[], bool]] = None,
406405
) -> None:
407406
"""Add a setting definition.
408407
@@ -864,7 +863,7 @@ def _process_data(self, data):
864863
}[flips](data)
865864
return super()._process_data(data)
866865

867-
def get_transform(self) -> typing.Tuple[bool, bool, bool]:
866+
def get_transform(self) -> Tuple[bool, bool, bool]:
868867
"""Return the current transform without readout transform."""
869868
return self._client_transform
870869

@@ -879,7 +878,7 @@ def _update_transform(self):
879878
ud = not ud
880879
self._transform = (lr, ud, rot)
881880

882-
def set_transform(self, transform: typing.Tuple[bool, bool, bool]) -> None:
881+
def set_transform(self, transform: Tuple[bool, bool, bool]) -> None:
883882
"""Set client transform and update resultant transform."""
884883
self._client_transform = transform
885884
self._update_transform()
@@ -903,11 +902,11 @@ def get_cycle_time(self) -> float:
903902
pass
904903

905904
@abc.abstractmethod
906-
def _get_sensor_shape(self) -> typing.Tuple[int, int]:
905+
def _get_sensor_shape(self) -> Tuple[int, int]:
907906
"""Return a tuple of `(width, height)` indicating shape in pixels."""
908907
pass
909908

910-
def get_sensor_shape(self) -> typing.Tuple[int, int]:
909+
def get_sensor_shape(self) -> Tuple[int, int]:
911910
"""Return a tuple of `(width, height)` corrected for transform."""
912911
shape = self._get_sensor_shape()
913912
if self._transform[2]:
@@ -1065,7 +1064,7 @@ class DeformableMirror(TriggerTargetMixin, Device, metaclass=abc.ABCMeta):
10651064
@abc.abstractmethod
10661065
def __init__(self, **kwargs) -> None:
10671066
super().__init__(**kwargs)
1068-
self._patterns: typing.Optional[numpy.ndarray] = None
1067+
self._patterns: Optional[numpy.ndarray] = None
10691068
self._pattern_idx: int = -1
10701069

10711070
@property
@@ -1193,7 +1192,7 @@ def __init__(self, **kwargs):
11931192
self._set_point = 0.0
11941193

11951194
@abc.abstractmethod
1196-
def get_status(self) -> typing.List[str]:
1195+
def get_status(self) -> List[str]:
11971196
"""Query and return the light source status."""
11981197
result = []
11991198
return result
@@ -1319,7 +1318,7 @@ class Controller(Device, metaclass=abc.ABCMeta):
13191318

13201319
@property
13211320
@abc.abstractmethod
1322-
def devices(self) -> typing.Mapping[str, Device]:
1321+
def devices(self) -> Mapping[str, Device]:
13231322
"""Map of names to the controlled devices."""
13241323
raise NotImplementedError()
13251324

@@ -1432,7 +1431,7 @@ class documentation for hardware specific details.
14321431

14331432
@property
14341433
@abc.abstractmethod
1435-
def axes(self) -> typing.Mapping[str, StageAxis]:
1434+
def axes(self) -> Mapping[str, StageAxis]:
14361435
"""Map of axis names to the corresponding :class:`StageAxis`.
14371436
14381437
.. code-block:: python
@@ -1475,7 +1474,7 @@ def may_move_on_enable(self) -> bool:
14751474
raise NotImplementedError()
14761475

14771476
@property
1478-
def position(self) -> typing.Mapping[str, float]:
1477+
def position(self) -> Mapping[str, float]:
14791478
"""Map of axis name to their current position.
14801479
14811480
.. code-block:: python
@@ -1490,7 +1489,7 @@ def position(self) -> typing.Mapping[str, float]:
14901489
return {name: axis.position for name, axis in self.axes.items()}
14911490

14921491
@property
1493-
def limits(self) -> typing.Mapping[str, microscope.AxisLimits]:
1492+
def limits(self) -> Mapping[str, microscope.AxisLimits]:
14941493
"""Map of axis name to its upper and lower limits.
14951494
14961495
.. code-block:: python
@@ -1510,7 +1509,7 @@ def limits(self) -> typing.Mapping[str, microscope.AxisLimits]:
15101509
return {name: axis.limits for name, axis in self.axes.items()}
15111510

15121511
@abc.abstractmethod
1513-
def move_by(self, delta: typing.Mapping[str, float]) -> None:
1512+
def move_by(self, delta: Mapping[str, float]) -> None:
15141513
"""Move axes by the corresponding amounts.
15151514
15161515
Args:
@@ -1536,7 +1535,7 @@ def move_by(self, delta: typing.Mapping[str, float]) -> None:
15361535
raise NotImplementedError()
15371536

15381537
@abc.abstractmethod
1539-
def move_to(self, position: typing.Mapping[str, float]) -> None:
1538+
def move_to(self, position: Mapping[str, float]) -> None:
15401539
"""Move axes to the corresponding positions.
15411540
15421541
Args:

microscope/cameras/hamamatsu.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
import math
4646
import sys
4747
import threading
48-
import typing
48+
from typing import Callable, Dict, List, Optional, Tuple, Type
4949

5050
import numpy as np
5151

@@ -134,7 +134,7 @@ def _status_to_error(status: int) -> str:
134134
return "{}[{:#010x}]".format(name, status & 0x8FFFFFFF)
135135

136136

137-
def _call(f: typing.Callable[..., int], *args) -> None:
137+
def _call(f: Callable[..., int], *args) -> None:
138138
"""Call a C function from dcamapi4.
139139
140140
This is an helper function for the most typical case of checking
@@ -150,15 +150,15 @@ def _call(f: typing.Callable[..., int], *args) -> None:
150150

151151

152152
def _create_struct_with_size(
153-
stype: typing.Type[ctypes.Structure],
153+
stype: Type[ctypes.Structure],
154154
) -> ctypes.Structure:
155155
s = stype()
156156
s.size = ctypes.sizeof(stype)
157157
return s
158158

159159

160160
def _create_struct_with_cbSize(
161-
stype: typing.Type[ctypes.Structure],
161+
stype: Type[ctypes.Structure],
162162
) -> ctypes.Structure:
163163
s = stype()
164164
s.cbSize = ctypes.sizeof(stype)
@@ -167,7 +167,7 @@ def _create_struct_with_cbSize(
167167

168168
def _create_devstring_with_length(
169169
nbytes: int,
170-
) -> typing.Tuple[dcam.DEV_STRING, ctypes.c_char]:
170+
) -> Tuple[dcam.DEV_STRING, ctypes.c_char]:
171171
# FIXME: the type annotation is not quite right, we actually
172172
# return a ctypes array of c_char as the second value.
173173
devstr = _create_struct_with_size(dcam.DEV_STRING)
@@ -498,14 +498,14 @@ def _init_method_add_all_properties(self) -> None:
498498

499499
def _init_method_get_prop_values(
500500
self, prop_attr: dcam.PROP_ATTR
501-
) -> typing.Dict[int, str]:
501+
) -> Dict[int, str]:
502502
strbuf = ctypes.create_string_buffer(64)
503503
vtxt = _create_struct_with_cbSize(dcam.PROP_VALUETEXT)
504504
vtxt.iProp = prop_attr.iProp
505505
vtxt.text = ctypes.cast(ctypes.pointer(strbuf), ctypes.c_char_p)
506506
vtxt.textbytes = ctypes.sizeof(strbuf)
507507

508-
val2txt: typing.Dict[int, str] = {}
508+
val2txt: Dict[int, str] = {}
509509
next_value = ctypes.c_double(prop_attr.valuemin)
510510
while next_value.value <= prop_attr.valuemax:
511511
vtxt.value = next_value.value
@@ -681,7 +681,7 @@ def set_exposure_time(self, seconds: float) -> None:
681681
def get_cycle_time(self) -> float:
682682
return self._get_real_property(dcam.IDPROP.TIMING_MINTRIGGERINTERVAL)
683683

684-
def _get_sensor_shape(self) -> typing.Tuple[int, int]:
684+
def _get_sensor_shape(self) -> Tuple[int, int]:
685685
return self._sensor_shape
686686

687687
def _get_binning(self) -> microscope.Binning:
@@ -733,7 +733,7 @@ def _get_roi(self) -> microscope.ROI:
733733
def _set_roi(self, roi: microscope.ROI) -> None:
734734
pass
735735

736-
def _fetch_data(self) -> typing.Optional[np.ndarray]:
736+
def _fetch_data(self) -> Optional[np.ndarray]:
737737
_logger.debug("Start waiting for FRAMEREADY")
738738
status = dcam.wait_start(
739739
self._wait_open.hwait, ctypes.byref(self._wait_start)
@@ -766,7 +766,7 @@ def _do_trigger(self) -> None:
766766

767767
def _get_trigger_combo(
768768
self,
769-
) -> typing.Tuple[microscope.TriggerType, microscope.TriggerMode]:
769+
) -> Tuple[microscope.TriggerType, microscope.TriggerMode]:
770770
source = self._get_long_property(dcam.IDPROP.TRIGGERSOURCE)
771771
if source == dcam.PROPMODEVALUE.TRIGGERSOURCE__SOFTWARE:
772772
return (
@@ -858,8 +858,8 @@ def _list_devices() -> None:
858858
"""Print all available Hamamatsu devices and some of their info."""
859859
api = _DCAM_API()
860860

861-
models: typing.List[str] = []
862-
cids: typing.List[str] = []
861+
models: List[str] = []
862+
cids: List[str] = []
863863

864864
devstr, devstrbuf = _create_devstring_with_length(64)
865865
for i in range(api.n_devices):
@@ -906,10 +906,10 @@ def _list_properties(index: int) -> None:
906906
hdcam = sopen.hdcam
907907

908908
# Collect all the strings to pretty print later.
909-
ids: typing.List[str] = []
910-
names: typing.List[str] = []
911-
rws: typing.List[str] = []
912-
values: typing.List[str] = []
909+
ids: List[str] = []
910+
names: List[str] = []
911+
rws: List[str] = []
912+
values: List[str] = []
913913

914914
# There is no property with ID zero, it is reserved, so we start
915915
# at ID zero and loop to the next until there is no next property.
@@ -1007,7 +1007,7 @@ def _list_properties(index: int) -> None:
10071007
_logger.warning("failed to close device during shutdown")
10081008

10091009

1010-
def _main(argv: typing.List[str]) -> int:
1010+
def _main(argv: List[str]) -> int:
10111011
prog_name = "microscope.cameras.hamamatsu"
10121012
parser = argparse.ArgumentParser(prog=prog_name)
10131013
subparsers = parser.add_subparsers(

microscope/cameras/ximea.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@
5959
import contextlib
6060
import enum
6161
import logging
62-
import typing
62+
from typing import Optional, Tuple
6363

6464
import numpy as np
6565
from ximea import xiapi
@@ -183,9 +183,7 @@ class XimeaCamera(microscope.abc.Camera):
183183
184184
"""
185185

186-
def __init__(
187-
self, serial_number: typing.Optional[str] = None, **kwargs
188-
) -> None:
186+
def __init__(self, serial_number: Optional[str] = None, **kwargs) -> None:
189187
super().__init__(**kwargs)
190188
self._acquiring = False
191189
self._handle = xiapi.Camera()
@@ -216,7 +214,7 @@ def _trigger_source_setter(index: int) -> None:
216214

217215
self.initialize()
218216

219-
def _fetch_data(self) -> typing.Optional[np.ndarray]:
217+
def _fetch_data(self) -> Optional[np.ndarray]:
220218
if not self._acquiring:
221219
return None
222220

@@ -359,7 +357,7 @@ def get_exposure_time(self) -> float:
359357
def get_cycle_time(self):
360358
return 1.0 / self._handle.get_framerate()
361359

362-
def _get_sensor_shape(self) -> typing.Tuple[int, int]:
360+
def _get_sensor_shape(self) -> Tuple[int, int]:
363361
return self._sensor_shape
364362

365363
def soft_trigger(self) -> None:

0 commit comments

Comments
 (0)