From cbec1f616a423e4dd28a97fd2b8bf9c2bdcf36ec Mon Sep 17 00:00:00 2001 From: Casey Brooks Date: Fri, 26 Dec 2025 01:52:59 +0000 Subject: [PATCH] fix(pipeline): implement __len__ --- sklearn/pipeline.py | 4 ++++ sklearn/tests/test_pipeline.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/sklearn/pipeline.py b/sklearn/pipeline.py index 7eaf9a46f09e9..243b67e66d26f 100644 --- a/sklearn/pipeline.py +++ b/sklearn/pipeline.py @@ -199,6 +199,10 @@ def _iter(self, with_final=True): if trans is not None and trans != 'passthrough': yield idx, name, trans + def __len__(self): + """Return the number of steps in the pipeline.""" + return len(self.steps) + def __getitem__(self, ind): """Returns a sub-pipeline or a single esimtator in the pipeline diff --git a/sklearn/tests/test_pipeline.py b/sklearn/tests/test_pipeline.py index 8d6fe8f70374e..494836b7a9a51 100644 --- a/sklearn/tests/test_pipeline.py +++ b/sklearn/tests/test_pipeline.py @@ -529,6 +529,35 @@ def test_pipeline_fit_transform(): assert_array_almost_equal(X_trans, X_trans2) +def test_pipeline_len(): + steps = [('transf', Transf()), ('clf', FitParamT())] + pipe = Pipeline(steps) + assert len(pipe) == len(steps) + + passthrough_steps = [('transf', Transf()), ('final', 'passthrough')] + pipe_passthrough = Pipeline(passthrough_steps) + assert len(pipe_passthrough) == len(passthrough_steps) + + none_steps = [('transf', Transf()), ('final', None)] + pipe_none = Pipeline(none_steps) + assert len(pipe_none) == len(none_steps) + + +def test_pipeline_slice_with_len(): + steps = [ + ('transf1', Transf()), + ('transf2', Transf()), + ('clf', FitParamT()) + ] + pipe = Pipeline(steps) + + pipe_all = pipe[:len(pipe)] + + assert isinstance(pipe_all, Pipeline) + assert pipe_all.steps == steps + assert len(pipe_all) == len(pipe) + + def test_pipeline_slice(): pipe = Pipeline([('transf1', Transf()), ('transf2', Transf()),