Skip to content

Core

Foundational data structures for molecular systems. All available via import molpy as mp.

Quick reference

Symbol Summary Preferred for Avoid when
Atomistic Editable molecular graph (atoms + bonds) Building, editing, reacting on chemistry Array-backed analysis or export
Block Columnar table: column names → NumPy arrays Tabular data, vectorized computation Graph-level chemical editing
Frame Named collection of Blocks + metadata System snapshots, file I/O Editing individual atoms
Box Periodic simulation cell (3×3 matrix + PBC) Wrapping, minimum-image distances Non-periodic systems
Trajectory Ordered sequence of Frames (eager or lazy) Time-series analysis, streaming I/O Single-snapshot work
CoarseGrain CG molecular graph (beads + CG bonds) Coarse-grained modelling; mirrors Atomistic All-atom work (use Atomistic)
Config Thread-safe global configuration singleton Logging level, thread count settings Per-run overrides (use Config.temporary)
AtomisticForcefield Force field container (styles → types → potentials) Defining parameters before execution Direct numerical computation

Canonical examples

import molpy as mp

# Atomistic: editable molecular graph
mol = mp.Atomistic(name="water")
o = mol.def_atom(element="O", x=0.0, y=0.0, z=0.0)
h = mol.def_atom(element="H", x=0.957, y=0.0, z=0.0)
mol.def_bond(o, h)

# Block + Frame: tabular snapshot
frame = mp.Frame(blocks={
    "atoms": {"element": ["O", "H"], "x": [0.0, 0.957]},
}, timestep=0)

# Box: periodic cell
box = mp.Box.cubic(20.0)
wrapped = box.wrap(coords)
d = box.dist(r1, r2)  # minimum-image distance

# ForceField: parameter data
ff = mp.AtomisticForcefield(name="demo", units="real")
style = ff.def_atomstyle("full")
ct = style.def_type("CT", mass=12.011)

Full API

Atomistic

atomistic

All-atom molecular structure as a handle-view over a molrs Atomistic.

Atomistic(_GraphViews, molrs.Atomistic) IS a molrs world — it is accepted directly by every molrs.* system free function (no .to_molrs() bridge). :class:Atom / :class:Bond / :class:Angle / :class:Dihedral / :class:Improper are handle views interned per stable handle.

Angle

Angle(a, b, c, /, **attrs)

Bases: Link[Atom]

Valence angle over three atoms i--j--k (kind angles).

Atom

Atom(mapping=None, /, **attrs)

Bases: Entity

Atom view: one node in a molrs Atomistic world (or pending).

is_virtual property
is_virtual

True if this node carries a virtual-site marker (vsite field).

The marker is a stored data field, not the Python class: molrs re-materialises nodes as plain :class:Atom, so identity must be read from the persisted vsite field rather than isinstance.

Atomistic

Atomistic(**props)

Bases: Atomistic, _GraphViews

All-atom molecular structure backed by a molrs Atomistic world.

Note on base order: the pyo3 native molrs.Atomistic must be the first base so the extension instance layout is initialised correctly (a pyo3 extends class cannot sit behind a plain-Python base). _GraphViews contributes only non-conflicting helpers, and the leaf's own methods win in the MRO regardless of order, so this preserves the spec's intent.

adopt staticmethod
adopt(graph)

Zero-copy take ownership of a molrs-produced Atomistic graph.

Uses the molrs zero-copy adopt to move graph's storage into a fresh molpy Atomistic (graph is left empty). Views over the adopted nodes/relations are interned lazily on access.

get_topo
get_topo(entity_type=Atom, link_type=Bond, gen_angle=False, gen_dihe=False, clear_existing=False)

Return a copy with angle/dihedral relations perceived from the bonds.

Angle/dihedral perception (2-edge / 3-edge paths over the bond graph) is a molrs-native graph operation; this delegates to that Rust kernel on a copy. With no gen_* flags it is a plain copy. Always returns an :class:Atomistic (never a bare topology graph).

merge
merge(other)

Transfer other's atoms and topology into self in place.

The same view objects are reused (identity preserved): each of other's atoms/links is detached and re-spawned onto self with a fresh handle, so external references (e.g. a reacter's leaving-group list) stay valid. other is emptied and must not be used afterwards.

to_frame
to_frame(atom_fields=None)

Export to a tabular :class:Frame (atoms + bonds/angles/dihedrals/ impropers blocks).

Delegates straight to the molrs world's native to_frame: the Rust column store already holds every component as a dense, row-aligned column, so each block is materialized as numpy with zero Python-side conversion. atom_fields optionally restricts the atoms block columns.

Bond

Bond(a, b, /, **attrs)

Bases: Link[Atom]

Covalent bond between two atoms (molrs relation kind bonds).

Dihedral

Dihedral(a, b, c, d, /, **attrs)

Bases: Link[Atom]

Proper dihedral (torsion) over four atoms (kind dihedrals).

DrudeParticle

DrudeParticle(mapping=None, /, **attrs)

Bases: VirtualSite

Polarizable Drude shell: co-located with its core, spring-bound.

Improper

Improper(a, b, c, d, /, **attrs)

Bases: Link[Atom]

Improper torsion over four atoms, i central (kind impropers).

MasslessSite

MasslessSite(mapping=None, /, **attrs)

Bases: VirtualSite

Rigid geometric site (e.g. TIP4P M-site, lone pair); no spring.

VirtualSite

VirtualSite(mapping=None, /, **attrs)

Bases: Atom

A massless / rule-placed auxiliary particle. Data only — no energy.

Carries a persistent vsite marker field (set on construction) plus the usual atom data. Subclasses set the marker value via _vsite_kind. Identity after a molrs round-trip is read from the vsite field (:attr:Atom.is_virtual), since the Python subclass is not preserved.

Box

box

Box

Box(matrix=None, pbc=None, origin=None)

Bases: Box

Simulation box — molpy front for the molrs spatial primitive.

Inherits molrs.Box directly, so a molpy.Box instance is accepted by every molrs API (NeighborQuery, RDF, wrap, isin, …) without conversion. molpy adds:

  • the Style enum (FREE / ORTHOGONAL / TRICLINIC),
  • molpy-style accessors (lx, ly, lz, xy, xz, yz, a, b, c, lengths, angles, tilts, bounds, xlo/xhi/…),
  • convenience factories (cubic, orth, tric, from_lengths_angles, from_bounds, from_box),
  • PBC-aware geometry helpers (wrap, unwrap, diff, dist, make_fractional, make_absolute, get_distance_between_faces, get_images).

Immutable. State lives in the molrs base; per-axis setters and set_* methods were removed in this refactor (use one of the classmethod factories to construct a new Box instead). This matches molpy's own coding-style.md "avoid mutation" rule.

Parameters:

Name Type Description Default
matrix ArrayLike | None

A (3, 3) upper-triangular box matrix (lattice vectors as columns). None or an all-zero matrix produces a FREE (non-periodic) box. A (3,) array is promoted to a diagonal matrix.

None
pbc ArrayLike | None

Boolean periodic-boundary flags per axis, shape (3,). Defaults to [True, True, True].

None
origin ArrayLike | None

Cartesian origin in Angstroms, shape (3,). Defaults to [0, 0, 0].

None
angles property
angles

Lattice angles [alpha, beta, gamma] in degrees.

is_free property
is_free

True if this box is FREE (no defined cell, zero volume).

Derived from the molrs base's cell_defined flag — the single source of truth — not a Python-side shadow.

lengths property
lengths

Lattice vector magnitudes [a, b, c] in Angstroms.

Returns zeros for FREE.

matrix property
matrix

Box matrix with lattice vectors as columns, shape (3, 3).

style property
style

FREE / ORTHOGONAL / TRICLINIC depending on the matrix shape.

volume property
volume

Box volume in Angstroms³ (zero for FREE).

Style

Bases: str, Enum

Enumeration of simulation-box geometries.

Values are the canonical molrs style strings so a molpy.Box.Style member compares equal to the string returned by molrs.Box.style (e.g. Box.Style.ORTHOGONAL == "orthogonal"), letting frame.box (a molrs box) interoperate with molpy style checks.

cubic classmethod
cubic(length, pbc=None, origin=None, central=False)

Cubic box with three equal edge lengths.

from_bounds classmethod
from_bounds(points, padding=0.0, pbc=None)

Tight orthogonal box around a point cloud (non-periodic by default).

from_box classmethod
from_box(box)

Copy / upgrade constructor.

Accepts a molpy Box or a bare molrs.Box (e.g. frame.box), reading only the public matrix / pbc / origin accessors so it works across both. A free source box reconstructs a free molpy box.

from_lengths_angles classmethod
from_lengths_angles(lengths, angles)

