Skip to content

API Reference

Attributes

__version__ module-attribute

__version__ = _read_version()

Classes

Hostlist dataclass

Slurm‑style hostlist handling.

Source code in src/hostlist/core.py
@dataclass(frozen=True)
class Hostlist:
    """Slurm‑style hostlist handling."""
    hosts: tuple[str, ...]

    # ------------------------------------------------------------------
    # Construction helpers
    # ------------------------------------------------------------------
    @classmethod
    def expand(cls, spec: str) -> "Hostlist":
        """Parse a possibly‑compressed hostlist string."""
        if not spec:
            return cls(())

        # split on commas that are **outside** brackets
        parts, buf, depth = [], "", 0
        for ch in spec:
            if ch == "[":
                depth += 1
            elif ch == "]":
                depth -= 1
                if depth < 0:
                    raise ValueError("Unexpected closing bracket ']' in hostlist")
            if ch == "," and depth == 0:
                parts.append(buf)
                buf = ""
            else:
                buf += ch

        if depth != 0:
            raise ValueError("Unclosed bracket '[' in hostlist")

        if buf:
            parts.append(buf)

        expanded: list[str] = []
        for token in parts:
            token = token.strip()
            if not token:
                continue
            m = re.fullmatch(
                r"(?P<prefix>[\w-]+)\[(?P<body>[^\]]*)\](?P<suffix>.*)", token
            )
            if not m:               # plain host (no brackets)
                expanded.append(token)
                continue

            prefix, body, suffix = m.group("prefix"), m.group("body"), m.group("suffix")

            # Determine zero‑padding width from the first numeric token
            pad = 0
            for sub in body.split(","):
                sub = sub.strip()
                if not sub: continue
                start = sub.split("-", 1)[0] if "-" in sub else sub
                if start.lstrip("0") != start:          # leading zeros present
                    pad = max(pad, len(start))

            try:
                for num in _expand_range(body):
                    expanded.append(f"{prefix}{str(num).zfill(pad)}{suffix}")
            except ValueError as e:
                raise ValueError(f"Invalid range in bracket for {token!r}: {e}")

        # Normalise ordering (numeric order per prefix/suffix)
        expanded.sort(key=_sort_key)
        return cls(tuple(expanded))

    @classmethod
    def from_list(cls, hosts: Iterable[str]) -> "Hostlist":
        """Create a Hostlist from an already‑expanded iterable."""
        # Convert to set to remove duplicates, then sort and tuple
        sorted_hosts = sorted(set(hosts), key=_sort_key)
        return cls(tuple(sorted_hosts))


    # ------------------------------------------------------------------
    # Formatting
    # ------------------------------------------------------------------
    def compact(self, compress: bool = True) -> str:
        """Return a comma‑separated hostlist; optionally compress it."""
        if not self.hosts:
            return ""
        if not compress:
            return ",".join(self.hosts)

        groups = _group_by_prefix(self.hosts)
        parts = []
        for (prefix, suffix) in sorted(groups.keys()):
            nums = groups[(prefix, suffix)]

            numeric = sorted([n for n in nums if n is not None])

            if not numeric:
                # Just a literal host
                parts.append(f"{prefix}{suffix}")
                continue

            # Infer padding width from the first numeric occurrence of this prefix/suffix
            first_host = next(h for h in self.hosts if h.startswith(prefix) and h.endswith(suffix) and any(c.isdigit() for c in h))
            num_match = re.search(rf"{re.escape(prefix)}(?P<num>\d+){re.escape(suffix)}", first_host)
            pad = len(num_match.group("num")) if num_match else 0

            parts.append(f"{prefix}[{_compress_numbers(numeric, pad)}]{suffix}")

        return ",".join(parts)

    # ------------------------------------------------------------------
    # Set‑like operations (return new Hostlist instances)
    # ------------------------------------------------------------------
    def _as_set(self) -> set[str]:
        return set(self.hosts)

    def diff(self, *others: Union["Hostlist", str, list[str]]) -> "Hostlist":
        """self – union(others)"""
        base = self._as_set()
        for o in others:
            base.difference_update(_coerce(o)._as_set())
        return Hostlist.from_list(sorted(base, key=lambda h: _parse_node(h)))

    def intersect(self, *others: Union["Hostlist", str, list[str]]) -> "Hostlist":
        base = self._as_set()
        for o in others:
            base.intersection_update(_coerce(o)._as_set())
        return Hostlist.from_list(sorted(base, key=lambda h: _parse_node(h)))

    def union(self, *others: Union["Hostlist", str, list[str]]) -> "Hostlist":
        base = self._as_set()
        for o in others:
            base.update(_coerce(o)._as_set())
        return Hostlist.from_list(sorted(base, key=lambda h: _parse_node(h)))

    def xor(self, *others: Union["Hostlist", str, list[str]]) -> "Hostlist":
        base = self._as_set()
        for o in others:
            base.symmetric_difference_update(_coerce(o)._as_set())
        return Hostlist.from_list(sorted(base, key=lambda h: _parse_node(h)))

    # ------------------------------------------------------------------
    # Collection API (Magic Methods)
    # ------------------------------------------------------------------
    def __len__(self) -> int:
        return len(self.hosts)

    def __iter__(self):
        return iter(self.hosts)

    def __contains__(self, item: object) -> bool:
        return item in self.hosts

    def __getitem__(self, index: Union[int, slice]) -> Union[str, "Hostlist"]:
        """Supports 0-based indexing and slicing."""
        if isinstance(index, slice):
            return Hostlist.from_list(self.hosts[index])
        return self.hosts[index]

    def __repr__(self) -> str:
        return f"Hostlist({self.hosts!r})"

    # ------------------------------------------------------------------
    # Set Operators
    # ------------------------------------------------------------------
    def __and__(self, other: Union["Hostlist", str, list[str]]) -> "Hostlist":
        return self.intersect(other)

    def __or__(self, other: Union["Hostlist", str, list[str]]) -> "Hostlist":
        return self.union(other)

    def __sub__(self, other: Union["Hostlist", str, list[str]]) -> "Hostlist":
        return self.diff(other)

    def __xor__(self, other: Union["Hostlist", str, list[str]]) -> "Hostlist":
        return self.xor(other)

    # ------------------------------------------------------------------
    # Misc helpers
    # ------------------------------------------------------------------
    def nth(self, n: int) -> str:
        """Return the n‑th host (1‑based)."""
        if n < 1 or n > len(self):
            raise ValueError("index out of range")
        return self[n - 1]

    def find(self, host: str) -> int:
        """Return 1‑based position of *host*."""
        try:
            return self.hosts.index(host) + 1
        except ValueError:
            raise ValueError("host not found") from None

    def count(self) -> int:
        """Backward compatible with __len__."""
        return len(self)

    def remove(self, host: str) -> "Hostlist":
        """Return a new Hostlist without *host*."""
        if host not in self:
            raise ValueError("host not found")
        new = [h for h in self.hosts if h != host]
        return Hostlist.from_list(new)

    def delimiter(self, d: str) -> str:
        """Join the list with a custom delimiter (no compression)."""
        return d.join(self.hosts)

    def size(self, N: int) -> "Hostlist":
        """Return at most N hosts (negative → last N)."""
        return Hostlist.from_list(self.hosts[:N] if N >= 0 else self.hosts[N:])

    def exclude(self, *hosts: str) -> "Hostlist":
        """Return a Hostlist without the supplied hosts."""
        remaining = [h for h in self.hosts if h not in hosts]
        if not remaining:
            raise ValueError("resulting hostlist empty")
        return Hostlist.from_list(remaining)

    def quiet(self) -> str:
        """Plain comma‑separated list; raise if empty."""
        if not self.hosts:
            raise ValueError("hostlist empty")
        return ",".join(self.hosts)

    def format(self, template: str) -> list[str]:
        """
        Return a list of formatted strings using the provided template.
        The template should contain a {host} placeholder.
        """
        return [template.format(host=h) for h in self.hosts]

