55import itertools as it
66from .spaces import HWBish
77from .types import ColorInput , AnyColor
8+ from .interpolate import carryforward_convert
89from typing import Iterable
910
1011
@@ -24,7 +25,8 @@ def average(
2425 colors : Iterable [ColorInput ],
2526 weights : Iterable [float ] | None ,
2627 space : str ,
27- premultiplied : bool = True
28+ premultiplied : bool = True ,
29+ carryforward : bool = False
2830) -> AnyColor :
2931 """
3032 Average a list of colors together.
@@ -33,10 +35,9 @@ def average(
3335 """
3436
3537 sentinel = Sentinel ()
36- obj = color_cls (space , [])
3738
3839 # Get channel information
39- cs = obj .CS_MAP [space ]
40+ cs = color_cls .CS_MAP [space ]
4041 if cs .is_polar ():
4142 hue_index = cs .hue_index () # type: ignore[attr-defined]
4243 is_hwb = isinstance (cs , HWBish )
@@ -49,6 +50,8 @@ def average(
4950 hue_max = 0.0
5051 to_rad = 0.0
5152 to_hue = 0.0
53+
54+ obj = color_cls (space , [])
5255 channels = cs .channels
5356 chan_count = len (channels )
5457 avgs = [0.0 ] * chan_count
@@ -83,10 +86,15 @@ def average(
8386 elif w > mx :
8487 mx = w
8588
86- obj .update (c ) # type: ignore[arg-type]
87- # If cylindrical color is achromatic, ensure hue is undefined
88- if hue_index >= 0 and not math .isnan (obj [hue_index ]) and obj .is_achromatic ():
89- obj [hue_index ] = math .nan
89+ if carryforward :
90+ obj .mutate (c ) # type: ignore[arg-type]
91+ carryforward_convert (obj , space , hue_index , True )
92+ else :
93+ obj .update (c ) # type: ignore[arg-type]
94+ # If cylindrical color is achromatic, ensure hue is undefined
95+ if hue_index >= 0 and not math .isnan (obj [hue_index ]) and obj .is_achromatic ():
96+ obj [hue_index ] = math .nan
97+
9098 coords = obj [:]
9199
92100 # Average weights
0 commit comments