Type Hints, Dataclasses and Domain Objects

by Giux GX-TXT, python-en, scripts-en 2 min read

Scientific Python in GX-TXT · Module 9 · Lesson 50

A small Python object can collect the identity of a Dataset and the variables to use, making the code clearer. The authoritative source of the scheme remains GX-TXT: the Python object describes a request, does not replace the Dataset.

Objectives

  • Use type annotations and dataclass.
  • Define runtime controlled variables in __post_init__.
  • Ask the description of a real Dataset.
  • Distinguish a type suggestion from validation of values.

Execution

At the corso_python Session, import dataset_reference.py, save the script and run it in the Runner.

Reference dataclass in the GX-TXT editor.
Reference dataclass in the GX-TXT editor.
from dataclasses import dataclass, asdict
from typing import Optional
from gxtxt import gxtxt_api_call, gxtxt_api_require

@dataclass(frozen=True)
class DatasetReference:
    dataset_id: str
    variables: tuple[str, ...]
    description: Optional[str] = None
    def __post_init__(self):
        if not self.dataset_id.strip() or not self.variables:
            raise ValueError("Need ID and at least one variable")

gxtxt_api_require("CANONICAL_DATASET_API_v2@2")
reference = DatasetReference("corso_python_serie_sintetica", ("tempo", "segnale"), "Synthetic")
schema = gxtxt_api_call("CANONICAL_DATASET_API_v2", "describe", [reference.dataset_id])
print("Riferimento:", asdict(reference))
print("Description available:", bool(schema))
try:
    DatasetReference("", ())
except ValueError as caught_error:
    print("Input not valid refused:", caught_error)

@dataclass generates useful methods for a class that collects data; frozen=True prevents ordinary reassigning of fields after creation. dataset_id: str and variables: tuple[str, ...] describe the expected types. Optional[str] allows a text description or None. asdict produces a Python dictionary; for an exchange format it is necessary to choose and document an appropriate serialization.

The annotations do not automatically control the values during the execution. __post_init__ adds explicit control here: an empty ID or no variable raises ValueError. This does not verify that the IDs exist: to know the actual Dataset we use CANONICAL_DATASET_API_v2/describe and, in a complete program, we also compare the IDs of the variables required with the scheme.

Output showing the reference, the available description and rejection of empty input.
Output showing the reference, the available description and rejection of empty input.

Exercise

  1. What happens if you create a reference with empty ID?
  2. Does a str annotation guarantee on its own that the ID exists in Session?
  3. Why read the pattern from GX-TXT instead of assuming that the local object is the authoritative source?

Worked solution

  1. The control in __post_init__ raises ValueError.
  2. No: describes an expected type, but does not question the catalog or automatically validate the value.
  3. The canon scheme and variables belong to the Dataset managed by GX-TXT; a local object can be incomplete or not updated.

In the next lesson, we will read block data through a stream.

Download the Module 9 scripts (ZIP)

#Debugging #GX-TXT #Python

Other steps of this project

Leave a Reply

Your email address will not be published. Required fields are marked *