CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-napari

n-dimensional array viewer in Python with fast, interactive multi-dimensional image visualization

Pending
Overview
Eval results
Files

types.mddocs/

Types

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.

Core Data Types

Array Types

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

ArrayLike = Union[np.ndarray, 'dask.array.Array', 'zarr.Array']
"""
Union type for array-like objects supported by napari.
Includes NumPy arrays, Dask arrays, and Zarr arrays.
"""

ArrayBase = Any
"""
Base type for array objects. Placeholder for duck-array protocol.
"""

Layer Data Types

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

LayerData = Union[tuple[Any], tuple[Any, Mapping], FullLayerData]
"""
Layer data can be:
- (data,) - Just the data array
- (data, meta) - Data with metadata dictionary  
- (data, meta, layer_type) - Complete layer specification
"""

FullLayerData = tuple[Any, Mapping, LayerTypeName]
"""
Complete layer data tuple containing:
- data: The actual data array or structure
- meta: Metadata dictionary with layer properties
- layer_type: String specifying the layer type
"""

LayerDataTuple = LayerData
"""Alias for LayerData tuple types."""

LayerTypeName = str
"""String identifier for layer types (from npe2.types)."""

Specific Layer Data Types

Type definitions for data structures specific to each layer type.

ImageData = ArrayLike
"""
Type for image layer data.
N-dimensional arrays representing image data.
"""

LabelsData = ArrayLike  
"""
Type for labels layer data.
Integer arrays representing segmentation/label data.
"""

PointsData = ArrayLike
"""
Type for points layer data.
Array of point coordinates (N x D).
"""

ShapesData = list
"""
Type for shapes layer data.
List of shape data arrays defining geometric shapes.
"""

SurfaceData = tuple
"""
Type for surface layer data.
Tuple of (vertices, faces, values) defining 3D mesh.
"""

TracksData = ArrayLike
"""
Type for tracks layer data.
Array with time, track_id, and coordinate information.
"""

VectorsData = ArrayLike
"""
Type for vectors layer data.
Array of vector positions and directions.
"""

File and Path Types

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

PathLike = Union[str, Path]
"""
Type for path-like objects.
Accepts both string paths and pathlib.Path objects.
"""

PathOrPaths = Union[PathLike, Sequence[PathLike]]
"""
Type for single path or sequence of paths.
Used in functions that accept multiple file inputs.
"""

Plugin Interface Types

Type definitions for plugin system interfaces and callback functions.

ReaderFunction = Callable[[PathOrPaths], list[LayerData]]
"""
Type for plugin reader functions.
Takes path(s) and returns list of layer data tuples.
"""

WriterFunction = Callable[[str, list[FullLayerData]], list[str]]
"""
Type for plugin writer functions.
Takes output path and layer data, returns list of written files.
"""

SampleData = Union[PathLike, Callable[..., Iterable[LayerData]]]
"""
Type for sample data providers.
Can be path to data file or function returning layer data.
"""

class SampleDict(TypedDict):
    """
    Typed dictionary for sample data specification.
    Used in plugin sample data contributions.
    """
    display_name: str
    data: SampleData

GUI and Widget Types

Type definitions for GUI components and widget interfaces.

WidgetCallable = Callable[..., Union['FunctionGui', 'QWidget']]
"""
Type for widget factory functions.
Returns magicgui FunctionGui or Qt QWidget objects.
"""

AugmentedWidget = Union[WidgetCallable, tuple[WidgetCallable, dict]]
"""
Type for widget specifications with optional configuration.
Can be just the widget function or tuple with config dict.
"""

ExcInfo = Union[
    tuple[type[BaseException], BaseException, TracebackType],
    tuple[None, None, None]
]
"""
Type for exception information tuples.
Standard Python exception info format.
"""

Type Conversion Utilities

Functions for converting between different type representations.

def image_reader_to_layerdata_reader(func):
    """
    Convert image reader function to layerdata reader function.
    
    Parameters:
    - func: Image reader function
    
    Returns:
    LayerData reader function
    """

Usage Examples

Type Annotations in Functions

import napari
from napari.types import LayerData, PathLike, ArrayLike
from typing import List, Optional
import numpy as np

def process_image_data(data: ArrayLike, name: Optional[str] = None) -> LayerData:
    """
    Process image data and return layer data tuple.
    
    Parameters:
    - data: Image array data
    - name: Optional layer name
    
    Returns:
    Layer data tuple
    """
    processed = data * 2  # Simple processing
    metadata = {'name': name or 'Processed'}
    return (processed, metadata)

def load_and_process(path: PathLike) -> List[LayerData]:
    """
    Load image from path and process it.
    
    Parameters:
    - path: Path to image file
    
    Returns:
    List of layer data tuples
    """
    # Simulate loading (would use actual I/O)
    data = np.random.random((100, 100))
    
    # Process the data
    processed_data = process_image_data(data, name='Loaded Image')
    
    return [processed_data]

