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

Allow apply udf to reference global modules in cudf.pandas #15569

Merged
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
9 changes: 6 additions & 3 deletions python/cudf/cudf/pandas/fast_slow_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -1108,7 +1108,7 @@ def _replace_closurevars(
if any(c == types.CellType() for c in f.__closure__):
return f

f_nonlocals, f_globals, f_builtins, _ = inspect.getclosurevars(f)
f_nonlocals, f_globals, _, _ = inspect.getclosurevars(f)

g_globals = _transform_arg(f_globals, attribute_name, seen)
g_nonlocals = _transform_arg(f_nonlocals, attribute_name, seen)
Expand All @@ -1121,11 +1121,14 @@ def _replace_closurevars(
return f

g_closure = tuple(types.CellType(val) for val in g_nonlocals.values())
g_globals["__builtins__"] = f_builtins

# https://github.com/rapidsai/cudf/issues/15548
new_g_globals = f.__globals__.copy()
new_g_globals.update(g_globals)

g = types.FunctionType(
f.__code__,
g_globals,
new_g_globals,
name=f.__name__,
argdefs=f.__defaults__,
closure=g_closure,
Expand Down
12 changes: 12 additions & 0 deletions python/cudf/cudf_pandas_tests/test_cudf_pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -1208,3 +1208,15 @@ def test_pickle_groupby(dataframe):
def test_isinstance_base_offset():
offset = xpd.tseries.frequencies.to_offset("1s")
assert isinstance(offset, xpd.tseries.offsets.BaseOffset)


def test_apply_slow_path_udf_references_global_module():
def my_apply(df, unused):
# `datetime` Raised `KeyError: __import__`
datetime.datetime.strptime(df["Minute"], "%H:%M:%S")
return pd.to_numeric(1)

df = xpd.DataFrame({"Minute": ["09:00:00"]})
result = df.apply(my_apply, axis=1, unused=True)
expected = xpd.Series([1])
tm.assert_series_equal(result, expected)
Loading