Triclinic box from edge lengths and lattice angles (degrees).

general2restrict staticmethod
general2restrict(matrix)

General → restricted-triclinic conversion (LAMMPS convention).

orth classmethod
orth(lengths, pbc=None, origin=None, central=False)

Orthogonal (axis-aligned cuboid) box.

plot
plot()

Placeholder for 3D box visualization.

to_lengths_angles
to_lengths_angles()

Return (lengths, angles); angles in degrees.

tric classmethod
tric(lengths, tilts, pbc=None, origin=None, central=False)

Triclinic box from edge lengths and tilt factors.

Forcefield

forcefield

Force-field model — thin re-export of the native molrs hierarchy.

molrs (the Rust extension) natively owns the entire force-field model: ForceField, the Style tree, the Type tree and Parameters. molpy no longer maintains a parallel Python hierarchy; this module simply re-exports the molrs classes and adds the handful of thin specialized Style subclasses that molrs does not ship a named class for (e.g. morse, class2, fourier, periodic variants).

A specialized style here carries no kernel — it only fixes the style name so callers can write ff.def_style(BondMorseStyle()) instead of ff.def_bondstyle("morse"). Energy/force evaluation lives entirely in molrs via ff.to_potentials().calc_energy(frame) / .calc_forces(frame).

AngleClass2BondAngleStyle

Bases: AngleStyle

Angle class2/ba cross term.

AngleClass2BondBondStyle

Bases: AngleStyle

Angle class2/bb cross term.

AngleClass2Style

Bases: AngleStyle

Angle class2 style.

BondClass2Style

Bases: BondStyle

Bond class2 style.

BondMorseStyle

Bases: BondStyle

Bond morse style (LAMMPS bond_style morse).

DihedralCharmmStyle

Bases: DihedralStyle

Dihedral charmm style.

DihedralClass2Style

Bases: DihedralStyle

Dihedral class2 style.

DihedralFourierStyle

Bases: DihedralStyle

Dihedral fourier style (AMBER multi-term).

DihedralMultiHarmonicStyle

Bases: DihedralStyle

Dihedral multi/harmonic style.

DihedralPeriodicStyle

Bases: DihedralStyle

Dihedral periodic (CHARMM-style charmm/periodic) style.

ImproperClass2Style

Bases: ImproperStyle

Improper class2 style.

ImproperCvffStyle

Bases: ImproperStyle

Improper cvff style.

ImproperHarmonicStyle

Bases: ImproperStyle

Improper harmonic style.

ImproperPeriodicStyle

Bases: ImproperStyle

Improper periodic style.

PairBuckStyle

Bases: PairStyle

Pair buck (Buckingham) style.

PairCoulTTStyle

Bases: PairStyle

Pair coul/tt — Tang−Toennies damped charge−dipole Coulomb style.

Style-level parameters: b (1/Å, default 4.5), n (default 4), c (default 1.0). Per-atom-type parameter: charge (e). Damping: f_n(r) = 1 − c·exp(−b·r)·Σ_{k=0}^n (b·r)^k/k!.

Reference: Tang & Toennies, J. Chem. Phys. 80 (1984) 3726, :doi:10.1063/1.447150.

PairLJClass2Style

Bases: PairStyle

Pair lj/class2 style.

PairMorseStyle

Bases: PairStyle

Pair morse style.

PairTholeStyle

Bases: PairStyle

Pair thole — Thole damped dipole-dipole / core-shell Coulomb style.

Per-atom-type parameters: charge (e), alpha (ų), a_thole (dimensionless Thole damping width, default 2.6). Damping: T(r) = 1 − (1 + s·r/2)·exp(−s·r) where s = a_ij / (α_i·α_j)^(1/6), a_ij = (a_i + a_j)/2.

Reference: Thole, Chem. Phys. 59 (1981) 341, :doi:10.1016/0301-0104(81)85176-2.

TypeBucket

TypeBucket(container_type=set)

Generic TypeBucket implementation that groups and stores objects by their concrete type.

Supports two storage modes: - Set mode (set): For storing unique type definitions with automatic deduplication - List mode (list): For storing entity objects while maintaining order

Usage example
Set mode (used by forcefield)

bucket = TypeBucket(container_type=set)

List mode (used by entity)

bucket = TypeBucket(container_type=list)

Initialize TypeBucket

Parameters:

Name Type Description Default
container_type type