Methods:

__getitem__
__getitem__(index)

Supports 0-based indexing and slicing.

Source code in src/hostlist/core.py
def __getitem__(self, index: Union[int, slice]) -> Union[str, "Hostlist"]:
    """Supports 0-based indexing and slicing."""
    if isinstance(index, slice):
        return Hostlist.from_list(self.hosts[index])
    return self.hosts[index]
compact
compact(compress=True)

Return a comma‑separated hostlist; optionally compress it.

Source code in src/hostlist/core.py
def compact(self, compress: bool = True) -> str:
    """Return a comma‑separated hostlist; optionally compress it."""
    if not self.hosts:
        return ""
    if not compress:
        return ",".join(self.hosts)

    groups = _group_by_prefix(self.hosts)
    parts = []
    for (prefix, suffix) in sorted(groups.keys()):
        nums = groups[(prefix, suffix)]

        numeric = sorted([n for n in nums if n is not None])

        if not numeric:
            # Just a literal host
            parts.append(f"{prefix}{suffix}")
            continue

        # Infer padding width from the first numeric occurrence of this prefix/suffix
        first_host = next(h for h in self.hosts if h.startswith(prefix) and h.endswith(suffix) and any(c.isdigit() for c in h))
        num_match = re.search(rf"{re.escape(prefix)}(?P<num>\d+){re.escape(suffix)}", first_host)
        pad = len(num_match.group("num")) if num_match else 0

        parts.append(f"{prefix}[{_compress_numbers(numeric, pad)}]{suffix}")

    return ",".join(parts)
