Skip to content

Session

kedro.framework.session

kedro.framework.session provides access to KedroSession responsible for project lifecycle.

Module Description
AbstractSession Base class for all Kedro session implementations.
KedroSession Implements Kedro session responsible for project lifecycle.
KedroServiceSession Implements Kedro service session responsible for project lifecycle.
BaseSessionStore Implements a dict-like store object used to persist Kedro sessions.
KedroSessionError Raised by KedroSession and KedroServiceSession when they encounter an error.

kedro.framework.session.abstract_session.AbstractSession

Bases: ABC

AbstractSession is the base class for all Kedro session implementations.

Subclasses must implement the create, close, and run methods.

__enter__

__enter__()
Source code in kedro/framework/session/abstract_session.py
33
34
def __enter__(self) -> AbstractSession:
    return self

__exit__

__exit__(_exc_type, _exc_value, _tb)
Source code in kedro/framework/session/abstract_session.py
36
37
def __exit__(self, _exc_type: Any, _exc_value: Any, _tb: Any) -> None:
    self.close()

close abstractmethod

close()

Close the current session.

Source code in kedro/framework/session/abstract_session.py
23
24
25
26
@abstractmethod
def close(self) -> None:
    """Close the current session."""
    ...

create abstractmethod classmethod

create()

Create a new instance of the session.

Source code in kedro/framework/session/abstract_session.py
15
16
17
18
19
20
21
@classmethod
@abstractmethod
def create(
    cls,
) -> AbstractSession:
    """Create a new instance of the session."""
    ...

run abstractmethod

run()

Run the pipeline.

Source code in kedro/framework/session/abstract_session.py
28
29
30
31
@abstractmethod
def run(self) -> dict[str, Any]:
    """Run the pipeline."""
    ...

kedro.framework.session.session.KedroSession

KedroSession(session_id, package_name=None, project_path=None, save_on_close=False, conf_source=None)

Bases: AbstractSession

KedroSession is the object that is responsible for managing the lifecycle of a Kedro run. Use KedroSession.create() as a context manager to construct a new KedroSession with session data provided (see the example below).

Example:

from kedro.framework.session import KedroSession
from kedro.framework.startup import bootstrap_project
from pathlib import Path

# If you are creating a session outside of a Kedro project (i.e. not using
# `kedro run` or `kedro jupyter`), you need to run `bootstrap_project` to
# let Kedro find your configuration.
bootstrap_project(Path("<project_root>"))
with KedroSession.create() as session:
    session.run()

Source code in kedro/framework/session/session.py
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
def __init__(
    self,
    session_id: str,
    package_name: str | None = None,
    project_path: Path | str | None = None,
    save_on_close: bool = False,
    conf_source: str | None = None,
):
    self._project_path = Path(
        project_path or find_kedro_project(Path.cwd()) or Path.cwd()
    ).resolve()
    self.session_id = session_id
    self.save_on_close = save_on_close
    self._package_name = package_name or kedro_project.PACKAGE_NAME
    self._store = self._init_store()
    self._run_called = False

    hook_manager = _create_hook_manager()
    _register_hooks(hook_manager, settings.HOOKS)
    _register_hooks_entry_points(hook_manager, settings.DISABLE_HOOKS_FOR_PLUGINS)
    self._hook_manager = hook_manager

    self._conf_source = conf_source or str(
        self._project_path / settings.CONF_SOURCE
    )

_conf_source instance-attribute

_conf_source = conf_source or str(_project_path / CONF_SOURCE)

_hook_manager instance-attribute

_hook_manager = hook_manager

_logger property

_logger

_package_name instance-attribute

_package_name = package_name or PACKAGE_NAME

_project_path instance-attribute

_project_path = resolve()

_run_called instance-attribute

_run_called = False

_store instance-attribute

_store = _init_store()

save_on_close instance-attribute

save_on_close = save_on_close

session_id instance-attribute

session_id = session_id

store property

store

Return a copy of internal store.

__exit__