# Usage with type checking
viewer = napari.Viewer()
layer_data = load_and_process('example.tif')
for data_tuple in layer_data:
    if len(data_tuple) == 2:
        data, meta = data_tuple
        viewer.add_image(data, **meta)

Plugin Type Usage

from napari.types import ReaderFunction, WriterFunction, LayerData, PathOrPaths
from typing import List, Optional
import numpy as np

# Reader plugin with proper typing
def my_reader(path: PathOrPaths) -> Optional[List[LayerData]]:
    """
    Read custom file format.
    
    Parameters:
    - path: File path(s) to read
    
    Returns:
    List of layer data or None if cannot read
    """
    if isinstance(path, (list, tuple)):
        path = path[0]  # Take first path
    
    if not str(path).endswith('.myformat'):
        return None
    
    # Simulate reading custom format
    data = np.random.random((100, 100))
    metadata = {'name': 'Custom Data', 'colormap': 'viridis'}
    
    return [(data, metadata)]

# Writer plugin with proper typing
def my_writer(path: str, layer_data: List[LayerData]) -> List[str]:
    """
    Write layers to custom format.
    
    Parameters:
    - path: Output file path
    - layer_data: List of layer data tuples
    
    Returns:
    List of written file paths
    """
    written_files = []
    
    for i, layer_tuple in enumerate(layer_data):
        if len(layer_tuple) >= 1:
            data = layer_tuple[0]
            
            # Simulate writing
            filename = f"{path}_{i}.myformat"
            # np.save(filename, data)  # Actual saving
            written_files.append(filename)
    
    return written_files

# Register plugins (pseudo-code)
# napari_plugin_manager.register_reader(my_reader)
# napari_plugin_manager.register_writer(my_writer)

Widget Type Usage

from napari.types import WidgetCallable, AugmentedWidget
from magicgui import magic_factory
import napari

# Widget function with proper typing
@magic_factory
def image_processor(
    threshold: float = 0.5,
    invert: bool = False
) -> None:
    """Process current image layer."""
    viewer = napari.current_viewer()
    if viewer and viewer.layers.selected:
        layer = viewer.layers.selected[0]
        if hasattr(layer, 'data'):
            data = layer.data
            
            # Apply processing
            processed = data > threshold
            if invert:
                processed = ~processed
            
            # Add result
            viewer.add_labels(processed.astype(int), name='Processed')

# Widget specification with configuration
widget_config = {
    'threshold': {'widget_type': 'FloatSlider', 'min': 0, 'max': 1},
    'invert': {'widget_type': 'CheckBox'}
}

# AugmentedWidget type allows both forms
simple_widget: WidgetCallable = image_processor
configured_widget: AugmentedWidget = (image_processor, widget_config)

Array Type Usage

from napari.types import ArrayLike, ImageData, LabelsData
import numpy as np
import dask.array as da

def create_sample_data() -> tuple[ImageData, LabelsData]:
    """
    Create sample image and labels data.
    
    Returns:
    Tuple of (image_data, labels_data)
    """
    # Can be numpy array
    image_np: ArrayLike = np.random.random((100, 100))
    
    # Can be dask array  
    image_dask: ArrayLike = da.random.random((100, 100), chunks=(50, 50))
    
    # Labels data
    labels: LabelsData = np.zeros((100, 100), dtype=int)
    labels[25:75, 25:75] = 1
    
    return image_dask, labels

# Usage
image_data, labels_data = create_sample_data()

viewer = napari.Viewer()
viewer.add_image(image_data, name='Image')
viewer.add_labels(labels_data, name='Labels')

Path Type Usage

from napari.types import PathLike, PathOrPaths
from pathlib import Path
from typing import Union, List

def process_files(paths: PathOrPaths) -> List[str]:
    """
    Process single file or multiple files.
    
    Parameters:
    - paths: Single path or list of paths
    
    Returns:
    List of processed file information
    """
    # Normalize to list
    if isinstance(paths, (str, Path)):
        path_list = [paths]
    else:
        path_list = list(paths)
    
    results = []
    for path in path_list:
        path_obj = Path(path)  # Convert to Path object
        results.append(f"Processed: {path_obj.name}")
    
    return results

# Usage examples
single_file: PathLike = "data.tif"
multiple_files: PathOrPaths = ["data1.tif", "data2.tif", Path("data3.tif")]

print(process_files(single_file))
print(process_files(multiple_files))

Install with Tessl CLI

npx tessl i tessl/pypi-napari

docs

components.md

core-viewer.md

index.md

layers.md

qt-interface.md

types.md

utilities.md

tile.json