Container type, set (deduplication) or list (maintain order)

set
add
add(item)

Add an object to its corresponding type bucket

add_many
add_many(items)

Add multiple objects

all
all()

Return all objects from all buckets

bucket
bucket(cls)

Get objects of the specified type and all its subclasses

Parameters:

Name Type Description Default
cls type[T]

Target type

required

Returns:

Type Description
list[T]

List containing all matching objects

classes
classes()

Return all concrete types currently stored

exact_bucket
exact_bucket(cls)

Get objects of exact type (excluding subclasses)

Parameters:

Name Type Description Default
cls type[T]

Target type

required

Returns:

Type Description
list[T]

List containing exact matching objects

remove
remove(item)

Remove an object from the bucket

Returns:

Type Description
bool

True if successfully removed, False otherwise

get_nearest_type

get_nearest_type(item)

Get the concrete type of an object

Frame

frame

molpy Frame/Block — re-exported from the molrs Rust backend.

After the frame-block-sink cutover (chain 4/4), molpy no longer defines its own Frame/Block subclasses or any Python-side object-column overflow. The canonical rich types live in molrs: numpy-only typed columns in the Rust Store with a pandas-style Python API (selectors, sorting, row iteration, CSV, and dict conversion).

Identity contract::

molpy.core.frame.Frame is molrs.Frame
molpy.core.frame.Block is molrs.Block

This module exists only so the existing from molpy.core.frame import Frame, Block call sites keep resolving. Object / None / ragged columns are now rejected fail-fast at write time (molrs.BlockDtypeError); callers must use numpy-representable columns.

Trajectory

trajectory

Trajectory container (molrs-backed) + split extensions.

The trajectory container sinks to molrs: :class:molpy.Trajectory subclasses :class:molrs.Trajectory — an eager, materialized sequence of frames with optional step / time arrays. molpy adds Python-side conveniences: an associated topology, slice indexing that returns a sub-trajectory, and frame mapping. Lazy, seekable reading from disk lives in molrs as TrajectoryReader (molrs.read_lammps_trajectory / read_xyz_trajectory), not here.

Trajectory splitting stays in molpy as an extension layer that operates on the molrs-backed container (:class:SplitStrategy and :class:TrajectorySplitter).

CustomStrategy

CustomStrategy(split_func)

Bases: SplitStrategy

Split a trajectory using a user-provided function.

Parameters:

Name Type Description Default
split_func Callable[[Trajectory], list[int]]

A callable taking a :class:Trajectory and returning a list of split indices. The first index should be 0 and the last the total frame count.

required

FrameIntervalStrategy

FrameIntervalStrategy(interval)

Bases: SplitStrategy

Split a trajectory at regular frame intervals.

Splits the trajectory every interval frames, creating segments of equal size (except possibly the last).

Parameters:

Name Type Description Default
interval int

Number of frames per segment. Must be positive.

required

SplitStrategy

Bases: ABC

Abstract base class for trajectory splitting strategies.

Subclasses implement different strategies for dividing a trajectory into segments based on various criteria (frame count, time intervals, etc.).

get_split_indices abstractmethod
get_split_indices(trajectory)

Get split-point indices for dividing the trajectory.

Parameters:

Name Type Description Default
trajectory Trajectory

The trajectory to split.

required

Returns:

Type Description
list[int]

Indices where the trajectory should be split. The first index is 0

list[int]

and the last is the total number of frames.

TimeIntervalStrategy

TimeIntervalStrategy(interval)

Bases: SplitStrategy

Split a trajectory by simulation-time intervals.

Splits based on the trajectory's native per-frame time array (the molrs container's time representation, set via Trajectory(frames, time=...)). A trajectory without a time array is left unsplit (single segment).

Parameters:

Name Type Description Default
interval float