__exit__(exc_type, exc_value, tb_)
Source code in kedro/framework/session/session.py
269
270
271
272
def __exit__(self, exc_type: Any, exc_value: Any, tb_: Any) -> None:
    if exc_type:
        self._log_exception(exc_type, exc_value, tb_)
    self.close()

_get_config_loader

_get_config_loader()

An instance of the config loader.

Source code in kedro/framework/session/session.py
249
250
251
252
253
254
255
256
257
258
259
260
def _get_config_loader(self) -> AbstractConfigLoader:
    """An instance of the config loader."""
    env = self.store.get("env")
    runtime_params = self.store.get("runtime_params")

    config_loader_class = settings.CONFIG_LOADER_CLASS
    return config_loader_class(  # type: ignore[no-any-return]
        conf_source=self._conf_source,
        env=env,
        runtime_params=runtime_params,
        **settings.CONFIG_LOADER_ARGS,
    )

_init_store

_init_store()
Source code in kedro/framework/session/session.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def _init_store(self) -> BaseSessionStore:
    store_class = settings.SESSION_STORE_CLASS
    classpath = f"{store_class.__module__}.{store_class.__qualname__}"
    store_args = deepcopy(settings.SESSION_STORE_ARGS)
    store_args.setdefault("path", (self._project_path / "sessions").as_posix())
    store_args["session_id"] = self.session_id

    try:
        return store_class(**store_args)  # type: ignore[no-any-return]
    except TypeError as err:
        raise ValueError(
            f"\n{err}.\nStore config must only contain arguments valid "
            f"for the constructor of '{classpath}'."
        ) from err
    except Exception as err:
        raise ValueError(
            f"\n{err}.\nFailed to instantiate session store of type '{classpath}'."
        ) from err

_log_exception

_log_exception(exc_type, exc_value, exc_tb)
Source code in kedro/framework/session/session.py
211
212
213
214
215
216
217
218
219
220
def _log_exception(self, exc_type: Any, exc_value: Any, exc_tb: Any) -> None:
    type_ = [] if exc_type.__module__ == "builtins" else [exc_type.__module__]
    type_.append(exc_type.__qualname__)

    exc_data = {
        "type": ".".join(type_),
        "value": str(exc_value),
        "traceback": traceback.format_tb(exc_tb),
    }
    self._store["exception"] = exc_data

close

close()

Close the current session and save its store to disk if save_on_close attribute is True.

Source code in kedro/framework/session/session.py
262
263
264
265
266
267
def close(self) -> None:
    """Close the current session and save its store to disk
    if `save_on_close` attribute is True.
    """
    if self.save_on_close:
        self._store.save()

create classmethod

create(project_path=None, save_on_close=True, env=None, runtime_params=None, conf_source=None)

Create a new instance of KedroSession with the session data.

Parameters:

  • project_path (Path | str | None, default: None ) –

    Path to the project root directory. Default is current working directory Path.cwd().

  • save_on_close (bool, default: True ) –

    Whether or not to save the session when it's closed.

  • conf_source (str | None, default: None ) –

    Path to a directory containing configuration

  • env (str | None, default: None ) –

    Environment for the KedroContext.

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

    Optional dictionary containing extra project parameters for underlying KedroContext. If specified, will update (and therefore take precedence over) the parameters retrieved from the project configuration.

Returns:

Source code in kedro/framework/session/session.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
@classmethod
def create(
    cls,
    project_path: Path | str | None = None,
    save_on_close: bool = True,
    env: str | None = None,
    runtime_params: dict[str, Any] | None = None,
    conf_source: str | None = None,
) -> KedroSession:
    """Create a new instance of ``KedroSession`` with the session data.

    Args:
        project_path: Path to the project root directory. Default is
            current working directory Path.cwd().
        save_on_close: Whether or not to save the session when it's closed.
        conf_source: Path to a directory containing configuration
        env: Environment for the KedroContext.
        runtime_params: Optional dictionary containing extra project parameters
            for underlying KedroContext. If specified, will update (and therefore
            take precedence over) the parameters retrieved from the project
            configuration.

    Returns:
        A new ``KedroSession`` instance.
    """
    validate_settings()

    session = cls(
        project_path=project_path,
        session_id=generate_timestamp(),
        save_on_close=save_on_close,
        conf_source=conf_source,
    )

    # have to explicitly type session_data otherwise mypy will complain
    # possibly related to this: https://github.com/python/mypy/issues/1430
    session_data: dict[str, Any] = {
        "project_path": session._project_path,
        "session_id": session.session_id,
    }

    ctx = click.get_current_context(silent=True)
    if ctx:
        session_data["cli"] = _jsonify_cli_context(ctx)

    env = env or os.getenv("KEDRO_ENV")
    if env:
        session_data["env"] = env

    if runtime_params:
        session_data["runtime_params"] = runtime_params

    try:
        session_data["username"] = getpass.getuser()
    except Exception as exc:
        logging.getLogger(__name__).debug(
            "Unable to get username. Full exception: %s", exc
        )

    session_data.update(**_describe_git(session._project_path))
    session._store.update(session_data)

    return session

load_context

load_context()

An instance of the project context.

Source code in kedro/framework/session/session.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
def load_context(self) -> KedroContext:
    """An instance of the project context."""
    env = self.store.get("env")
    runtime_params = self.store.get("runtime_params")
    config_loader = self._get_config_loader()
    context_class = settings.CONTEXT_CLASS
    context = context_class(
        package_name=self._package_name,
        project_path=self._project_path,
        config_loader=config_loader,
        env=env,
        runtime_params=runtime_params,
        hook_manager=self._hook_manager,
    )
    self._hook_manager.hook.after_context_created(context=context)

    return context  # type: ignore[no-any-return]

run

run(pipeline_name=None, pipeline_names=None, tags=None, runner=None, node_names=None, from_nodes=None, to_nodes=None, from_inputs=None, to_outputs=None, load_versions=None, namespaces=None, only_missing_outputs=False)

Runs the pipeline with a specified runner.

Parameters:

  • pipeline_name (str | None, default: None ) –

    Name of the pipeline that is being run.

  • pipeline_names (list[str] | None, default: None ) –

    Name of the pipelines that is being run.

  • tags (Iterable[str] | None, default: None ) –

    An optional list of node tags which should be used to filter the nodes of the Pipeline. If specified, only the nodes containing any of these tags will be run.

  • runner (AbstractRunner | None, default: None ) –

    An optional parameter specifying the runner that you want to run the pipeline with.

  • node_names (Iterable[str] | None, default: None ) –

    An optional list of node names which should be used to filter the nodes of the Pipeline. If specified, only the nodes with these names will be run.

  • from_nodes (Iterable[str] | None, default: None ) –

    An optional list of node names which should be used as a starting point of the new Pipeline.

  • to_nodes (Iterable[str] | None, default: None ) –

    An optional list of node names which should be used as an end point of the new Pipeline.

  • from_inputs (Iterable[str] | None, default: None ) –

    An optional list of input datasets which should be used as a starting point of the new Pipeline.

  • to_outputs (Iterable[str] | None, default: None ) –

    An optional list of output datasets which should be used as an end point of the new Pipeline.

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

    An optional flag to specify a particular dataset version timestamp to load.

  • namespaces (Iterable[str] | None, default: None ) –

    The namespaces of the nodes that are being run.

  • only_missing_outputs (bool, default: False ) –

    Run only nodes with missing outputs.

Raises: ValueError: If the named or __default__ pipeline is not defined by register_pipelines. Exception: Any uncaught exception during the run will be re-raised after being passed to on_pipeline_error hook. KedroSessionError: If more than one run is attempted to be executed during a single session. Returns: Dictionary with pipeline outputs, where keys are dataset names and values are dataset objects.

Source code in kedro/framework/session/session.py
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
def run(  # noqa: PLR0913
    self,
    pipeline_name: str | None = None,
    pipeline_names: list[str] | None = None,
    tags: Iterable[str] | None = None,
    runner: AbstractRunner | None = None,
    node_names: Iterable[str] | None = None,
    from_nodes: Iterable[str] | None = None,
    to_nodes: Iterable[str] | None = None,
    from_inputs: Iterable[str] | None = None,
    to_outputs: Iterable[str] | None = None,
    load_versions: dict[str, str] | None = None,
    namespaces: Iterable[str] | None = None,
    only_missing_outputs: bool = False,
) -> dict[str, Any]:
    """Runs the pipeline with a specified runner.

    Args:
        pipeline_name: Name of the pipeline that is being run.
        pipeline_names: Name of the pipelines that is being run.
        tags: An optional list of node tags which should be used to
            filter the nodes of the ``Pipeline``. If specified, only the nodes
            containing *any* of these tags will be run.
        runner: An optional parameter specifying the runner that you want to run
            the pipeline with.
        node_names: An optional list of node names which should be used to
            filter the nodes of the ``Pipeline``. If specified, only the nodes
            with these names will be run.
        from_nodes: An optional list of node names which should be used as a
            starting point of the new ``Pipeline``.
        to_nodes: An optional list of node names which should be used as an
            end point of the new ``Pipeline``.
        from_inputs: An optional list of input datasets which should be
            used as a starting point of the new ``Pipeline``.
        to_outputs: An optional list of output datasets which should be
            used as an end point of the new ``Pipeline``.
        load_versions: An optional flag to specify a particular dataset
            version timestamp to load.
        namespaces: The namespaces of the nodes that are being run.
        only_missing_outputs: Run only nodes with missing outputs.
    Raises:
        ValueError: If the named or `__default__` pipeline is not
            defined by `register_pipelines`.
        Exception: Any uncaught exception during the run will be re-raised
            after being passed to ``on_pipeline_error`` hook.
        KedroSessionError: If more than one run is attempted to be executed during
            a single session.
    Returns:
        Dictionary with pipeline outputs, where keys are dataset names
        and values are dataset objects.
    """
    # Report project name
    project_name = self._package_name or self._project_path.name
    self._logger.info("Kedro project %s", project_name)
    if pipeline_name:
        self._logger.warning(
            "`pipeline_name` is deprecated and will be removed in a future release. "
            "Please use `pipeline_names` instead."
        )
        pipeline_names = [pipeline_name]

    if self._run_called:
        raise KedroSessionError(
            "A run has already been completed as part of the"
            " active KedroSession. KedroSession has a 1-1 mapping with"
            " runs, and thus only one run should be executed per session."
        )

    session_id = self.store["session_id"]
    save_version = session_id
    runtime_params = self.store.get("runtime_params") or {}
    context = self.load_context()

    names = pipeline_names or ["__default__"]
    combined_pipelines = Pipeline([])
    for name in names:
        try:
            combined_pipelines += pipelines[name]
        except KeyError as exc:
            matches = get_close_matches(name, pipelines.keys())
            if matches:
                suggestion = (
                    "Did you mean one of these instead?\n"
                    + textwrap.indent("\n".join(matches), " " * 4)
                )
            else:
                suggestion = ""
            raise ValueError(
                f"Failed to find the pipeline named '{name}'. "
                f"It needs to be generated and returned "
                f"by the 'register_pipelines' function. "
                f"{suggestion}"
            ) from exc

    filtered_pipeline = combined_pipelines.filter(
        tags=tags,
        from_nodes=from_nodes,
        to_nodes=to_nodes,
        node_names=node_names,
        from_inputs=from_inputs,
        to_outputs=to_outputs,
        node_namespaces=namespaces,
    )

    record_data = {
        "run_id": session_id,
        "project_path": self._project_path.as_posix(),
        "env": context.env,
        "kedro_version": kedro_version,
        "tags": tags,
        "from_nodes": from_nodes,
        "to_nodes": to_nodes,
        "node_names": node_names,
        "from_inputs": from_inputs,
        "to_outputs": to_outputs,
        "load_versions": load_versions,
        "runtime_params": runtime_params,
        "pipeline_names": pipeline_names,
        "namespaces": namespaces,
        "runner": getattr(runner, "__name__", str(runner)),
        "only_missing_outputs": only_missing_outputs,
    }

    runner = runner or SequentialRunner()
    if not isinstance(runner, AbstractRunner):
        raise KedroSessionError(
            "KedroSession expect an instance of Runner instead of a class."
            "Have you forgotten the `()` at the end of the statement?"
        )

    catalog_class = (
        SharedMemoryDataCatalog
        if isinstance(runner, ParallelRunner)
        else settings.DATA_CATALOG_CLASS
    )

    # Scope validation to the requested pipelines; `__default__` falls
    # back to validating every registered pipeline.
    if "__default__" not in names:
        context._pipelines_to_validate = list(names)

    catalog = context._get_catalog(
        catalog_class=catalog_class,
        save_version=save_version,
        load_versions=load_versions,
    )

    # Run the runner
    hook_manager = self._hook_manager
    hook_manager.hook.before_pipeline_run(
        run_params=record_data, pipeline=filtered_pipeline, catalog=catalog
    )
    try:
        run_result = runner.run(
            filtered_pipeline,
            catalog,
            hook_manager,
            run_id=session_id,
            only_missing_outputs=only_missing_outputs,
        )
        self._run_called = True
    except Exception as error:
        hook_manager.hook.on_pipeline_error(
            error=error,
            run_params=record_data,
            pipeline=filtered_pipeline,
            catalog=catalog,
        )
        raise

    hook_manager.hook.after_pipeline_run(
        run_params=record_data,
        run_result=run_result,
        pipeline=filtered_pipeline,
        catalog=catalog,
    )
    return run_result

kedro.framework.session.service_session.KedroServiceSession

KedroServiceSession(session_id, package_name=None, project_path=None, conf_source=None, env=None)

Bases: AbstractSession

KedroServiceSession is the object that is responsible for managing the lifecycle of multiple Kedro runs. Use KedroServiceSession.create() as a context manager to construct a new KedroServiceSession with session data provided (see the example below).

Example:

from kedro.framework.session import KedroServiceSession
from kedro.framework.startup import bootstrap_project
from pathlib import Path

# If you are creating a session outside of a Kedro project (i.e. not using
# `kedro run` or `kedro jupyter`), you need to run `bootstrap_project` to
# let Kedro find your configuration.
bootstrap_project(Path("<project_root>"))
with KedroServiceSession.create() as session:
    run_1 = session.run(runtime_params={"param1": "value1"})
    run_2 = session.run(runtime_params={"param1": "value2"})
NOTE: This session implementation is under active development and may occasionally contain breaking changes.

Source code in kedro/framework/session/service_session.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def __init__(
    self,
    session_id: str,
    package_name: str | None = None,
    project_path: Path | str | None = None,
    conf_source: Path | str | None = None,
    env: str | None = None,
):
    self._project_path = Path(
        project_path or find_kedro_project(Path.cwd()) or Path.cwd()
    ).resolve()
    self.session_id = session_id
    self._package_name = package_name or kedro_project.PACKAGE_NAME
    hook_manager = _create_hook_manager()
    _register_hooks(hook_manager, settings.HOOKS)
    _register_hooks_entry_points(hook_manager, settings.DISABLE_HOOKS_FOR_PLUGINS)
    self._hook_manager = hook_manager
    self.env = env
    self._conf_source = conf_source or str(
        self._project_path / settings.CONF_SOURCE
    )

_conf_source instance-attribute

_conf_source = conf_source or str(_project_path / CONF_SOURCE)

_hook_manager instance-attribute

_hook_manager = hook_manager

_logger property

_logger

_package_name instance-attribute

_package_name = package_name or PACKAGE_NAME

_project_path instance-attribute

_project_path = resolve()

env instance-attribute

env = env

session_id instance-attribute

session_id = session_id

