Skip to content

Add closure variables into global scope #431

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 2 commits 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
9 changes: 8 additions & 1 deletion src/patchy/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,11 +299,18 @@ def _process_function() -> ast.Module:

# Compile and retrieve the new Code object
localz: dict[str, Any] = {}

globalz = func.__globals__.copy()
for cell in func.__closure__ or ():
cell_contents = cell.cell_contents
Copy link
Author

Choose a reason for hiding this comment

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

Type of cell_contents is Any. So I'm NOT SURE here
Is it better to check if cell_contents is type instance?
What else may it be?

Copy link
Author

Choose a reason for hiding this comment

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

So, I was right in this question

if isinstance(cell_contents, type):
globalz.update(cell_contents.__dict__)

new_code = cast(CodeType, _compile(new_source))

exec(
new_code,
dict(func.__globals__),
globalz,
localz,
)
new_func = localz["__patchy_freevars__"]()
Expand Down
43 changes: 43 additions & 0 deletions tests/test_patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -795,6 +795,49 @@ def bark() -> str:
assert Doge.bark() == "Wowowow"


def test_patch_closure_use_function():
DEFAULT_MEDIUM = "Chalk"

def paint(medium: str = DEFAULT_MEDIUM) -> str:
return medium

assert paint() == "Chalk"

patchy.patch(
paint,
"""\
@@ -1,2 +1,2 @@
def paint(medium: str = DEFAULT_MEDIUM) -> str:
- return medium
+ return "Cheese"
""",
)

assert paint() == "Cheese"


def test_patch_closure_use_instancemethod():
class Artist:
DEFAULT_MEDIUM = "Chalk"

def paint(self, medium: str = DEFAULT_MEDIUM) -> str:
return medium

assert Artist().paint() == "Chalk"

patchy.patch(
Artist.paint,
"""\
@@ -1,2 +1,2 @@
def paint(self, medium: str = DEFAULT_MEDIUM) -> str:
- return medium
+ return "Cheese"
""",
)

assert Artist().paint() == "Cheese"


def test_patch_future_python(tmp_path):
(tmp_path / "future_user.py").write_text(
dedent(
Expand Down
Loading