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

fix[tool]: update VarAccess pickle implementation #4270

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
19 changes: 19 additions & 0 deletions tests/integration/test_pickle_ast.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import copy
import pickle

from vyper.compiler.phases import CompilerData


def test_pickle_ast():
code = """
@external
def foo():
self.bar()
y: uint256 = 5
x: uint256 = 5
def bar():
pass
"""
f = CompilerData(code)
copy.deepcopy(f.annotated_vyper_module)
pickle.loads(pickle.dumps(f.annotated_vyper_module))
14 changes: 12 additions & 2 deletions vyper/semantics/analysis/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import enum
from dataclasses import dataclass
from dataclasses import dataclass, fields
from functools import cached_property
from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union

Expand Down Expand Up @@ -234,6 +234,17 @@ class VarAccess:
# A sentinel indicating a subscript access
SUBSCRIPT_ACCESS: ClassVar[Any] = object()

# custom __reduce__ and _produce implementations to work around
# a pickle bug.
# see https://github.com/python/cpython/issues/124937#issuecomment-2392227290
def __reduce__(self):
dict_obj = {f.name: getattr(self, f.name) for f in fields(self)}
return self.__class__._produce, (dict_obj,)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could also use the following trick if all fields can be passed as keyword arguments to constructor in subclasses:

Suggested change
return self.__class__._produce, (dict_obj,)
return partial(self.__class__, **dict_obj), ()

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

interesting, is there a performance difference?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It may be slower. The advantage is that you do not need to add private method _produce().


@classmethod
def _produce(cls, data):
return cls(**data)

@cached_property
def attrs(self):
ret = []
Expand Down Expand Up @@ -286,7 +297,6 @@ def __post_init__(self):
for attr in should_match:
if getattr(self.var_info, attr) != getattr(self, attr):
raise CompilerPanic(f"Bad analysis: non-matching {attr}: {self}")

self._writes: OrderedSet[VarAccess] = OrderedSet()
self._reads: OrderedSet[VarAccess] = OrderedSet()

Expand Down
Loading