|
5 | 5 | from workflows import HelloWorldWorkflow |
6 | 6 | from activities import Activities |
7 | 7 | import shared |
| 8 | +import inspect |
8 | 9 |
|
9 | 10 |
|
10 | 11 | async def main(): |
11 | 12 | default_profile = ClientConfigProfile.load() |
12 | 13 | connect_config = default_profile.to_client_connect_config() |
13 | 14 |
|
14 | 15 | client = await Client.connect(**connect_config) |
| 16 | + |
| 17 | + # Register the activities - you may need to inject dependencies in here |
15 | 18 | activities = Activities() |
16 | 19 |
|
17 | 20 | worker = Worker( |
18 | 21 | client, |
19 | 22 | task_queue=shared.TASK_QUEUE_NAME, |
20 | 23 | workflows=[HelloWorldWorkflow], |
21 | | - activities=[activities.sayName], |
| 24 | + activities=find_activities(activities), |
22 | 25 | ) |
23 | 26 |
|
24 | 27 | print("Worker started.") |
25 | 28 | await worker.run() |
26 | 29 |
|
27 | 30 |
|
| 31 | +# ---- auto-discovery helper ---- |
| 32 | +_ACTIVITY_ATTR = "__temporal_activity_definition" # set by @activity.defn |
| 33 | + |
| 34 | + |
| 35 | +def find_activities(obj): |
| 36 | + """Return a list of bound methods on `obj` that are Temporal activities.""" |
| 37 | + acts = [] |
| 38 | + for _, member in inspect.getmembers(obj): |
| 39 | + if callable(member) and is_activity_callable(member): |
| 40 | + acts.append(member) # bound method carries injected deps |
| 41 | + return acts |
| 42 | + |
| 43 | + |
| 44 | +def is_activity_callable(attr) -> bool: |
| 45 | + # Works for functions and bound methods |
| 46 | + func = attr.__func__ if inspect.ismethod(attr) else attr |
| 47 | + return hasattr(func, _ACTIVITY_ATTR) |
| 48 | + |
| 49 | + |
28 | 50 | if __name__ == "__main__": |
29 | 51 | asyncio.run(main()) |
0 commit comments