count
count()

Backward compatible with len.

Source code in src/hostlist/core.py
def count(self) -> int:
    """Backward compatible with __len__."""
    return len(self)
delimiter
delimiter(d)

Join the list with a custom delimiter (no compression).

Source code in src/hostlist/core.py
def delimiter(self, d: str) -> str:
    """Join the list with a custom delimiter (no compression)."""
    return d.join(self.hosts)
diff
diff(*others)

self – union(others)

Source code in src/hostlist/core.py
def diff(self, *others: Union["Hostlist", str, list[str]]) -> "Hostlist":
    """self – union(others)"""
    base = self._as_set()
    for o in others:
        base.difference_update(_coerce(o)._as_set())
    return Hostlist.from_list(sorted(base, key=lambda h: _parse_node(h)))
exclude
exclude(*hosts)

Return a Hostlist without the supplied hosts.

Source code in src/hostlist/core.py
def exclude(self, *hosts: str) -> "Hostlist":
    """Return a Hostlist without the supplied hosts."""
    remaining = [h for h in self.hosts if h not in hosts]
    if not remaining:
        raise ValueError("resulting hostlist empty")
    return Hostlist.from_list(remaining)
expand classmethod
expand(spec)

Parse a possibly‑compressed hostlist string.

Source code in src/hostlist/core.py
@classmethod
def expand(cls, spec: str) -> "Hostlist":
    """Parse a possibly‑compressed hostlist string."""
    if not spec:
        return cls(())

    # split on commas that are **outside** brackets
    parts, buf, depth = [], "", 0
    for ch in spec:
        if ch == "[":
            depth += 1
        elif ch == "]":
            depth -= 1
            if depth < 0:
                raise ValueError("Unexpected closing bracket ']' in hostlist")
        if ch == "," and depth == 0:
            parts.append(buf)
            buf = ""
        else:
            buf += ch

    if depth != 0:
        raise ValueError("Unclosed bracket '[' in hostlist")

    if buf:
        parts.append(buf)

    expanded: list[str] = []
    for token in parts:
        token = token.strip()
        if not token:
            continue
        m = re.fullmatch(
            r"(?P<prefix>[\w-]+)\[(?P<body>[^\]]*)\](?P<suffix>.*)", token
        )
        if not m:               # plain host (no brackets)
            expanded.append(token)
            continue

        prefix, body, suffix = m.group("prefix"), m.group("body"), m.group("suffix")

        # Determine zero‑padding width from the first numeric token
        pad = 0
        for sub in body.split(","):
            sub = sub.strip()
            if not sub: continue
            start = sub.split("-", 1)[0] if "-" in sub else sub
            if start.lstrip("0") != start:          # leading zeros present
                pad = max(pad, len(start))

        try:
            for num in _expand_range(body):
                expanded.append(f"{prefix}{str(num).zfill(pad)}{suffix}")
        except ValueError as e:
            raise ValueError(f"Invalid range in bracket for {token!r}: {e}")

    # Normalise ordering (numeric order per prefix/suffix)
    expanded.sort(key=_sort_key)
    return cls(tuple(expanded))
find
find(host)

Return 1‑based position of host.

Source code in src/hostlist/core.py
def find(self, host: str) -> int:
    """Return 1‑based position of *host*."""
    try:
        return self.hosts.index(host) + 1
    except ValueError:
        raise ValueError("host not found") from None
