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)
Related¶
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 ¶
Atom ¶
Bases: Entity
Atom view: one node in a molrs Atomistic world (or pending).
is_virtual
property
¶
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 ¶
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
¶
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 ¶
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 ¶
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 ¶
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 ¶
Dihedral ¶
DrudeParticle ¶
Improper ¶
MasslessSite ¶
VirtualSite ¶
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 ¶
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
Styleenum (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 |
None
|
pbc
|
ArrayLike | None
|
Boolean periodic-boundary flags per axis, shape |
None
|
origin
|
ArrayLike | None
|
Cartesian origin in Angstroms, shape |
None
|
is_free
property
¶
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
¶
Lattice vector magnitudes [a, b, c] in Angstroms.
Returns zeros 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 box with three equal edge lengths.
from_bounds
classmethod
¶
Tight orthogonal box around a point cloud (non-periodic by default).
from_box
classmethod
¶
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
¶
Triclinic box from edge lengths and lattice angles (degrees).
general2restrict
staticmethod
¶
General → restricted-triclinic conversion (LAMMPS convention).
orth
classmethod
¶
Orthogonal (axis-aligned cuboid) box.
tric
classmethod
¶
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 ¶
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
|
bucket ¶
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 |
exact_bucket ¶
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 an object from the bucket
Returns:
| Type | Description |
|---|---|
bool
|
True if successfully removed, False otherwise |
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 ¶
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: |
required |
FrameIntervalStrategy ¶
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-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 ¶
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
|
required |
Trajectory ¶
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: |
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)
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 ¶
Apply func to every frame, returning a new trajectory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[[Frame], Frame]
|
A callable mapping a :class: |
required |
Returns:
| Type | Description |
|---|---|
'Trajectory'
|
A new :class: |
'Trajectory'
|
trajectory's topology. The original is not modified. |
TrajectorySplitter ¶
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 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: |
list[Trajectory]
|
the original frames sharing its topology. |
split_frames ¶
Split every interval frames (convenience for FrameIntervalStrategy).
split_time ¶
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 molrsCoarseGrainas 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 ¶
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 ¶
Bases: Link['Bead']
Coarse-grained bond between two beads (molrs relation kind bonds).
CoarseGrain ¶
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).
merge ¶
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 ¶
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 ¶
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
¶
reset
classmethod
¶
temporary
classmethod
¶
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:
update
classmethod
¶
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:
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
¶
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
¶
Get a copy of all script lines.
Returns:
| Type | Description |
|---|---|
list[str]
|
Copy of internal lines list |
text
property
¶
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 a single line to the end of the script.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
line
|
str
|
Line content to append |
''
|
append_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 |
delete ¶
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 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 ¶
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 ¶
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 ¶
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
¶
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
¶
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
¶
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 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 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 ¶
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 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 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 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 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 |