or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

components.mdcore-viewer.mdindex.mdlayers.mdqt-interface.mdtypes.mdutilities.md

types.mddocs/

0

# Types

1

2

Napari type definitions provide comprehensive type annotations for arrays, layer data, plugin interfaces, and configuration objects used throughout the napari ecosystem. These types support static analysis, IDE assistance, and runtime validation.

3

4

## Core Data Types

5

6

### Array Types

7

8

Type definitions for array-like objects that napari can work with, supporting multiple array backends.

9

10

```python { .api }

11

ArrayLike = Union[np.ndarray, 'dask.array.Array', 'zarr.Array']

12

"""

13

Union type for array-like objects supported by napari.

14

Includes NumPy arrays, Dask arrays, and Zarr arrays.

15

"""

16

17

ArrayBase = Any

18

"""

19

Base type for array objects. Placeholder for duck-array protocol.

20

"""

21

```

22

23

### Layer Data Types

24

25

Type definitions for different kinds of layer data structures used throughout napari.

26

27

```python { .api }

28

LayerData = Union[tuple[Any], tuple[Any, Mapping], FullLayerData]

29

"""

30

Layer data can be:

31

- (data,) - Just the data array

32

- (data, meta) - Data with metadata dictionary

33

- (data, meta, layer_type) - Complete layer specification

34

"""

35

36

FullLayerData = tuple[Any, Mapping, LayerTypeName]

37

"""

38

Complete layer data tuple containing:

39

- data: The actual data array or structure

40

- meta: Metadata dictionary with layer properties

41

- layer_type: String specifying the layer type

42

"""

43

44

LayerDataTuple = LayerData

45

"""Alias for LayerData tuple types."""

46

47

LayerTypeName = str

48

"""String identifier for layer types (from npe2.types)."""

49

```

50

51

### Specific Layer Data Types

52

53

Type definitions for data structures specific to each layer type.

54

55

```python { .api }

56

ImageData = ArrayLike

57

"""

58

Type for image layer data.

59

N-dimensional arrays representing image data.

60

"""

61

62

LabelsData = ArrayLike

63

"""

64

Type for labels layer data.

65

Integer arrays representing segmentation/label data.

66

"""

67

68

PointsData = ArrayLike

69

"""

70

Type for points layer data.

71

Array of point coordinates (N x D).

72

"""

73

74

ShapesData = list

75

"""

76

Type for shapes layer data.

77

List of shape data arrays defining geometric shapes.

78

"""

79

80

SurfaceData = tuple

81

"""

82

Type for surface layer data.

83

Tuple of (vertices, faces, values) defining 3D mesh.

84

"""

85

86

TracksData = ArrayLike

87

"""

88

Type for tracks layer data.

89

Array with time, track_id, and coordinate information.

90

"""

91

92

VectorsData = ArrayLike

93

"""

94

Type for vectors layer data.

95

Array of vector positions and directions.

96

"""

97

```

98

99

## File and Path Types

100

101

Type definitions for file paths and path-like objects used in I/O operations.

102

103

```python { .api }

104

PathLike = Union[str, Path]

105

"""

106

Type for path-like objects.

107

Accepts both string paths and pathlib.Path objects.

108

"""

109

110

PathOrPaths = Union[PathLike, Sequence[PathLike]]

111

"""

112

Type for single path or sequence of paths.

113

Used in functions that accept multiple file inputs.

114

"""

115

```

116

117

## Plugin Interface Types

118

119

Type definitions for plugin system interfaces and callback functions.

120

121

