Metadata-Version: 2.5
Name: liquid-xml-objects-runtime
Version: 21.6.5
Summary: Liquid XML Objects runtime for Python: read and write XML as typed Python objects generated from an XSD.
Author: Liquid Technologies Ltd
License: AGPL-3.0-only OR Liquid Technologies License (see LICENSE.md and LICENSE-COMMERCIAL.md)
License-File: LICENSE-COMMERCIAL.md
License-File: LICENSE.md
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Text Processing :: Markup :: XML
Classifier: Typing :: Typed
Requires-Python: >=3.10
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: mypy>=1.8; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.4; extra == 'dev'
Requires-Dist: twine>=5; extra == 'dev'
Description-Content-Type: text/markdown

# Liquid XML Objects for Python

Read and write XML as typed Python objects. The classes are generated from an XSD, and the runtime (`liquid_xml_objects_runtime`) turns them into
XML and back again, validating the data against the schema (facets, cardinality, `xs:choice`, `xs:alternative`, `xsi:nil`, `xsi:type` ...).

This is a port of the C# `LiquidTechnologies.XmlObjects.Runtime`, the classes have the same names (in Python style) wherever that makes sense.

* Python 3.10+, no dependencies (it uses `xml.parsers.expat` from the standard library).
* Fully typed (`py.typed`), the runtime passes `mypy --strict`, and so does the generated code.

## Generating the classes

Use the Liquid XML Objects generator (`LxGen`) with `-L:Python`:

```
LxGen /Language:Python /OutputFolder:out /OutputNamespace:my_company.bookstore bookstore.xsd
```

| Argument                | Meaning                                                                                            |
| ----------------------- | -------------------------------------------------------------------------------------------------- |
| `/OutputNamespace`      | The package the classes are generated into (`my_company.bookstore` creates `my_company/bookstore`) |
| `/PythonOutput`         | `Project` (default) : a Python project built with setuptools, `HatchProject` : the same built with hatchling and hatch (see below), `VsCode` / `PyCharm` : the `Project` with the files that set it up in that IDE (see below), `Files` : just the package |
| `/PythonModuleName`     | The module inside the package that holds the classes (default `models`)                            |
| `/PythonProjectName`    | The name of the distribution in the `pyproject.toml`                                               |
| `/PythonProjectVersion` | The version of the distribution                                                                    |
| `/PythonProjectDescription` | A one line description of the project                                                          |
| `/PythonProjectAuthor`  | The author of the project                                                                          |
| `/GenerationModel`      | `Simple` (default), `Conformant` or `ConformantWithAccessors` (`Conformant` with read only properties, see below) |
| `/GenerateSample`       | Also writes `sample_usage.py`, a program that uses the classes : `python sample_usage.py in.xml out.xml` reads an XML file and writes it again, and it shows how to read, write and handle errors (next to the package for `Files`, in `tests/` for a project) |

### The Python project

`/PythonOutput:Project` (setuptools) and `/PythonOutput:HatchProject` (hatchling) build the standard Python environment around the generated package, using the usual tools:

| File                                       | What it is for                                                                                                               |
| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- |
| `src/<package>/`                           | The generated package (`src` layout), with `py.typed`                                                                        |
| `pyproject.toml`                           | Build configuration (setuptools), metadata, the dependency on the runtime, the `test`, `lint` and `dev` extras, and the configuration of pytest, ruff, mypy and coverage |
| `requirements.txt`, `requirements-dev.txt` | `pip install -r ...` for running the project, and for working on it                                                          |
| `tox.ini` (not `HatchProject`)                 | Tests on every supported Python, `lint` (ruff), `type` (mypy), `build` (`python -m build` and `twine check`). `HatchProject` has the same environments in the `pyproject.toml` instead (`hatch test`, `hatch run lint:check`, `hatch run types:check`, `hatch build`) |
| `tests/`                                   | pytest tests: checks on the package, and a round trip of every `.xml` file in `tests/data`                                   |
| `README.md`, `.gitignore`                  | How to set the project up, test, check and build it                                                                          |

The two differ in the `pyproject.toml` (`setuptools.build_meta` or `hatchling.build` as the build backend, with the configuration of that tool) and in how the environments are managed (tox, or hatch).
`pip install -e ".[dev]"` installs the project and the development tools, and with them the runtime (`pip install liquid-xml-objects-runtime`, which is imported as `liquid_xml_objects_runtime`).
The project depends on `liquid-xml-objects-runtime~=X.Y.0` (X.Y being the major and minor version of the generator, `~=21.6.0` is `>=21.6.0, ==21.6.*`, so pip installs the latest 21.6.x release that is available), because the runtime only works with code generated by the same major and minor version.
The tests that read and write XML need the license to be chosen with `LIQUID_XML_OBJECTS_LICENSE=agpl` (or `commercial`), otherwise they are skipped.

#### Visual Studio Code and PyCharm

`/PythonOutput:VsCode` and `/PythonOutput:PyCharm` write the same project as `Project` (setuptools, tox), and also the files that set it up in the IDE, so that it can be set up, built, tested and debugged from there:

| IDE                 | Files                    | What is in them |
| ------------------- | ------------------------ | --------------- |
| Visual Studio Code  | `.vscode/`               | `extensions.json` (the Python extensions), `settings.json` (pytest, `src` on the analysis path), `tasks.json` (`Setup project` creates `.venv` and runs `pip install -e ".[dev]"`; `Build package`, `Run tests`, `Lint`, `Type check` run the tools of `.venv`, on Windows and elsewhere) and `launch.json` (debug the open file, the tests and the sample) |
| PyCharm             | `.idea/`                 | the module (`src` is the source folder, `tests` the test folder run with pytest, `.venv` and the tool caches are excluded) and shared run configurations: `Install development dependencies`, `Build package`, `Run tests`, `Lint`, `Type check` and the sample |

