CSV I/O API¶
Tier: Stable Core
Read and write Click Ladder CSV files and bundles of them.
laddercodec.read_csv ¶
read_csv(
path: Path | str,
*,
strict: bool = True,
unchecked: bool = False,
allow: Iterable[str] = (),
) -> list[Rung]
Read any Click Ladder CSV and return one Rung per CLICK rung.
Handles both single-rung and multi-rung CSV files in a single call.
Each Rung is a frozen dataclass with the fields conditions,
instructions, comment and comment_rtf::
rungs = read_csv(path)
r = rungs[0]
r.logical_rows # int, len(r.conditions)
r.conditions # tuple[tuple[ConditionToken, ...], ...]
r.instructions # tuple[InstructionToken, ...]
r.comment # str | None
Each rung is drawn as CLICK's syntax check draws it. The CSV gives the
circuit, and the layout sets the rows, the columns and the box heights.
CLICK splits a rung whose outputs' circuits meet only at the rail into one
rung per circuit, and read_csv does the same. The list can therefore
hold more rungs than the CSV. A rung that laddercodec.check() reports
is read as written.
Instruction tokens (e.g. X001, out(Y001)) are parsed into
Contact / Coil objects; wire tokens remain as strings.
When strict is False, unsupported AF instructions are silently
replaced with blank tokens instead of raising.
When unchecked is True, an instruction whose values its checks refuse
is read as written, the same way decode() reads a stored instruction.
A RefusedFieldWarning carries the refusals, and encode() still
refuses the instruction. A value that no stored instruction can hold still
raises: a timer unit that is none of CLICK's, a flag that is not 0 or 1, or
pin rows the box can't take. By default every refusal raises.
allow lists the codes of the refusals that you accept, such as
allow=["bank-not-allowed"]. Each item is a code's name or a Code. An
instruction keeps a refusal only if every error in it (FieldError.errors) has a
code in allow. Any other refusal raises, as it does by default. These refusals
raise whatever allow lists:
- a value that is not one of a field's named values, or a flag that is not 0 or 1;
- text that is not in CLICK's display form;
- a refusal of the rows of a box's pins;
- a refusal that a check raised because it crashed on the value.
read_csv keeps a refusal that allow lists only when laddercodec can write the
instruction and read it back the same. Otherwise the refusal raises, as it does by
default. A check that depends on a refused field does not run, so allow can let
through a value that such a check would refuse.
read_csv emits no RefusedFieldWarning for a refusal that allow lists.
encode(), write_csv and csv_rows write the instruction from its fields.
If you change a field with :func:laddercodec.replace, the copy is checked again. A
refused value that the copy still holds then raises, even if allow listed its code.
To build a changed instruction that keeps the refusal, call its constructor with
allow=. Each instruction's constructor accepts the same allow=.
A file that isn't UTF-8 text, or a row, token or rung that can't be read, raises
CsvReadError. A value that CLICK's dialog refuses raises FieldError, or
AddressError for an address. Each error carries a :class:CsvLocation as its
location, with the file, line, rung, row and column where they are known.
CsvLocation.of(exc) returns it, and the error message ends with it. When
unchecked is True or allow lists a code, each refusal that an instruction
keeps carries the location it would have raised with.
read_csv checks allow before it reads the file. It raises CsvReadError, with no
location, in these cases:
- an item is not a code's name;
- allow is a single string, bytes, or a value that you can't iterate over;
- you pass both
unchecked=Trueand a non-empty allow.
allow=None reads as no codes.
laddercodec.write_csv ¶
write_csv(
path: Path | str,
rungs: Iterable[Rung],
*,
index: bool = False,
stop: UndecodedStop = "end",
) -> None
Write decoded rungs to a canonical CSV file.
The file holds CSV_HEADER and then the rows that :func:csv_rows returns
for the same arguments. When laddercodec can lay out a rung, it is written as
CLICK's syntax check draws it. If CLICK would split a rung, the file holds the
rungs it splits into, so the file can hold more rungs than rungs. A rung
that has no layout is written with its cells where they are (see
:func:decoded_rung_to_rows).
No CSV token can hold the bytes of an unknown condition or instruction.
A rung that holds one is written as an undecoded marker rung, with an
UndecodedRungWarning. So is a rung that holds a compare whose cell
does not read back as that compare, such as "A"=="B" compared with
"C".
Parameters¶
path:
Output file path.
rungs:
Any iterable of decoded rungs, such as the list decode() returns.
index:
When True, each rung's R marker gets the rung's number, counted
from 1 across the whole file: R1, R2, R3 and so on. The
default, False, writes a plain R. read_csv() ignores the
digits, so an indexed file reads back the same.
stop:
Whether the marker that stands in for a rung with an unknown token acts as
end() or as return(). Pass "end" in the main program and
"return" in a subroutine.
Raises¶
CsvWriteError
If stop is neither "end" nor "return", or if a rung can't be
written, such as one whose shape the CSV can't hold. It is also raised
for a rung that needs more than the 32 rows of a CLICK rung, as
:func:csv_rows raises it. write_csv builds every row before it opens
path. If it raises CsvWriteError, it has not created or changed the file.
laddercodec.csv_rows ¶
csv_rows(
rungs: Iterable[Rung],
*,
index: bool = False,
stop: UndecodedStop = "end",
) -> list[list[str]]
Return the CSV rows that write_csv writes for rungs, without the header.
The file that write_csv(path, rungs) writes has the rows
[list(CSV_HEADER), *csv_rows(rungs)]. A data row is a list of 33 strings: the
marker, the cells of columns A to AE, and the AF cell. A comment row is
["#", text], with one line of the rung's comment in column A.
When laddercodec can lay out a rung, its rows are the rung as CLICK's syntax
check draws it. If CLICK would split a rung, the rows hold each rung that it
splits into, each with its own R row. A rung that has no layout keeps its
cells where they are (see :func:decoded_rung_to_rows).
No CSV token can hold the bytes of an unknown condition or instruction. A
rung that holds one becomes an undecoded marker rung, with an
UndecodedRungWarning.
Parameters¶
rungs:
Any iterable of decoded rungs, such as the list decode() returns.
index:
When True, each rung's R marker gets the rung's number, counted
from 1 across the whole call: R1, R2, R3 and so on. A rung
that CLICK would split gets one number for each rung it splits into. Each
call starts again at R1. To number the rungs of each program from
R1, call csv_rows once for the main program and once for each
subroutine. With
the default, False, each marker is a plain R. read_csv()
ignores the digits, so an indexed file reads back the same.
stop:
Whether the marker that stands in for a rung with an unknown token acts as
end() or as return(). Pass "end" in the main program and
"return" in a subroutine.
Raises¶
CsvWriteError
If stop is neither "end" nor "return", or if a rung can't be
written, such as one whose shape the CSV can't hold. It is also raised
for a rung that needs more than the 32 rows of a CLICK rung. The message
then starts with the rung's index in rungs, such as rungs[3]. The
error's code is layout-too-tall, and its __cause__ is a
LayoutError with the same code.
laddercodec.CSV_HEADER
module-attribute
¶
The header row of every Click Ladder CSV: marker, A to AE and AF.
laddercodec.read_bundle ¶
read_bundle(
directory: Path | str,
*,
strict: bool = True,
unchecked: bool = False,
allow: Iterable[str] = (),
) -> Project
Read the bundle in directory and return it as a Project.
A bundle is a directory that holds main.csv and, optionally, a subroutines/
folder with one <name>.csv file for each subroutine::
project = read_bundle("my_program")
project.main.rungs # list[Rung], from main.csv
project.subroutines[0].name # the first file's name, without .csv
The main program comes back as "Main Program", the name CLICK gives it, with
prog_idx 1. The subroutines are the files directly in subroutines/ whose
names end in .csv, in any case. Each subroutine is named after its file's
name without the last four characters, .csv. read_bundle sorts the
subroutines by name, ignoring case, and the order is the same on every operating
system. Their prog_idx values are 2, 3, 4 and so on, in that order.
read_bundle ignores every other file.
read_bundle reads each file as :func:~laddercodec.read_csv reads it, with the
same strict, unchecked and allow. When unchecked is True, each
RefusedFieldWarning names its program.
allow lists the codes of the refusals that you accept in every file, such as
allow=["bank-not-allowed"]. read_bundle keeps or raises each refusal as
read_csv does. It emits no RefusedFieldWarning for a refusal that it keeps
because allow lists its code.
Raises¶
CsvReadError
If allow holds an item that is not a code's name, if allow is a single string,
bytes or a value that you can't iterate over, or if you pass both
unchecked=True and a non-empty allow. read_bundle checks allow
before it reads any file, and this error has no location.
``CsvReadError`` is also raised if ``main.csv`` is missing, if a file can't be read, or
if the names of the files in ``subroutines/`` are refused. ``read_bundle`` checks
the names before it reads any file. It refuses a name that CLICK refuses as a
subroutine name, a name that starts or ends with whitespace, and two names that are
equal when the case of A-Z is ignored. For a name that CLICK refuses, the
``CsvReadError`` copies the ``FieldError``'s ``field``, ``code``, ``reason`` and
``click_id``. For two names that are equal when the case of A-Z is ignored, its
``code`` is
``duplicate-subroutine-name`` and its ``click_id`` is ``GUI-036``.
FieldError
If a file holds a value that CLICK's dialog refuses, as read_csv raises it.
It is an AddressError for an address.
Each error, except an error about allow, has a :class:~laddercodec.CsvLocation as
its location. The location's file is the file at fault. If main.csv is
missing, file is the path where main.csv should be.
laddercodec.write_bundle ¶
write_bundle(
directory: Path | str,
project: Project,
*,
index: bool = False,
strip: bool | Literal["mark"] = False,
) -> None
Write project to directory as a bundle that :func:read_bundle reads.
write_bundle writes these files and creates the directories that are missing::
<directory>/
main.csv the main program
subroutines/
<name>.csv one file for each subroutine
<name> is the subroutine's Program.name with the whitespace stripped from
both ends. write_bundle does not write project.main.name. read_bundle
names the main program "Main Program". write_bundle creates
subroutines/ even when the project has no subroutines. It replaces a file that
has the same name. It does not delete or change any other file in directory. A
file in subroutines/ from an earlier write stays there when project has no
subroutine of that name, and read_bundle reads it.
Each file holds what :func:~laddercodec.write_csv writes for the program's rungs.
main.csv is written with stop="end" and each subroutine with
stop="return". With index=True, each file numbers its rungs from R1.
With strip=True, write_bundle removes the text that laddercodec can find, or it
raises CsvWriteError and writes nothing. $hh codes stay, so check them before
you share the files. It does not change project. It writes no rung comment. It
renames the subroutines Sub1, Sub2 and so on, in the order of
project.subroutines, in the file names and in each Call. A Call to a subroutine
that is not in project gets the next unused number. Quoted text in a Copy, Fill,
Search or compare contact becomes x of the same length. The name of a Send or
Receive target becomes x, and its IP address becomes 0.0.0.0. The text of an
Email becomes x, if the Email's fields allow it. The reason of an undecoded marker
becomes fixed text. Ports, Slave IDs, addresses and numbers stay. It raises for a
RawInstruction (which includes an Email read from CSV), a Home, a PositionMove, a
VelocityMove, an instruction or condition that holds a value that laddercodec's checks
refuse, and a cell that holds a string other than a wire token, NOP or blank. A
rung with an unknown condition or instruction is not checked, because the writer puts a
marker rung in its place and writes none of its cells. The message names the program
and the rung, counted from 1. A file from an earlier write can still hold comments and
old names, so write to a new directory.
strip="mark" does the same, but it does not raise for a cell that it can't strip.
It writes an undecoded marker in place of the whole rung, and issues an
UndecodedRungWarning for each one. The marker names the instruction's class, or
says A cell for a string or a class that laddercodec does not have. It holds no
value from the cell. The marker rung has a comment with the same text. The marker
acts as an End in the main program and as a Return in a subroutine. The warning holds
the original name of the subroutine. encode() refuses the marker, so remove it
before you encode the rungs.
write_bundle does not write prog_idx, and the files have no order. When you
read the bundle back, read_bundle returns the subroutines sorted by name,
ignoring case, with prog_idx 2, 3, 4 and so on.
Raises¶
FieldError
If CLICK refuses a subroutine's name. The field is Program.name.
CsvWriteError
If two subroutines have names that are equal when the case of A-Z is ignored.
The error's code is then duplicate-subroutine-name, and its click_id
is GUI-036. It is also raised, with no code and no click_id, for two
names whose files would be one file on a file system that ignores case, such as
é1 and É1. It is raised for a name that holds a control character,
U+0000 to U+001F or U+007F, anywhere in the name. It is raised when
directory, subroutines/, main.csv or a subroutine's file exists and is
of the wrong kind, such as a directory named main.csv. write_bundle
also raises it for a rung that the CSV can't hold, as write_csv does. With
strip=True, it raises it for a cell that holds text that it can't replace.
write_bundle also raises CsvWriteError when strip is not True, False or
"mark".
write_bundle checks the names and the paths, and builds the rows of every file,
before it writes any file. If it raises FieldError or CsvWriteError, it has
not created or changed any file. The message of an error from a program's rungs
starts with the program: Main program: or Subroutine 'Pump':. An
OSError while it writes, such as a full disk, can leave some files written and
others not.
laddercodec.CsvLocation
dataclass
¶
The place in a CSV file of an error that read_csv raises, or of a refusal that
it keeps.
Every exception that read_csv raises for a bad CSV has a CsvLocation as its
location attribute. This is so for a CsvReadError, which is raised for a row or
token that read_csv can't read. It is also so for a FieldError or an
AddressError, which keeps its own class. :meth:of returns the location of an
exception. The message of each exception ends with (at <location>).
read_csv raises a csv.Error, or a UnicodeDecodeError for a file that isn't
UTF-8, as a CsvReadError with the same message. The original exception is its
__cause__. For a file that isn't UTF-8, the location holds only file.
A check can refuse a value while a box takes its pin rows. Examples are a .jump()
target, or a .reset() on a timer that can't be retentive. read_csv then raises a
CsvReadError that carries the data of the refusal. Each refusal in the errors of a
FieldError has its own location. Each field of the location is None where it is
not known or does not apply.
When read_csv reads with unchecked=True, an instruction keeps each refusal
instead of raising it. The refusal appears in the errors of a
:class:~laddercodec.RefusedFieldWarning. When read_csv reads with allow=, an
instruction keeps each refusal that allow= lists, and no warning is emitted. Each
kept refusal has the location that the default read would give it when it raised. Its
message does not end with the location.
Attributes¶
file:
The CSV file being read.
line:
The line of the CSV file that the bad row starts on. Lines are counted from 1, as an
editor counts them, and blank lines count. The header is line 1 only when no blank
line comes before it. It is None for an error about the whole file.
rung_line:
The line of the R row that starts the rung that holds the bad row, counted the
same way. It is None when the row is in no rung. The header and a comment row are
in no rung. So is a row that has no R row between it and the nearest comment row
or header above it.
row:
The index of the row within its rung, from 0. The R row is row 0, and the comment
rows above it are not counted. Rows are counted as they appear in the CSV file,
before laddercodec lays out the rung. It is None when rung_line is None.
If a check refuses the value that a pin row holds, the row is that pin row. If a pin
row is missing, the row is the box's row.
column:
The cell's column, counted from 0 as :class:laddercodec.Finding counts columns.
0 is A, 30 is AE and 31 is AF. It is None for an error about a whole
row or its marker. :attr:column_name returns the letters.