format
format(template)

Return a list of formatted strings using the provided template. The template should contain a {host} placeholder.

Source code in src/hostlist/core.py
def format(self, template: str) -> list[str]:
    """
    Return a list of formatted strings using the provided template.
    The template should contain a {host} placeholder.
    """
    return [template.format(host=h) for h in self.hosts]
from_list classmethod
from_list(hosts)

Create a Hostlist from an already‑expanded iterable.

Source code in src/hostlist/core.py
@classmethod
def from_list(cls, hosts: Iterable[str]) -> "Hostlist":
    """Create a Hostlist from an already‑expanded iterable."""
    # Convert to set to remove duplicates, then sort and tuple
    sorted_hosts = sorted(set(hosts), key=_sort_key)
    return cls(tuple(sorted_hosts))
nth
nth(n)

Return the n‑th host (1‑based).

Source code in src/hostlist/core.py
def nth(self, n: int) -> str:
    """Return the n‑th host (1‑based)."""
    if n < 1 or n > len(self):
        raise ValueError("index out of range")
    return self[n - 1]
quiet
quiet()

Plain comma‑separated list; raise if empty.

Source code in src/hostlist/core.py
def quiet(self) -> str:
    """Plain comma‑separated list; raise if empty."""
    if not self.hosts:
        raise ValueError("hostlist empty")
    return ",".join(self.hosts)
remove
remove(host)

Return a new Hostlist without host.

Source code in src/hostlist/core.py
def remove(self, host: str) -> "Hostlist":
    """Return a new Hostlist without *host*."""
    if host not in self:
        raise ValueError("host not found")
    new = [h for h in self.hosts if h != host]
    return Hostlist.from_list(new)
size
size(N)

Return at most N hosts (negative → last N).

Source code in src/hostlist/core.py
def size(self, N: int) -> "Hostlist":
    """Return at most N hosts (negative → last N)."""
    return Hostlist.from_list(self.hosts[:N] if N >= 0 else self.hosts[N:])

Functions:

_read_version

_read_version()
Source code in src/hostlist/__init__.py
def _read_version():
    try:
        # The VERSION file is in the project root, 2 levels up from this file
        version_file = os.path.join(os.path.dirname(__file__), '..', '..', 'VERSION')
        with open(version_file, 'r') as f:
            return f.read().strip()
    except FileNotFoundError:
        return "0.0.0"

Modules

cli

Classes

core

Classes

Hostlist dataclass

Slurm‑style hostlist handling.