```python { .api }

122

ReaderFunction = Callable[[PathOrPaths], list[LayerData]]

123

"""

124

Type for plugin reader functions.

125

Takes path(s) and returns list of layer data tuples.

126

"""

127

128

WriterFunction = Callable[[str, list[FullLayerData]], list[str]]

129

"""

130

Type for plugin writer functions.

131

Takes output path and layer data, returns list of written files.

132

"""

133

134

SampleData = Union[PathLike, Callable[..., Iterable[LayerData]]]

135

"""

136

Type for sample data providers.

137

Can be path to data file or function returning layer data.

138

"""

139

140

class SampleDict(TypedDict):

141

"""

142

Typed dictionary for sample data specification.

143

Used in plugin sample data contributions.

144

"""

145

display_name: str

146

data: SampleData

147

```

148

149

## GUI and Widget Types

150

151

Type definitions for GUI components and widget interfaces.

152

153

```python { .api }

154

WidgetCallable = Callable[..., Union['FunctionGui', 'QWidget']]

155

"""

156

Type for widget factory functions.

157

Returns magicgui FunctionGui or Qt QWidget objects.

158

"""

159

160

AugmentedWidget = Union[WidgetCallable, tuple[WidgetCallable, dict]]

161

"""

162

Type for widget specifications with optional configuration.

163

Can be just the widget function or tuple with config dict.

164

"""

165

166

ExcInfo = Union[

167

tuple[type[BaseException], BaseException, TracebackType],

168

tuple[None, None, None]

169

]

170

"""

171

Type for exception information tuples.

172

Standard Python exception info format.

173

"""

174

```

175

176

## Type Conversion Utilities

177

178

Functions for converting between different type representations.

179

180

```python { .api }

181

def image_reader_to_layerdata_reader(func):

182

"""

183

Convert image reader function to layerdata reader function.

184

185

Parameters:

186

- func: Image reader function

187

188

Returns:

189

LayerData reader function

190

"""

191

```

192

193

## Usage Examples

194

195

### Type Annotations in Functions

196

197

```python

198

import napari

199

from napari.types import LayerData, PathLike, ArrayLike

200

from typing import List, Optional

201

import numpy as np

202

203

def process_image_data(data: ArrayLike, name: Optional[str] = None) -> LayerData:

204

"""

205

Process image data and return layer data tuple.

206

207

Parameters:

208

- data: Image array data

209

- name: Optional layer name

210

211

Returns:

212

Layer data tuple

213

"""

214

processed = data * 2 # Simple processing

215

metadata = {'name': name or 'Processed'}

216

return (processed, metadata)

217

218

def load_and_process(path: PathLike) -> List[LayerData]:

219

"""

220

Load image from path and process it.

221

222

Parameters:

223

- path: Path to image file

224

225

Returns:

226

List of layer data tuples

227

"""

228

# Simulate loading (would use actual I/O)

229

data = np.random.random((100, 100))

230

231

# Process the data

232

processed_data = process_image_data(data, name='Loaded Image')

233

234

return [processed_data]

235

236

# Usage with type checking

237

viewer = napari.Viewer()

238

layer_data = load_and_process('example.tif')

239

for data_tuple in layer_data:

240

if len(data_tuple) == 2:

241

data, meta = data_tuple

242

viewer.add_image(data, **meta)

243

```

244

245

### Plugin Type Usage

246

247

```python

248

from napari.types import ReaderFunction, WriterFunction, LayerData, PathOrPaths

249

from typing import List, Optional

250

import numpy as np

251

252

# Reader plugin with proper typing

253

def my_reader(path: PathOrPaths) -> Optional[List[LayerData]]:

254

"""

255

Read custom file format.

256

257

Parameters:

258

- path: File path(s) to read

259

260

Returns:

261

List of layer data or None if cannot read

262

"""

263

if isinstance(path, (list, tuple)):

264

path = path[0] # Take first path

265

266

if not str(path).endswith('.myformat'):

267

return None

268

269

# Simulate reading custom format

270

data = np.random.random((100, 100))

271

metadata = {'name': 'Custom Data', 'colormap': 'viridis'}

272

273

return [(data, metadata)]

274

275

# Writer plugin with proper typing

276

def my_writer(path: str, layer_data: List[LayerData]) -> List[str]:

277

"""

278

Write layers to custom format.

279

280

Parameters:

281

- path: Output file path

282

- layer_data: List of layer data tuples

283

284

Returns:

285

List of written file paths

286

"""

287

written_files = []

288

289

for i, layer_tuple in enumerate(layer_data):

290

if len(layer_tuple) >= 1:

291

data = layer_tuple[0]

292

293

# Simulate writing

294

filename = f"{path}_{i}.myformat"

295

# np.save(filename, data) # Actual saving

296

written_files.append(filename)

297

298

return written_files

299

300

# Register plugins (pseudo-code)

301

# napari_plugin_manager.register_reader(my_reader)

302

# napari_plugin_manager.register_writer(my_writer)

303

```