Time interval for splitting (same units as the trajectory's time array). Must be positive.

required

Trajectory

Trajectory(frames, topology=None, step=None, time=None)

Bases: Trajectory

An eager sequence of molecular frames with an optional topology.

Subclasses :class:molrs.Trajectory: frame storage, len(), integer indexing, and the frames / step / time accessors all live in the Rust container. molpy adds an associated topology, slice indexing (returns a sub-:class:Trajectory), and :meth:map.

Frames must be :class:molrs.Frame objects — the Rust container copies each into its column store on construction. For lazy, seekable reading from disk use molrs.read_lammps_trajectory / read_xyz_trajectory, which return a lazy TrajectoryReader instead of materializing every frame.

Parameters:

Name Type Description Default
frames Iterable[Frame]

Sequence of :class:molrs.Frame objects.

required
topology Any | None

Optional connectivity/topology object carried alongside the frames (stored and passed through unchanged). Defaults to None.

None
step Any | None

Optional per-frame integer step indices (forwarded to molrs).

None
time Any | None

Optional per-frame simulation times (forwarded to molrs).

None

Examples:

>>> traj = Trajectory([frame0, frame1, frame2])
>>> len(traj)
3
>>> traj[0]            # integer index -> Frame
Frame(...)
>>> traj[0:2]          # slice -> sub-Trajectory
Trajectory(n_frames=2, topology=None)
topology property
topology

The topology object associated with this trajectory (or None).

has_length
has_length()

Whether len() is available — always True for the eager container.

Retained for backwards compatibility; the molrs-backed container is always materialized, so this never returns False.

map
map(func)

Apply func to every frame, returning a new trajectory.

Parameters:

Name Type Description Default
func Callable[[Frame], Frame]

A callable mapping a :class:Frame to a :class:Frame.

required

Returns:

Type Description
'Trajectory'

A new :class:Trajectory of the mapped frames, sharing this

'Trajectory'

trajectory's topology. The original is not modified.

TrajectorySplitter

TrajectorySplitter(trajectory)

Split a trajectory into sub-trajectories using a strategy.

The resulting segments are :class:Trajectory objects that share the same topology as the original.

Parameters:

Name Type Description Default
trajectory Trajectory

The trajectory to split.

required
split
split(strategy)

Split the trajectory using strategy.

Parameters:

Name Type Description Default
strategy SplitStrategy

The splitting strategy to apply.

required

Returns:

Type Description
list[Trajectory]

A list of :class:Trajectory segments, each a contiguous subset of

list[Trajectory]

the original frames sharing its topology.

split_frames
split_frames(interval)

Split every interval frames (convenience for FrameIntervalStrategy).

split_time
split_time(interval)

Split every interval time units (convenience for TimeIntervalStrategy).

Coarse-Grain

cg

Coarse-grained molecular structure as a handle-view over a molrs CoarseGrain.

Mirrors :mod:molpy.core.atomistic: CoarseGrain(_GraphViews, molrs.CoarseGrain) IS a molrs world; :class:Bead / :class:CGBond are interned handle views.

Dict keys:

  • bead["atoms"] — tuple[Atom, ...] of atom views this bead groups. This is the bead's membership, owned by the molrs CoarseGrain as opaque atom handles (not a scalar component) and resolved back to views through the source all-atom world. Drives :meth:CoarseGrain.beads_of.
  • bead["x"] / bead["y"] / bead["z"] — position (molrs columns).
  • bead["type"] / bead["mass"] / bead["charge"] — molrs columns.

Bead

Bead(mapping=None, /, **attrs)

Bases: Entity

Coarse-grained bead view: one node in a molrs CoarseGrain world.

The "atoms" key is not a scalar component: it is the bead's membership (the underlying atom views it groups), owned by the molrs CoarseGrain as opaque atom handles and resolved back to views through the source world. It is intercepted here so bead["atoms"] / bead.get("atoms") keep working over the membership store rather than the component columns.

CGBond

CGBond(a, b, /, **attrs)

Bases: Link['Bead']

Coarse-grained bond between two beads (molrs relation kind bonds).

CoarseGrain

CoarseGrain(**props)

Bases: CoarseGrain, _GraphViews

Coarse-grained molecular structure backed by a molrs CoarseGrain.

Base order: the pyo3 native molrs.CoarseGrain must be first (see the note on :class:molpy.core.atomistic.Atomistic).

adopt staticmethod
adopt(graph)

Zero-copy take ownership of a molrs-produced CoarseGrain graph.

beads_of
beads_of(atom)

Beads whose membership includes atom (molrs reverse lookup).

merge
merge(other)

Transfer other's beads and bonds into self in place.

Identity-preserving move (see :meth:molpy.core.atomistic.Atomistic.merge): the same view objects are reused; other is emptied.

to_frame
to_frame(bead_fields=None)

Export to a tabular :class:Frame (beads + cgbonds blocks).

Delegates straight to the molrs world's native to_frame: the Rust column store yields dense numpy columns and applies the CG-domain block / column labels (beads / cgbonds / ibead / jbead) itself, so there is zero Python-side conversion. bead_fields optionally restricts the beads block columns.

Config

config

Global configuration system for MolPy.

This module provides a thread-safe singleton configuration system using Pydantic. Configuration can be accessed globally, updated, reset, or temporarily overridden using a context manager.

Examples:

>>> from molpy.core.config import config, Config
>>>
>>> # Access current config
>>> print(config.log_level)
'INFO'
>>>
>>> # Update config globally
>>> Config.update(log_level='DEBUG', n_threads=4)
>>>
>>> # Temporary override
>>> with Config.temporary(log_level='WARNING'):
...     print(config.log_level)  # 'WARNING'
>>> print(config.log_level)  # Back to 'DEBUG'

config module-attribute

config = instance()

Global config instance. Use this for read access.

Config

Bases: BaseModel

Global configuration for MolPy.

Thread-safe singleton that stores global settings like logging level and parallelization parameters. Use class methods to access and modify the singleton instance.

Attributes:

Name Type Description
log_level str

Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)