The run / debug configuration of the sample (`Debug sample usage`, `Sample usage`) is only written with `/GenerateSample`. The files of the IDE are part of the project (committed), so the `.gitignore` does not ignore them (PyCharm's `workspace.xml` and other user specific files are). The README of the project describes how to use them.
PyCharm keeps the interpreters in its own settings: add the `.venv` of the project (*Settings > Project > Python Interpreter*) once, then run `Install development dependencies`.

All the schemas are generated into a single module (a base class has to be declared before the classes derived from it, and schemas often refer
to each other). The package exports every class (`__all__`).

## Registering the license

The library can not be used until you have registered the license it is used under. Call one of these once, when your program starts (before
the first `serialize` / `deserialize`), otherwise a `LxLicenseException` is raised that explains what to do and summarizes the AGPL terms:

```python
import liquid_xml_objects_runtime

# Open source use, under the terms of the GNU Affero General Public License v3 (AGPL-3.0)
liquid_xml_objects_runtime.register_liquid_xml_object_license_agpl()

# or, with a commercial license
liquid_xml_objects_runtime.register_liquid_xml_object_license_commercial("My Company Ltd", "<license key>")
```

## Using the classes

```python
from liquid_xml_objects_runtime import LxSerializer
import my_company.bookstore as bookstore

serializer = LxSerializer(bookstore)

company = serializer.deserialize("company.xml")
for book in company.catalog.books:
    print(book.title, book.isbn)

company.catalog.books.append(bookstore.BookElm(isbn="0-123", title="A new book", author="Me", sku=1))
serializer.serialize(company, "copy.xml")
```

* `LxSerializer(module)` registers the generated classes of a package (or the loaded generated classes if it is given nothing).
* `deserialize` / `deserialize_from_string` / `deserialize_with_root_name` read a file, a stream, bytes, an `XElement` or an `XmlReader`.
* `serialize` / `serialize_to_string` / `serialize_to_x_element` write a file, a stream or an `XmlWriter`. An object that is based on an
  `xs:complexType` (rather than a global `xs:element`) needs `element_name=` as well.
* `LxTypedSerializer[T]` is the same, with the type of the root object.

### Errors

By default a problem in the XML (or in the object being written) raises `LxSerializationException`. Give the settings an error handler to
collect the errors and carry on, the handler is called with `(message, severity, error_code, location, target_object)` when reading and
`(message, severity, error_code, target_object)` when writing:

```python
from liquid_xml_objects_runtime import LxReaderSettings

errors = []
settings = LxReaderSettings()
settings.error_handler = lambda message, severity, code, location, target: errors.append((code, message))
obj = serializer.deserialize("damaged.xml", settings)
```

### The ConformantWithAccessors model

`ConformantWithAccessors` is the `Conformant` model (a field for each compositor, which holds the elements) with a read only property added to the class for each
element, which follows the compositors to the element :

```python
@property
def names(self) -> list[str]:
    result: list[str] = []
    v1 = self.seq
    if v1 is not None:
        result.extend(v1.names)
    return result
```

An element that is required gives its value, one that is optional (or is in something that is) gives `None` if it is not there, one that is repeated (or is in something that
is) gives a new `list`. An element that is in more than one place (the class and a class it derives from both have it) is returned from all of them, the class itself first.

### What the generated code looks like

```python
@lx.simple_element_definition("Bookstore", NS, lx.ElementScopeType.GLOBAL_ELEMENT)
@dataclass(kw_only=True)
class BookstoreElm:
    name: str = lx.element_value(0, "Name", NS, lx.LxValueType.VALUE, lx.XsdType.STRING, initial="")
    rating: Decimal | None = lx.element_value(4, "Rating", NS, lx.LxValueType.VALUE, lx.XsdType.DECIMAL, min_occurs=0, initial=None)
    books: list[BookElm] = lx.element_ref(1, lambda: BookElm, min_occurs=0, max_occurs=UNBOUNDED, initial_factory=list)
```

* The classes are `dataclass(kw_only=True)`, the properties are fields. The field carries what the C# attributes carry (`attribution/attributes.py`).
* Names are Pythonic : `snake_case` properties, `UPPER_SNAKE_CASE` enumeration members (the value is the text used in the XML), a name that is a keyword
  or builtin gets a trailing `_` (`class_`).

| XSD                                        | Python                                                              |
| ------------------------------------------ | ------------------------------------------------------------------- |
| `xs:string` and the like                   | `str`                                                               |
| integers                                   | `int`                                                               |
| `xs:float`, `xs:double`                    | `float`                                                             |
| `xs:decimal`                               | `decimal.Decimal`                                                   |
| `xs:boolean`                               | `bool`                                                              |
| `xs:base64Binary`, `hexBinary`             | `bytes`                                                             |
| `xs:date`, `dateTime`, `time`, `gYear` ... | `LxDateTime` (the type says which of them it holds)                 |
| `xs:duration` ...                          | `LxDuration`                                                        |
| `xs:QName`                                 | `LxQName`                                                           |
| `xs:list`                                  | `list[...]`                                                         |
| enumeration                                | an `enum.Enum`                                                      |
| `xs:union`                                 | a subclass of `LxUnion`, `.value` holds the value                   |
| optional element/attribute                 | `T \| None`                                                         |
| `maxOccurs > 1`                            | `list[T]`                                                           |
| `nillable`                                 | `LxNillable[T]` (`.value`, `.is_nil`)                               |
| `xs:any`, `xs:anyType`                     | `XElement` / `XAttribute` (the runtime's own light weight xml tree) |

## Differences from the C# runtime

* The values of `xs:float`/`xs:double` are Python floats. They are written as .NET Core 3.0 and later write them, and as the Java and C++ runtimes do : the shortest text that
  reads back as exactly the same number (`1/3` is `0.3333333333333333`, a float of `1.2345612` is `1.2345612`), plain digits unless the exponent is less than -4 or more than 16
  (`1E-05`, `1E+17`; 8 for an `xs:float`), and `-0` for negative zero. A pattern (`float_format_override`, `double_format_override`) can ask for something else (`G7`, `F2` ...).
* The `Simple` generation model does not keep the order of elements with different names, nor enforce cardinality (as in C#). The
  `Conformant` model does.
* The JSON serializer is not ported.
* Change notification (`RaiseChangeEvents`) is not generated, use `dataclasses` features or `__setattr__` if you need it.
* Some forms of recursive schema are not supported (elm A=> seq => ref to elmA)