304

305

### Widget Type Usage

306

307

```python

308

from napari.types import WidgetCallable, AugmentedWidget

309

from magicgui import magic_factory

310

import napari

311

312

# Widget function with proper typing

313

@magic_factory

314

def image_processor(

315

threshold: float = 0.5,

316

invert: bool = False

317

) -> None:

318

"""Process current image layer."""

319

viewer = napari.current_viewer()

320

if viewer and viewer.layers.selected:

321

layer = viewer.layers.selected[0]

322

if hasattr(layer, 'data'):

323

data = layer.data

324

325

# Apply processing

326

processed = data > threshold

327

if invert:

328

processed = ~processed

329

330

# Add result

331

viewer.add_labels(processed.astype(int), name='Processed')

332

333

# Widget specification with configuration

334

widget_config = {

335

'threshold': {'widget_type': 'FloatSlider', 'min': 0, 'max': 1},

336

'invert': {'widget_type': 'CheckBox'}

337

}

338

339

# AugmentedWidget type allows both forms

340

simple_widget: WidgetCallable = image_processor

341

configured_widget: AugmentedWidget = (image_processor, widget_config)

342

```

343

344

### Array Type Usage

345

346

```python

347

from napari.types import ArrayLike, ImageData, LabelsData

348

import numpy as np

349

import dask.array as da

350

351

def create_sample_data() -> tuple[ImageData, LabelsData]:

352

"""

353

Create sample image and labels data.

354

355

Returns:

356

Tuple of (image_data, labels_data)

357

"""

358

# Can be numpy array

359

image_np: ArrayLike = np.random.random((100, 100))

360

361

# Can be dask array

362

image_dask: ArrayLike = da.random.random((100, 100), chunks=(50, 50))

363

364

# Labels data

365

labels: LabelsData = np.zeros((100, 100), dtype=int)

366

labels[25:75, 25:75] = 1

367

368

return image_dask, labels

369

370

# Usage

371

image_data, labels_data = create_sample_data()

372

373

viewer = napari.Viewer()

374

viewer.add_image(image_data, name='Image')

375

viewer.add_labels(labels_data, name='Labels')

376

```

377

378

### Path Type Usage

379

380

```python

381

from napari.types import PathLike, PathOrPaths

382

from pathlib import Path

383

from typing import Union, List

384

385

def process_files(paths: PathOrPaths) -> List[str]:

386

"""

387

Process single file or multiple files.

388

389

Parameters:

390

- paths: Single path or list of paths

391

392

Returns:

393

List of processed file information

394

"""

395

# Normalize to list

396

if isinstance(paths, (str, Path)):

397

path_list = [paths]

398

else:

399

path_list = list(paths)

400

401

results = []

402

for path in path_list:

403

path_obj = Path(path) # Convert to Path object

404

results.append(f"Processed: {path_obj.name}")

405

406

return results

407

408

# Usage examples

409

single_file: PathLike = "data.tif"

410

multiple_files: PathOrPaths = ["data1.tif", "data2.tif", Path("data3.tif")]

411

412

print(process_files(single_file))

413

print(process_files(multiple_files))

414

```