n_threads int

Number of threads for parallel computations

Examples:

>>> # Get singleton instance
>>> cfg = Config.instance()
>>>
>>> # Update configuration
>>> Config.update(n_threads=8)
>>>
>>> # Temporary override
>>> with Config.temporary(log_level='DEBUG'):
...     # Config is DEBUG here
...     pass
>>> # Config restored here
instance classmethod
instance()

Get the singleton Config instance.

Thread-safe lazy initialization. Creates instance on first call.

Returns:

Type Description
Self

The singleton Config instance

Examples:

>>> cfg = Config.instance()
>>> print(cfg.log_level)
'INFO'
reset classmethod
reset()

Reset configuration to default values.

Thread-safe reset. Creates a new instance with all default values.

Examples:

>>> Config.update(n_threads=8)
>>> Config.reset()
>>> print(Config.instance().n_threads)
1
temporary classmethod
temporary(**overrides)

Temporarily override configuration within a context.

Thread-safe context manager that restores original config on exit. Useful for testing or temporary parameter changes.

Parameters:

Name Type Description Default
**overrides Any

Configuration fields to temporarily override.

{}

Yields:

Type Description
None

None

Examples:

>>> original_level = Config.instance().log_level
>>> with Config.temporary(log_level='DEBUG'):
...     print(Config.instance().log_level)  # 'DEBUG'
>>> print(Config.instance().log_level)  # original_level
update classmethod
update(**kwargs)

Update the global configuration.

Thread-safe update that creates a new instance with updated values. Changes persist until reset() or another update().

Parameters:

Name Type Description Default
**kwargs Any

Configuration fields to update (log_level, n_threads, etc.).

{}

Examples:

>>> Config.update(log_level='DEBUG', n_threads=4)
>>> cfg = Config.instance()
>>> print(cfg.n_threads)
4

get_config

get_config()

Get the global configuration instance.

Convenience function equivalent to Config.instance().

Returns:

Type Description
Config

The singleton Config instance

Examples:

>>> cfg = get_config()
>>> print(cfg.log_level)
'INFO'

Script

script

Script - Editable script management with filesystem and URL support.

This module provides a Script class for managing script content that can be stored locally or loaded from URLs. It supports editing, formatting, and filesystem operations without any execution logic.

Script dataclass

Script(name, language='bash', description=None, _lines=list(), path=None, url=None, tags=set())

Represents an editable script with filesystem and URL support.

This class manages script content, metadata, and filesystem operations. It does NOT provide execution logic - only content management.

Attributes:

Name Type Description
name str

Logical name of the script

language ScriptLanguage

Script language type

description str | None

Optional human-readable description

_lines list[str]

Internal storage for multi-line content

path Path | None

Local file path if stored on disk

url str | None

URL the script was loaded from (if any)

tags set[str]

Optional lightweight tag system

lines property
lines

Get a copy of all script lines.

Returns:

Type Description
list[str]

Copy of internal lines list

text property
text

Get the full script as a single string.

Returns:

Type Description
str

Script content with lines joined by newlines, with exactly one trailing newline

append
append(line='')

Append a single line to the end of the script.

Parameters:

Name Type Description Default
line str

Line content to append

''
append_block
append_block(block)

Append a multi-line block to the script.

The block is dedented, trailing newlines are stripped, and then split into lines.

Parameters:

Name Type Description Default
block str

Multi-line string block to append

required
clear
clear()

Remove all lines from the script.

delete
delete(index)

Delete the line at the given index.

Parameters:

Name Type Description Default
index int

0-based index of line to delete

required

Raises:

Type Description
IndexError

If index is out of range

delete_file
delete_file()

Delete the script file from the filesystem.

Raises:

Type Description
ValueError

If script has no associated path

FileNotFoundError

If the file does not exist

OSError

If the file cannot be deleted

extend
extend(lines)

Append multiple lines in order to the end of the script.

Parameters:

Name Type Description Default
lines Iterable[str]

Iterable of lines to append

required
format
format(**kwargs)

Apply string formatting to all lines and return a new Script.

Uses Python's str.format(**kwargs) on each line.

Parameters:

Name Type Description Default
**kwargs Any

Format arguments

{}

Returns:

Type Description
Script

New Script instance with formatted lines

format_with_mapping
format_with_mapping(mapping)

Apply string formatting to all lines using a mapping and return a new Script.

Uses Python's str.format_map(mapping) on each line.

Parameters:

Name Type Description Default
mapping Mapping[str, Any]

Format mapping

required

Returns:

Type Description
Script

New Script instance with formatted lines

from_path classmethod
from_path(path, *, language=None, description=None)

Create a Script from a local file path.

Parameters:

Name Type Description Default
path str | Path

Path to the script file

required
language ScriptLanguage | None

Optional language override. If None, guessed from extension

None
description str | None

Optional description

None

Returns:

Type Description
Script

Script instance loaded from file

Raises:

Type Description
FileNotFoundError

If the file does not exist

IOError

If the file cannot be read

from_text classmethod
from_text(name, text, *, language='bash', description=None, path=None, url=None)

Create a Script from text content.

Parameters:

Name Type Description Default
name str

Logical name of the script

required
text str

Multi-line text content

required
language ScriptLanguage

Script language type

'bash'
description str | None

Optional description

None
path str | Path | None

Optional local file path

None
url str | None

Optional URL source

None

Returns:

Type Description
Script

Script instance with normalized content

from_url classmethod
from_url(url, *, name=None, language='other', description=None)

Create a Script from a URL.

Parameters:

Name Type Description Default
url str

URL to fetch the script from

required
name str | None

Optional name. If None, derived from URL

None
language ScriptLanguage

Script language type

'other'
description str | None

Optional description

None

Returns:

Type Description
Script

Script instance loaded from URL

Raises:

Type Description
URLError

If the URL cannot be fetched

insert
insert(index, line)

Insert a single line at the given index.

Parameters:

Name Type Description Default
index int

0-based index where to insert

required
line str

Line content to insert

required

Raises:

Type Description
IndexError

If index is out of range

move
move(new_path)

Move the script file to a new location.

Parameters:

Name Type Description Default
new_path str | Path

New file path

required

Returns:

Type Description
Path

New path where the script was moved

Raises:

Type Description
ValueError

If script has no associated path

FileNotFoundError

If the original file does not exist

OSError

If the file cannot be moved

preview
preview(max_lines=20, *, with_line_numbers=True)

Generate a preview of the script.

Parameters:

Name Type Description Default
max_lines int

Maximum number of lines to show

20
with_line_numbers bool

Whether to include line numbers

True

Returns:

Type Description
str

Preview string

reload
reload()

Reload the script content from its associated path.

Raises:

Type Description
ValueError

If script has no associated path

FileNotFoundError

If the file does not exist

IOError

If the file cannot be read

rename
rename(new_name)

Rename the script file (keeping the same directory).

Parameters:

Name Type Description Default
new_name str

New file name (with or without extension)

required

Returns:

Type Description
Path

New path where the script was renamed

Raises:

Type Description
ValueError

If script has no associated path

FileNotFoundError

If the original file does not exist

OSError

If the file cannot be renamed

replace
replace(index, line)

Replace the line at the given index.

Parameters:

Name Type Description Default
index int

0-based index of line to replace

required
line str

New line content

required

Raises:

Type Description
IndexError

If index is out of range

save
save(path=None)

Save the script to a file.

Parameters:

Name Type Description Default
path str | Path | None

Optional path to save to. If None, uses self.path

None

Returns:

Type Description
Path

Path where the script was saved

Raises:

Type Description
ValueError

If no path is provided and self.path is None

IOError

If the file cannot be written