_get_config_loader

_get_config_loader(runtime_params=None)

An instance of the config loader.

Source code in kedro/framework/session/service_session.py
108
109
110
111
112
113
114
115
116
117
118
def _get_config_loader(
    self, runtime_params: dict[str, Any] | None = None
) -> AbstractConfigLoader:
    """An instance of the config loader."""
    config_loader_class = settings.CONFIG_LOADER_CLASS
    return config_loader_class(  # type: ignore[no-any-return]
        conf_source=self._conf_source,
        env=self.env,
        runtime_params=runtime_params,
        **settings.CONFIG_LOADER_ARGS,
    )

close

close()
Source code in kedro/framework/session/service_session.py
105
106
def close(self) -> None:
    self._logger.info("Closing session %s", self.session_id)

create classmethod

create(session_id=None, project_path=None, env=None, conf_source=None)

Create a new instance of the session.

Source code in kedro/framework/session/service_session.py
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
@classmethod
def create(
    cls,
    session_id: str | None = None,
    project_path: Path | str | None = None,
    env: str | None = None,
    conf_source: Path | str | None = None,
) -> KedroServiceSession:
    """Create a new instance of the session."""
    validate_settings()
    env = env or os.getenv("KEDRO_ENV")
    session = cls(
        project_path=project_path,
        session_id=session_id or str(uuid.uuid4()),
        conf_source=conf_source,
        env=env,
    )
    return session

load_context

load_context(runtime_params=None)

An instance of the project context with runtime parameters injected.

Source code in kedro/framework/session/service_session.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def load_context(
    self, runtime_params: dict[str, Any] | None = None
) -> KedroContext:
    """An instance of the project context with runtime parameters injected."""
    config_loader = self._get_config_loader(runtime_params)
    context_class = settings.CONTEXT_CLASS
    context = context_class(
        package_name=self._package_name,
        project_path=self._project_path,
        config_loader=config_loader,
        env=self.env,
        runtime_params=runtime_params,
        hook_manager=self._hook_manager,
    )
    self._hook_manager.hook.after_context_created(context=context)

    return context  # type: ignore[no-any-return]

run

run(run_id=None, pipeline_names=None, tags=None, runner=None, node_names=None, from_nodes=None, to_nodes=None, from_inputs=None, to_outputs=None, load_versions=None, namespaces=None, only_missing_outputs=False, runtime_params=None)

Run the pipeline.

