SimPy Python
Build reproducible discrete-event models whose clock, state transitions,
resource ownership, stopping rule, randomness, and observations represent the
real system rather than an accidental execution order.
Boundary and core objects
| Object |
Meaning |
Use it for |
Environment |
Scheduler, simulation clock, and event queue. |
One simulated world/replication. |
Event |
A future state that becomes triggered, processed, and optionally carries a value/failure. |
Synchronization and completion signals. |
Process |
An event wrapping a generator's lifecycle. |
Active entities that yield events. |
Timeout |
An event scheduled after simulated delay. |
Duration, not wall-clock sleep. |
Resource family |
Capacity tokens with queues. |
Exclusive/shared service and congestion. |
Container |
Homogeneous numeric level. |
Bulk inventory or fuel. |
Store |
Queued Python objects. |
Items, messages, or jobs with identity. |
A process function is a generator recipe; env.process(generator) registers it
and returns a Process event. yield event suspends simulated activity until
that event is processed. Calling a generator normally does not run the model.
Read the event and process model before mixing
callbacks, interrupts, conditions, or resource requests.
Ordered workflow
- Define the question, time unit, warm-up, horizon/stopping event, and measured
population before modeling implementation details.
- Separate domain state from the environment and random-number generator.
- Express every delay, wait, acquisition, release, failure, and cancellation as
an event transition.
- Select
Resource, Container, or Store from what is constrained—not by
superficial queue vocabulary.
- Record observations at defined transitions and with clear denominators.
- Run independent replications with controlled seeds; report uncertainty, not
one trace, when making stochastic claims.
- Test tiny deterministic timelines, contention, boundary times, interruption,
empty/full queues, and the stopping rule.
Decision rules
- Use
Resource when entities compete for interchangeable usage slots. Use a
with resource.request() as request: yield request block so ownership is
released on normal exit or interruption.
- Use
PriorityResource when waiting order follows an explicit priority. State
whether lower numeric values mean higher priority and define tie behavior.
- Use
PreemptiveResource only when an admitted user can be interrupted. Handle
simpy.Interrupt, remaining work, cleanup, and measurement bias.
- Use
Container for an aggregate quantity without item identity. Use Store
when objects and selection/filtering matter.
- Use
env.timeout(duration) for simulated time. Reject negative durations and
define whether zero delay is a legitimate same-time event.
- Use
env.any_of/event1 | event2 for races and all_of/& for barriers.
Inspect which events completed; a losing event may still need cancellation or
cleanup.
- Use
env.run(until=t) knowing events scheduled exactly at t are not a vague
“through time t” promise; write a boundary test for the chosen stopping form.
- Use
RealtimeEnvironment only when coupling to wall-clock behavior is an
explicit requirement. It is not a way to make simulation more accurate.
Read resources, time, and experiments for ownership,
queues, monitoring, randomness, and replication rules.
Canonical anchor
from collections.abc import Generator
from dataclasses import dataclass
import simpy
@dataclass(frozen=True)
class Visit:
customer: int
queued_at: float
started_at: float
finished_at: float
def customer(
env: simpy.Environment,
server: simpy.Resource,
customer_id: int,
service_time: float,
visits: list[Visit],
) -> Generator[simpy.Event, object, None]:
queued_at = env.now
with server.request() as request:
yield request
started_at = env.now
yield env.timeout(service_time)
visits.append(Visit(customer_id, queued_at, started_at, env.now))
The record captures state-transition times rather than sampling a mutable queue.
Arrival creation and random service draws belong outside this process so a test
can inject a deterministic schedule.
High-risk rules
- Do not mutate state “after a delay” without yielding that delay.
- Do not hold a resource while waiting for unrelated work unless the real entity
occupies it during that time.
- Do not manually release a context-managed request twice.
- Never share one mutable RNG implicitly across replications. Derive and record
per-replication seeds; common random numbers require an intentional design.
- Avoid global
random calls inside processes. Inject distributions or an RNG.
- A queue-length time average requires time weighting between changes; averaging
observations at arrivals answers a different question.
- Distinguish censored entities still in the system at the horizon from
completed entities. Do not silently discard them from denominators.
- Same-time events are ordered by scheduler rules and creation sequence. If the
answer must not depend on that order, encode priorities or redesign the event.
- An interrupted process must release resources and decide whether work resumes,
restarts, or is lost. Catching and ignoring the interrupt is not a model.
Version grounding and completion
The authoring baseline is official SimPy 4.1.2 stable documentation; the local
foundry has not yet executed the package. Check the installed version with
simpy.__version__ and inspect signatures before relying on exception fields, resource variants, or
environment behavior. Read verification.
Completion requires an explicit clock/stopping contract, correct resource
ownership, injected randomness, traceable observations, deterministic
micro-tests, stochastic replication checks where relevant, and evidence that
the result does not depend accidentally on global state or one seed.
References
- Event and process model
- Resources, time, and experiments
- Verification and grounding
1---2name: simpy-python3description: Use for writing, reviewing, debugging, testing, or analyzing Python SimPy discrete-event simulations. Trigger on Environment, Event, Process, timeout, Resource, PriorityResource, PreemptiveResource, Container, Store, queues, interrupts, simulation clocks, replications, or SimPy monitoring. Do not use for asyncio services, wall-clock schedulers, continuous ODE solvers, or Monte Carlo code without an event-process model.4argument-hint: "[SimPy model, process, queue, experiment, or error]"5metadata:6 source: https://skillmd.com/skills/schattenspiegel/simpy-python7---89# SimPy Python1011Build reproducible discrete-event models whose clock, state transitions,12resource ownership, stopping rule, randomness, and observations represent the13real system rather than an accidental execution order.1415## Boundary and core objects1617| Object | Meaning | Use it for |18|---|---|---|19| `Environment` | Scheduler, simulation clock, and event queue. | One simulated world/replication. |20| `Event` | A future state that becomes triggered, processed, and optionally carries a value/failure. | Synchronization and completion signals. |21| `Process` | An event wrapping a generator's lifecycle. | Active entities that yield events. |22| `Timeout` | An event scheduled after simulated delay. | Duration, not wall-clock sleep. |23| `Resource` family | Capacity tokens with queues. | Exclusive/shared service and congestion. |24| `Container` | Homogeneous numeric level. | Bulk inventory or fuel. |25| `Store` | Queued Python objects. | Items, messages, or jobs with identity. |2627A process function is a generator recipe; `env.process(generator)` registers it28and returns a `Process` event. `yield event` suspends simulated activity until29that event is processed. Calling a generator normally does not run the model.30Read [the event and process model](references/event-model.md) before mixing31callbacks, interrupts, conditions, or resource requests.3233## Ordered workflow34351. Define the question, time unit, warm-up, horizon/stopping event, and measured36 population before modeling implementation details.372. Separate domain state from the environment and random-number generator.383. Express every delay, wait, acquisition, release, failure, and cancellation as39 an event transition.404. Select `Resource`, `Container`, or `Store` from what is constrained—not by41 superficial queue vocabulary.425. Record observations at defined transitions and with clear denominators.436. Run independent replications with controlled seeds; report uncertainty, not44 one trace, when making stochastic claims.457. Test tiny deterministic timelines, contention, boundary times, interruption,46 empty/full queues, and the stopping rule.4748## Decision rules4950- Use `Resource` when entities compete for interchangeable usage slots. Use a51 `with resource.request() as request: yield request` block so ownership is52 released on normal exit or interruption.53- Use `PriorityResource` when waiting order follows an explicit priority. State54 whether lower numeric values mean higher priority and define tie behavior.55- Use `PreemptiveResource` only when an admitted user can be interrupted. Handle56 `simpy.Interrupt`, remaining work, cleanup, and measurement bias.57- Use `Container` for an aggregate quantity without item identity. Use `Store`58 when objects and selection/filtering matter.59- Use `env.timeout(duration)` for simulated time. Reject negative durations and60 define whether zero delay is a legitimate same-time event.61- Use `env.any_of`/`event1 | event2` for races and `all_of`/`&` for barriers.62 Inspect which events completed; a losing event may still need cancellation or63 cleanup.64- Use `env.run(until=t)` knowing events scheduled exactly at `t` are not a vague65 “through time t” promise; write a boundary test for the chosen stopping form.66- Use `RealtimeEnvironment` only when coupling to wall-clock behavior is an67 explicit requirement. It is not a way to make simulation more accurate.6869Read [resources, time, and experiments](references/modeling.md) for ownership,70queues, monitoring, randomness, and replication rules.7172## Canonical anchor7374```python75from collections.abc import Generator76from dataclasses import dataclass7778import simpy798081@dataclass(frozen=True)82class Visit:83 customer: int84 queued_at: float85 started_at: float86 finished_at: float878889def customer(90 env: simpy.Environment,91 server: simpy.Resource,92 customer_id: int,93 service_time: float,94 visits: list[Visit],95) -> Generator[simpy.Event, object, None]:96 queued_at = env.now97 with server.request() as request:98 yield request99 started_at = env.now100 yield env.timeout(service_time)101 visits.append(Visit(customer_id, queued_at, started_at, env.now))102```103104The record captures state-transition times rather than sampling a mutable queue.105Arrival creation and random service draws belong outside this process so a test106can inject a deterministic schedule.107108## High-risk rules109110- Do not mutate state “after a delay” without yielding that delay.111- Do not hold a resource while waiting for unrelated work unless the real entity112 occupies it during that time.113- Do not manually release a context-managed request twice.114- Never share one mutable RNG implicitly across replications. Derive and record115 per-replication seeds; common random numbers require an intentional design.116- Avoid global `random` calls inside processes. Inject distributions or an RNG.117- A queue-length time average requires time weighting between changes; averaging118 observations at arrivals answers a different question.119- Distinguish censored entities still in the system at the horizon from120 completed entities. Do not silently discard them from denominators.121- Same-time events are ordered by scheduler rules and creation sequence. If the122 answer must not depend on that order, encode priorities or redesign the event.123- An interrupted process must release resources and decide whether work resumes,124 restarts, or is lost. Catching and ignoring the interrupt is not a model.125126## Version grounding and completion127128The authoring baseline is official SimPy 4.1.2 stable documentation; the local129foundry has not yet executed the package. Check the installed version with130`simpy.__version__` and inspect signatures before relying on exception fields, resource variants, or131environment behavior. Read [verification](references/verification.md).132133Completion requires an explicit clock/stopping contract, correct resource134ownership, injected randomness, traceable observations, deterministic135micro-tests, stochastic replication checks where relevant, and evidence that136the result does not depend accidentally on global state or one seed.137138## References139140- [Event and process model](references/event-model.md)141- [Resources, time, and experiments](references/modeling.md)142- [Verification and grounding](references/verification.md)