Skip to content

Wrap env in Python DO/WorkerEntrypoint constructor. #4109

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/pyodide/internal/workers.py
Original file line number Diff line number Diff line change
Expand Up @@ -892,6 +892,19 @@ def wrapper(*args, **kwargs):
return wrapper


def _wrap_subclass(cls):
# Override the class __init__ so that we can wrap the `env` in the constructor.
original_init = cls.__init__

def wrapped_init(self, *args, **kwargs):
if len(args) > 1:
args = (args[0], _EnvWrapper(args[1])) + args[2:]

original_init(self, *args, **kwargs)

cls.__init__ = wrapped_init


class DurableObject:
"""
Base class used to define a Durable Object.
Expand All @@ -901,6 +914,9 @@ def __init__(self, ctx, env):
self.ctx = ctx
self.env = env

def __init_subclass__(cls, **_kwargs):
_wrap_subclass(cls)


class WorkerEntrypoint:
"""
Expand All @@ -911,6 +927,9 @@ def __init__(self, ctx, env):
self.ctx = ctx
self.env = env

def __init_subclass__(cls, **_kwargs):
_wrap_subclass(cls)


class WorkflowEntrypoint:
"""
Expand All @@ -920,3 +939,6 @@ class WorkflowEntrypoint:
def __init__(self, ctx, env):
self.ctx = ctx
self.env = env

def __init_subclass__(cls, **_kwargs):
_wrap_subclass(cls)
14 changes: 14 additions & 0 deletions src/workerd/server/tests/python/python-rpc/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ def __init__(self, ctx, env):
assert self.env is not None
assert self.ctx is not None

assert not isinstance(env, JsProxy)
self.env = env

async def no_args(self):
return "hello from python"

Expand All @@ -43,6 +46,14 @@ async def handle_request(self, req):
assert isinstance(req, Request)
return req

async def check_env(self):
# Verify that the `env` supplied to the entrypoint class is wrapped.
curr_date = datetime.now()
py_date = await self.env.PythonRpc.identity(curr_date)
assert isinstance(py_date, datetime)
assert py_date == curr_date
return True


class CustomType:
def __init__(self, x):
Expand Down Expand Up @@ -242,3 +253,6 @@ def my_func():
await env.PythonRpc.identity(my_func)
with assertRaises(TypeError):
await env.PythonRpc.identity({"test": (1, 2, 3)})

# Verify that the `env` in the DO is correctly wrapped.
assert await env.PythonRpc.check_env()