Source code in kedro/framework/session/service_session.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def run(  # noqa: PLR0913
    self,
    run_id: str | None = None,
    pipeline_names: list[str] | None = None,
    tags: Iterable[str] | None = None,
    runner: AbstractRunner | None = None,
    node_names: Iterable[str] | None = None,
    from_nodes: Iterable[str] | None = None,
    to_nodes: Iterable[str] | None = None,
    from_inputs: Iterable[str] | None = None,
    to_outputs: Iterable[str] | None = None,
    load_versions: dict[str, str] | None = None,
    namespaces: Iterable[str] | None = None,
    only_missing_outputs: bool = False,
    runtime_params: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """Run the pipeline."""
    run_id = run_id or generate_timestamp()
    project_name = self._package_name or self._project_path.name
    self._logger.info("Kedro project %s", project_name)
    self._logger.info("Session ID: %s", self.session_id)
    self._logger.info("Run ID: %s", run_id)
    save_version = run_id

    context = self.load_context(runtime_params)
    pipeline_names = pipeline_names or ["__default__"]
    combined_pipeline = Pipeline([])
    for name in pipeline_names:
        try:
            combined_pipeline += pipelines[name]
        except KeyError as exc:
            matches = get_close_matches(name, pipelines.keys())
            if matches:
                suggestion = (
                    "Did you mean one of these instead?\n"
                    + textwrap.indent("\n".join(matches), " " * 4)
                )
            else:
                suggestion = ""
            raise ValueError(
                f"Failed to find the pipeline named '{name}'. "
                f"It needs to be generated and returned "
                f"by the 'register_pipelines' function. "
                f"{suggestion}"
            ) from exc

    filtered_pipeline = combined_pipeline.filter(
        tags=tags,
        from_nodes=from_nodes,
        to_nodes=to_nodes,
        node_names=node_names,
        from_inputs=from_inputs,
        to_outputs=to_outputs,
        node_namespaces=namespaces,
    )
    runner = runner or SequentialRunner()
    if not isinstance(runner, AbstractRunner):
        raise KedroSessionError(
            "KedroServiceSession expect an instance of Runner instead of a class."
            "Have you forgotten the `()` at the end of the statement?"
        )

    catalog_class = (
        SharedMemoryDataCatalog
        if isinstance(runner, ParallelRunner)
        else settings.DATA_CATALOG_CLASS
    )

    # Scope validation to the requested pipelines; `__default__` falls
    # back to validating every registered pipeline.
    if "__default__" not in pipeline_names:
        context._pipelines_to_validate = list(pipeline_names)

    catalog = context._get_catalog(
        catalog_class=catalog_class,
        save_version=save_version,
        load_versions=load_versions,
    )

    record_data = {
        "session_id": self.session_id,
        "run_id": run_id,
        "project_path": self._project_path.as_posix(),
        "env": context.env,
        "kedro_version": kedro_version,
        "tags": tags,
        "from_nodes": from_nodes,
        "to_nodes": to_nodes,
        "node_names": node_names,
        "from_inputs": from_inputs,
        "to_outputs": to_outputs,
        "load_versions": load_versions,
        "runtime_params": runtime_params or {},
        "pipeline_names": pipeline_names,
        "namespaces": namespaces,
        "runner": getattr(runner, "__name__", str(runner)),
        "only_missing_outputs": only_missing_outputs,
    }

    # Run the runner
    hook_manager = self._hook_manager
    hook_manager.hook.before_pipeline_run(
        run_params=record_data, pipeline=filtered_pipeline, catalog=catalog
    )
    try:
        run_result = runner.run(
            filtered_pipeline,
            catalog,
            hook_manager,
            run_id=run_id,
            only_missing_outputs=only_missing_outputs,
        )
    except Exception as error:
        hook_manager.hook.on_pipeline_error(
            error=error,
            run_params=record_data,
            pipeline=filtered_pipeline,
            catalog=catalog,
        )
        raise

    hook_manager.hook.after_pipeline_run(
        run_params=record_data,
        run_result=run_result,
        pipeline=filtered_pipeline,
        catalog=catalog,
    )
    return run_result

kedro.framework.session.store.BaseSessionStore

BaseSessionStore(path, session_id)

Bases: UserDict

BaseSessionStore is the base class for all session stores. BaseSessionStore is an ephemeral store implementation that doesn't persist the session data.

Source code in kedro/framework/session/store.py
16
17
18
19
def __init__(self, path: str, session_id: str):
    self._path = path
    self._session_id = session_id
    super().__init__(self.read())

_logger property

_logger

_path instance-attribute

_path = path

_session_id instance-attribute

_session_id = session_id

read

read()

Read the data from the session store.

Returns:

  • dict[str, Any]

    A mapping containing the session store data.

Source code in kedro/framework/session/store.py
25
26
27
28
29
30
31
32
33
34
35
def read(self) -> dict[str, Any]:
    """Read the data from the session store.

    Returns:
        A mapping containing the session store data.
    """
    self._logger.debug(
        "'read()' not implemented for '%s'. Assuming empty store.",
        self.__class__.__name__,
    )
    return {}

save

save()

Persist the session store

Source code in kedro/framework/session/store.py
37
38
39
40
41
42
def save(self) -> None:
    """Persist the session store"""
    self._logger.debug(
        "'save()' not implemented for '%s'. Skipping the step.",
        self.__class__.__name__,
    )

kedro.framework.session.abstract_session.KedroSessionError

Bases: Exception

KedroSessionError raised by KedroSession and KedroServiceSession when they encounter an error.