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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
11 changes: 11 additions & 0 deletions src/pyodide/internal/workers.py
Original file line number Diff line number Diff line change
Expand Up @@ -917,6 +917,17 @@ def _wrap_subclass(cls):
continue
setattr(cls, k, _wrap_attr(v))

# 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:
"""
Expand Down
15 changes: 15 additions & 0 deletions src/workerd/server/tests/python/python-rpc/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@


class PythonRpcTester(WorkerEntrypoint):
def __init__(self, ctx, env):
assert not isinstance(env, JsProxy)
self.env = env

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

Expand All @@ -37,6 +41,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 @@ -236,3 +248,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()
Loading