Skip to content

EagerPolarsDataset

EagerPolarsDataset loads and saves data using Polars in eager execution mode.

kedro_datasets.polars.EagerPolarsDataset

EagerPolarsDataset(
    *,
    filepath,
    file_format,
    load_args=None,
    save_args=None,
    version=None,
    credentials=None,
    fs_args=None,
    metadata=None
)

Bases: AbstractVersionedDataset[DataFrame, DataFrame]

polars.EagerPolarsDataset loads/saves data from/to a data file using an underlying filesystem (e.g.: local, S3, GCS). It uses polars to handle the dynamically select the appropriate type of read/write on a best effort basis.

Examples:

Using the YAML API:

cars:
  type: polars.EagerPolarsDataset
  file_format: parquet
  filepath: s3://data/01_raw/company/cars.parquet
  load_args:
    low_memory: True
  save_args:
    compression: "snappy"

Using the Python API:

>>> import polars as pl
>>> from kedro_datasets.polars import EagerPolarsDataset
>>>
>>> data = pl.DataFrame({"col1": [1, 2], "col2": [4, 5], "col3": [5, 6]})
>>>
>>> dataset = EagerPolarsDataset(filepath=tmp_path / "test.parquet", file_format="parquet")
>>> dataset.save(data)
>>> reloaded = dataset.load()
>>> assert data.equals(reloaded)

identified by string matching on a best effort basis.

Parameters:

  • filepath (str) –

    Filepath in POSIX format to a file prefixed with a protocol like s3://. If prefix is not provided, file protocol (local filesystem) will be used. The prefix should be any protocol supported by fsspec. Key assumption: The first argument of either load/save method points to a filepath/buffer/io type location. There are some read/write targets such as 'clipboard' or 'records' that will fail since they do not take a filepath like argument.

  • file_format (str) –

    String which is used to match the appropriate load/save method on a best effort basis. For example if 'csv' is passed, the polars.read_csv and polars.DataFrame.write_csv methods will be identified. An error will be raised unless there is at least one matching read_<file_format> or write_<file_format>.

  • load_args (dict[str, Any] | None, default: None ) –

    Polars options for loading CSV files. Here you can find all available arguments: https://pola-rs.github.io/polars/py-polars/html/reference/io.html All defaults are preserved.

  • save_args (dict[str, Any] | None, default: None ) –

    Polars options for saving files. Here you can find all available arguments: https://pola-rs.github.io/polars/py-polars/html/reference/io.html All defaults are preserved.

  • version (Version | None, default: None ) –

    If specified, should be an instance of kedro.io.core.Version. If its load attribute is None, the latest version will be loaded. If its save attribute is None, save version will be autogenerated.

  • credentials (dict[str, Any] | None, default: None ) –

    Credentials required to get access to the underlying filesystem. E.g. for GCSFileSystem it should look like {"token": None}.

  • fs_args (dict[str, Any] | None, default: None ) –

    Extra arguments to pass into underlying filesystem class constructor (e.g. {"project": "my-project"} for GCSFileSystem).

  • metadata (dict[str, Any] | None, default: None ) –

    Any arbitrary metadata. This is ignored by Kedro, but may be consumed by users or external plugins.

Raises: DatasetError: Will be raised if at least less than one appropriate read or write methods are identified.

Source code in kedro_datasets/polars/eager_polars_dataset.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def __init__(  # noqa: PLR0913
    self,
    *,
    filepath: str,
    file_format: str,
    load_args: dict[str, Any] | None = None,
    save_args: dict[str, Any] | None = None,
    version: Version | None = None,
    credentials: dict[str, Any] | None = None,
    fs_args: dict[str, Any] | None = None,
    metadata: dict[str, Any] | None = None,
):
    """Creates a new instance of ``EagerPolarsDataset`` pointing to a concrete data file
    on a specific filesystem. The appropriate polars load/save methods are dynamically
    identified by string matching on a best effort basis.

    Args:
        filepath: Filepath in POSIX format to a file prefixed with a protocol like
            `s3://`.
            If prefix is not provided, `file` protocol (local filesystem)
            will be used.
            The prefix should be any protocol supported by ``fsspec``.
            Key assumption: The first argument of either load/save method points to
            a filepath/buffer/io type location. There are some read/write targets such
            as 'clipboard' or 'records' that will fail since they do not take a filepath
            like argument.
        file_format: String which is used to match the appropriate load/save method on a
            best effort basis. For example if 'csv' is passed, the `polars.read_csv` and
            `polars.DataFrame.write_csv` methods will be identified. An error will
            be raised unless there is at least one matching `read_<file_format>`
            or `write_<file_format>`.
        load_args: Polars options for loading CSV files.
            Here you can find all available arguments:
            https://pola-rs.github.io/polars/py-polars/html/reference/io.html
            All defaults are preserved.
        save_args: Polars options for saving files.
            Here you can find all available arguments:
            https://pola-rs.github.io/polars/py-polars/html/reference/io.html
            All defaults are preserved.
        version: If specified, should be an instance of
            ``kedro.io.core.Version``. If its ``load`` attribute is
            None, the latest version will be loaded. If its ``save``
            attribute is None, save version will be autogenerated.
        credentials: Credentials required to get access to the underlying filesystem.
            E.g. for ``GCSFileSystem`` it should look like `{"token": None}`.
        fs_args: Extra arguments to pass into underlying filesystem class constructor
            (e.g. `{"project": "my-project"}` for ``GCSFileSystem``).
        metadata: Any arbitrary metadata.
            This is ignored by Kedro, but may be consumed by users or external plugins.
    Raises:
        DatasetError: Will be raised if at least less than one appropriate read or write
            methods are identified.
    """

    self._file_format = file_format.lower()

    _fs_args = deepcopy(fs_args) or {}
    _fs_open_args_load = _fs_args.pop("open_args_load", {})
    _fs_open_args_save = _fs_args.pop("open_args_save", {})
    _credentials = deepcopy(credentials) or {}

    protocol, path = get_protocol_and_path(filepath)
    if protocol == "file":
        _fs_args.setdefault("auto_mkdir", True)

    self._protocol = protocol
    self._fs = fsspec.filesystem(self._protocol, **_credentials, **_fs_args)
    self.metadata = metadata

    super().__init__(
        filepath=PurePosixPath(path),
        version=version,
        exists_function=self._fs.exists,
        glob_function=self._fs.glob,
    )

    self._load_args = deepcopy(self.DEFAULT_LOAD_ARGS)
    if load_args is not None:
        self._load_args.update(load_args)
    self._save_args = deepcopy(self.DEFAULT_SAVE_ARGS)
    if save_args is not None:
        self._save_args.update(save_args)

    _fs_open_args_save.setdefault("mode", "wb")
    self._fs_open_args_load = _fs_open_args_load
    self._fs_open_args_save = _fs_open_args_save

DEFAULT_LOAD_ARGS class-attribute instance-attribute

DEFAULT_LOAD_ARGS = {}

DEFAULT_SAVE_ARGS class-attribute instance-attribute

DEFAULT_SAVE_ARGS = {}

_file_format instance-attribute

_file_format = lower()

_fs instance-attribute

_fs = filesystem(_protocol, **_credentials, **_fs_args)

_fs_open_args_load instance-attribute

_fs_open_args_load = _fs_open_args_load

_fs_open_args_save instance-attribute

_fs_open_args_save = _fs_open_args_save

_load_args instance-attribute

_load_args = deepcopy(DEFAULT_LOAD_ARGS)

_protocol instance-attribute

_protocol = protocol

_save_args instance-attribute

_save_args = deepcopy(DEFAULT_SAVE_ARGS)

metadata instance-attribute

metadata = metadata

_describe

_describe()
Source code in kedro_datasets/polars/eager_polars_dataset.py
187
188
189
190
191
192
193
194
195
def _describe(self) -> dict[str, Any]:
    return {
        "file_format": self._file_format,
        "filepath": self._filepath,
        "protocol": self._protocol,
        "load_args": self._load_args,
        "save_args": self._save_args,
        "version": self._version,
    }

_exists

_exists()
Source code in kedro_datasets/polars/eager_polars_dataset.py
179
180
181
182
183
184
185
def _exists(self) -> bool:
    try:
        load_path = get_filepath_str(self._get_load_path(), self._protocol)
    except DatasetError:
        return False

    return self._fs.exists(load_path)

_invalidate_cache

_invalidate_cache()

Invalidate underlying filesystem caches.

Source code in kedro_datasets/polars/eager_polars_dataset.py
201
202
203
204
def _invalidate_cache(self) -> None:
    """Invalidate underlying filesystem caches."""
    filepath = get_filepath_str(self._filepath, self._protocol)
    self._fs.invalidate_cache(filepath)

_release

_release()
Source code in kedro_datasets/polars/eager_polars_dataset.py
197
198
199
def _release(self) -> None:
    super()._release()
    self._invalidate_cache()

load

load()
Source code in kedro_datasets/polars/eager_polars_dataset.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def load(self) -> pl.DataFrame:
    load_path = get_filepath_str(self._get_load_path(), self._protocol)
    load_method = getattr(pl, f"read_{self._file_format}", None)

    if not load_method:
        raise DatasetError(
            f"Unable to retrieve 'polars.read_{self._file_format}' method, please"
            " ensure that your "
            "'file_format' parameter has been defined correctly as per the Polars"
            " API"
            " https://pola-rs.github.io/polars/py-polars/html/reference/io.html"
        )
    with self._fs.open(load_path, **self._fs_open_args_load) as fs_file:
        return load_method(fs_file, **self._load_args)

save

save(data)
Source code in kedro_datasets/polars/eager_polars_dataset.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def save(self, data: pl.DataFrame) -> None:
    save_path = get_filepath_str(self._get_save_path(), self._protocol)
    save_method = getattr(data, f"write_{self._file_format}", None)

    if not save_method:
        raise DatasetError(
            f"Unable to retrieve 'polars.DataFrame.write_{self._file_format}' "
            "method, please "
            "ensure that your 'file_format' parameter has been defined correctly as"
            " per the Polars API "
            "https://pola-rs.github.io/polars/py-polars/html/reference/io.html"
        )
    buf = BytesIO()
    save_method(buf, **self._save_args)
    with self._fs.open(save_path, **self._fs_open_args_save) as fs_file:
        fs_file.write(buf.getvalue())
        self._invalidate_cache()