Source code in src/hostlist/core.py
@dataclass(frozen=True)
class Hostlist:
    """Slurm‑style hostlist handling."""
    hosts: tuple[str, ...]

    # ------------------------------------------------------------------
    # Construction helpers
    # ------------------------------------------------------------------
    @classmethod
    def expand(cls, spec: str) -> "Hostlist":
        """Parse a possibly‑compressed hostlist string."""
        if not spec:
            return cls(())

        # split on commas that are **outside** brackets
        parts, buf, depth = [], "", 0
        for ch in spec:
            if ch == "[":
                depth += 1
            elif ch == "]":
                depth -= 1
                if depth < 0:
                    raise ValueError("Unexpected closing bracket ']' in hostlist")
            if ch == "," and depth == 0:
                parts.append(buf)
                buf = ""
            else:
                buf += ch

        if depth != 0:
            raise ValueError("Unclosed bracket '[' in hostlist")

        if buf:
            parts.append(buf)

        expanded: list[str] = []
        for token in parts:
            token = token.strip()
            if not token:
                continue
            m = re.fullmatch(
                r"(?P<prefix>[\w-]+)\[(?P<body>[^\]]*)\](?P<suffix>.*)", token
            )
            if not m:               # plain host (no brackets)
                expanded.append(token)
                continue

            prefix, body, suffix = m.group("prefix"), m.group("body"), m.group("suffix")

            # Determine zero‑padding width from the first numeric token
            pad = 0
            for sub in body.split(","):
                sub = sub.strip()
                if not sub: continue
                start = sub.split("-", 1)[0] if "-" in sub else sub
                if start.lstrip("0") != start:          # leading zeros present
                    pad = max(pad, len(start))

            try:
                for num in _expand_range(body):
                    expanded.append(f"{prefix}{str(num).zfill(pad)}{suffix}")
            except ValueError as e:
                raise ValueError(f"Invalid range in bracket for {token!r}: {e}")

        # Normalise ordering (numeric order per prefix/suffix)
        expanded.sort(key=_sort_key)
        return cls(tuple(expanded))

    @classmethod
    def from_list(cls, hosts: Iterable[str]) -> "Hostlist":
        """Create a Hostlist from an already‑expanded iterable."""
        # Convert to set to remove duplicates, then sort and tuple
        sorted_hosts = sorted(set(hosts), key=_sort_key)
        return cls(tuple(sorted_hosts))


    # ------------------------------------------------------------------
    # Formatting
    # ------------------------------------------------------------------
    def compact(self, compress: bool = True) -> str:
        """Return a comma‑separated hostlist; optionally compress it."""
        if not self.hosts:
            return ""
        if not compress:
            return ",".join(self.hosts)

        groups = _group_by_prefix(self.hosts)
        parts = []
        for (prefix, suffix) in sorted(groups.keys()):
            nums = groups[(prefix, suffix)]

            numeric = sorted([n for n in nums if n is not None])

            if not numeric:
                # Just a literal host
                parts.append(f"{prefix}{suffix}")
                continue

            # Infer padding width from the first numeric occurrence of this prefix/suffix
            first_host = next(h for h in self.hosts if h.startswith(prefix) and h.endswith(suffix) and any(c.isdigit() for c in h))
            num_match = re.search(rf"{re.escape(prefix)}(?P<num>\d+){re.escape(suffix)}", first_host)
            pad = len(num_match.group("num")) if num_match else 0

            parts.append(f"{prefix}[{_compress_numbers(numeric, pad)}]{suffix}")

        return ",".join(parts)

    # ------------------------------------------------------------------
    # Set‑like operations (return new Hostlist instances)
    # ------------------------------------------------------------------
    def _as_set(self) -> set[str]:
        return set(self.hosts)

    def diff(self, *others: Union["Hostlist", str, list[str]]) -> "Hostlist":
        """self – union(others)"""
        base = self._as_set()
        for o in others:
            base.difference_update(_coerce(o)._as_set())
        return Hostlist.from_list(sorted(base, key=lambda h: _parse_node(h)))

    def intersect(self, *others: Union["Hostlist", str, list[str]]) -> "Hostlist":
        base = self._as_set()
        for o in others:
            base.intersection_update(_coerce(o)._as_set())
        return Hostlist.from_list(sorted(base, key=lambda h: _parse_node(h)))

    def union(self, *others: Union["Hostlist", str, list[str]]) -> "Hostlist":
        base = self._as_set()
        for o in others:
            base.update(_coerce(o)._as_set())
        return Hostlist.from_list(sorted(base, key=lambda h: _parse_node(h)))

    def xor(self, *others: Union["Hostlist", str, list[str]]) -> "Hostlist":
        base = self._as_set()
        for o in others:
            base.symmetric_difference_update(_coerce(o)._as_set())
        return Hostlist.from_list(sorted(base, key=lambda h: _parse_node(h)))

    # ------------------------------------------------------------------
    # Collection API (Magic Methods)
    # ------------------------------------------------------------------
    def __len__(self) -> int:
        return len(self.hosts)

    def __iter__(self):
        return iter(self.hosts)

    def __contains__(self, item: object) -> bool:
        return item in self.hosts

    def __getitem__(self, index: Union[int, slice]) -> Union[str, "Hostlist"]:
        """Supports 0-based indexing and slicing."""
        if isinstance(index, slice):
            return Hostlist.from_list(self.hosts[index])
        return self.hosts[index]

    def __repr__(self) -> str:
        return f"Hostlist({self.hosts!r})"

    # ------------------------------------------------------------------
    # Set Operators
    # ------------------------------------------------------------------
    def __and__(self, other: Union["Hostlist", str, list[str]]) -> "Hostlist":
        return self.intersect(other)

    def __or__(self, other: Union["Hostlist", str, list[str]]) -> "Hostlist":
        return self.union(other)

    def __sub__(self, other: Union["Hostlist", str, list[str]]) -> "Hostlist":
        return self.diff(other)

    def __xor__(self, other: Union["Hostlist", str, list[str]]) -> "Hostlist":
        return self.xor(other)

    # ------------------------------------------------------------------
    # Misc helpers
    # ------------------------------------------------------------------
    def nth(self, n: int) -> str:
        """Return the n‑th host (1‑based)."""
        if n < 1 or n > len(self):
            raise ValueError("index out of range")
        return self[n - 1]

    def find(self, host: str) -> int:
        """Return 1‑based position of *host*."""
        try:
            return self.hosts.index(host) + 1
        except ValueError:
            raise ValueError("host not found") from None

    def count(self) -> int:
        """Backward compatible with __len__."""
        return len(self)

    def remove(self, host: str) -> "Hostlist":
        """Return a new Hostlist without *host*."""
        if host not in self:
            raise ValueError("host not found")
        new = [h for h in self.hosts if h != host]
        return Hostlist.from_list(new)

    def delimiter(self, d: str) -> str:
        """Join the list with a custom delimiter (no compression)."""
        return d.join(self.hosts)

    def size(self, N: int) -> "Hostlist":
        """Return at most N hosts (negative → last N)."""
        return Hostlist.from_list(self.hosts[:N] if N >= 0 else self.hosts[N:])

    def exclude(self, *hosts: str) -> "Hostlist":
        """Return a Hostlist without the supplied hosts."""
        remaining = [h for h in self.hosts if h not in hosts]
        if not remaining:
            raise ValueError("resulting hostlist empty")
        return Hostlist.from_list(remaining)

    def quiet(self) -> str:
        """Plain comma‑separated list; raise if empty."""
        if not self.hosts:
            raise ValueError("hostlist empty")
        return ",".join(self.hosts)

    def format(self, template: str) -> list[str]:
        """
        Return a list of formatted strings using the provided template.
        The template should contain a {host} placeholder.
        """
        return [template.format(host=h) for h in self.hosts]
