Skip to content
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

Cannot pickle functions decorated through contextlib #509

Open
crusaderky opened this issue Jul 6, 2023 · 1 comment
Open

Cannot pickle functions decorated through contextlib #509

crusaderky opened this issue Jul 6, 2023 · 1 comment

Comments

@crusaderky
Copy link

It's a somewhat little known feature of contextlib.contextmanager and contextlib.asynccontextmanager that you can use the decorated functions not only as context managers, but also as function decorators:

import asyncio
from contextlib import contextmanager, asynccontextmanager

@contextmanager
def c():
    print("before")
    yield
    print("after")

@c()
def f():
    print("hello world")

f()

@asynccontextmanager
async def ac():
    print("async before")
    yield
    print("async after")

@ac()
async def af():
    print("async hello world")

asyncio.run(af())
before
hello world
after
async before
async hello world
async after

cloudpickle 2.2.1 fails to serialize functions decorated this way:

>>> pickle.loads(pickle.dumps(f))
<function f at 0x7f949972d580>

>>> pickle.loads(pickle.dumps(af))
<function af at 0x7f9499770180>

>>> cloudpickle.dumps(f)
Traceback (most recent call last):
  File "demo.py", line 34, in <module>
    cloudpickle.dumps(f)
          ^^^^^^^^^^^^^^^^^^^^
  File "lib/python3.11/site-packages/cloudpickle/cloudpickle_fast.py", line 73, in dumps
    cp.dump(obj)
  File "lib/python3.11/site-packages/cloudpickle/cloudpickle_fast.py", line 632, in dump
    return Pickler.dump(self, obj)
           ^^^^^^^^^^^^^^^^^^^^^^^
TypeError: cannot pickle 'generator' object

>>> cloudpickle.dumps(af)
Traceback (most recent call last):
  File "demo.py", line 35, in <module>
    cloudpickle.dumps(af)
          ^^^^^^^^^^^^^^^^^^^^^
  File "lib/python3.11/site-packages/cloudpickle/cloudpickle_fast.py", line 73, in dumps
    cp.dump(obj)
  File "lib/python3.11/site-packages/cloudpickle/cloudpickle_fast.py", line 632, in dump
    return Pickler.dump(self, obj)
           ^^^^^^^^^^^^^^^^^^^^^^^
TypeError: cannot pickle 'async_generator' object
@ogrisel
Copy link
Contributor

ogrisel commented Oct 13, 2023

Thanks for the report, I confirm I can reproduce with master.

The problem is weird because it is raised by the parent class of our pickler which should precisely be the pickle.Pickler class used internally by pickle.dumps...

>>> import io
>>> buffer = io.BytesIO()
>>> pickle.Pickler(buffer, protocol=5).dump(f)
# does not raise

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants