<@ULVA73B9P> is there any way for a task that is b...
# ask-marvin
k
@Marvin is there any way for a task that is being mapped to access the index of the item in the mapped list its processing (without having to map of a list of
(index, data)
tuples?)
m
thought for 242.9 seconds
Yes. In Prefect 3.x, a mapped task can read its mapping “index” from the runtime context via the task run’s dynamic key. - Inside the task, use
get_run_context()
and read
ctx.task_run.dynamic_key
- It’s a string; for mapped runs it will be "0", "1", "2", … corresponding to the position Example:
Copy code
from prefect import flow, task
from prefect.context import get_run_context

@task
def process(item):
    ctx = get_run_context()
    idx = int(ctx.task_run.dynamic_key)  # "0", "1", ... -> int
    print(f"Processing index={idx}, item={item}")
    return idx, item

@flow
def main():
    items = ["a", "b", "c"]
    return process.map(items)

if __name__ == "__main__":
    main()
Notes: -
dynamic_key
is not exposed via `prefect.runtime.task_run`; you need
get_run_context()
inside the task. - For maximum explicitness/portability, passing the index yourself (e.g.,
process.map(range(len(items)), items)
) is still the most transparent approach, but the above avoids changing your mapping inputs.