Methods:
__getitem__
__getitem__(index)

Supports 0-based indexing and slicing.

Source code in src/hostlist/core.py
def __getitem__(self, index: Union[int, slice]) -> Union[str, "Hostlist"]:
    """Supports 0-based indexing and slicing."""
    if isinstance(index, slice):
        return Hostlist.from_list(self.hosts[index])
    return self.hosts[index]
compact
compact(compress=True)

Return a comma‑separated hostlist; optionally compress it.

Source code in src/hostlist/core.py
def compact(self, compress: bool = True) -> str:
    """Return a comma‑separated hostlist; optionally compress it."""
    if not self.hosts:
        return ""
    if not compress:
        return ",".join(self.hosts)

    groups = _group_by_prefix(self.hosts)
    parts = []
    for (prefix, suffix) in sorted(groups.keys()):
        nums = groups[(prefix, suffix)]

        numeric = sorted([n for n in nums if n is not None])

        if not numeric:
            # Just a literal host
            parts.append(f"{prefix}{suffix}")
            continue

        # Infer padding width from the first numeric occurrence of this prefix/suffix
        first_host = next(h for h in self.hosts if h.startswith(prefix) and h.endswith(suffix) and any(c.isdigit() for c in h))
        num_match = re.search(rf"{re.escape(prefix)}(?P<num>\d+){re.escape(suffix)}", first_host)
        pad = len(num_match.group("num")) if num_match else 0

        parts.append(f"{prefix}[{_compress_numbers(numeric, pad)}]{suffix}")

    return ",".join(parts)
count
count()

Backward compatible with len.

Source code in src/hostlist/core.py
def count(self) -> int:
    """Backward compatible with __len__."""
    return len(self)
delimiter
delimiter(d)

Join the list with a custom delimiter (no compression).

Source code in src/hostlist/core.py
def delimiter(self, d: str) -> str:
    """Join the list with a custom delimiter (no compression)."""
    return d.join(self.hosts)
diff
diff(*others)

self – union(others)

Source code in src/hostlist/core.py
def diff(self, *others: Union["Hostlist", str, list[str]]) -> "Hostlist":
    """self – union(others)"""
    base = self._as_set()
    for o in others:
        base.difference_update(_coerce(o)._as_set())
    return Hostlist.from_list(sorted(base, key=lambda h: _parse_node(h)))
exclude
exclude(*hosts)

Return a Hostlist without the supplied hosts.

Source code in src/hostlist/core.py
def exclude(self, *hosts: str) -> "Hostlist":
    """Return a Hostlist without the supplied hosts."""
    remaining = [h for h in self.hosts if h not in hosts]
    if not remaining:
        raise ValueError("resulting hostlist empty")
    return Hostlist.from_list(remaining)
expand classmethod
expand(spec)

Parse a possibly‑compressed hostlist string.

Source code in src/hostlist/core.py
@classmethod
def expand(cls, spec: str) -> "Hostlist":
    """Parse a possibly‑compressed hostlist string."""
    if not spec:
        return cls(())

    # split on commas that are **outside** brackets
    parts, buf, depth = [], "", 0
    for ch in spec:
        if ch == "[":
            depth += 1
        elif ch == "]":
            depth -= 1
            if depth < 0:
                raise ValueError("Unexpected closing bracket ']' in hostlist")
        if ch == "," and depth == 0:
            parts.append(buf)
            buf = ""
        else:
            buf += ch

    if depth != 0:
        raise ValueError("Unclosed bracket '[' in hostlist")

    if buf:
        parts.append(buf)

    expanded: list[str] = []
    for token in parts:
        token = token.strip()
        if not token:
            continue
        m = re.fullmatch(
            r"(?P<prefix>[\w-]+)\[(?P<body>[^\]]*)\](?P<suffix>.*)", token
        )
        if not m:               # plain host (no brackets)
            expanded.append(token)
            continue

        prefix, body, suffix = m.group("prefix"), m.group("body"), m.group("suffix")

        # Determine zero‑padding width from the first numeric token
        pad = 0
        for sub in body.split(","):
            sub = sub.strip()
            if not sub: continue
            start = sub.split("-", 1)[0] if "-" in sub else sub
            if start.lstrip("0") != start:          # leading zeros present
                pad = max(pad, len(start))

        try:
            for num in _expand_range(body):
                expanded.append(f"{prefix}{str(num).zfill(pad)}{suffix}")
        except ValueError as e:
            raise ValueError(f"Invalid range in bracket for {token!r}: {e}")

    # Normalise ordering (numeric order per prefix/suffix)
    expanded.sort(key=_sort_key)
    return cls(tuple(expanded))
find
find(host)

Return 1‑based position of host.

Source code in src/hostlist/core.py
def find(self, host: str) -> int:
    """Return 1‑based position of *host*."""
    try:
        return self.hosts.index(host) + 1
    except ValueError:
        raise ValueError("host not found") from None
format
format(template)

Return a list of formatted strings using the provided template. The template should contain a {host} placeholder.

Source code in src/hostlist/core.py
def format(self, template: str) -> list[str]:
    """
    Return a list of formatted strings using the provided template.
    The template should contain a {host} placeholder.
    """
    return [template.format(host=h) for h in self.hosts]
from_list classmethod
from_list(hosts)

Create a Hostlist from an already‑expanded iterable.

Source code in src/hostlist/core.py
@classmethod
def from_list(cls, hosts: Iterable[str]) -> "Hostlist":
    """Create a Hostlist from an already‑expanded iterable."""
    # Convert to set to remove duplicates, then sort and tuple
    sorted_hosts = sorted(set(hosts), key=_sort_key)
    return cls(tuple(sorted_hosts))
nth
nth(n)

Return the n‑th host (1‑based).

Source code in src/hostlist/core.py
def nth(self, n: int) -> str:
    """Return the n‑th host (1‑based)."""
    if n < 1 or n > len(self):
        raise ValueError("index out of range")
    return self[n - 1]
quiet
quiet()

Plain comma‑separated list; raise if empty.

Source code in src/hostlist/core.py
def quiet(self) -> str:
    """Plain comma‑separated list; raise if empty."""
    if not self.hosts:
        raise ValueError("hostlist empty")
    return ",".join(self.hosts)
remove
remove(host)

Return a new Hostlist without host.

Source code in src/hostlist/core.py
def remove(self, host: str) -> "Hostlist":
    """Return a new Hostlist without *host*."""
    if host not in self:
        raise ValueError("host not found")
    new = [h for h in self.hosts if h != host]
    return Hostlist.from_list(new)
size
size(N)

Return at most N hosts (negative → last N).

Source code in src/hostlist/core.py
def size(self, N: int) -> "Hostlist":
    """Return at most N hosts (negative → last N)."""
    return Hostlist.from_list(self.hosts[:N] if N >= 0 else self.hosts[N:])