Skip to content

Commit 01ef546

Browse files
committed
Revert "Keep the passed in working directory in sys.path after the in… (#27718)
…itial import of user code (#27485)" This reverts commit 199c6b3. ## Summary & Motivation ## How I Tested These Changes ## Changelog > Insert changelog entry or delete this section.
1 parent 3487b08 commit 01ef546

File tree

6 files changed

+72
-99
lines changed

6 files changed

+72
-99
lines changed

CHANGES.md

-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@
2929
- Fixed an issue where partition keys could be dropped when converting a list of partition keys for a `MultiPartitionsDefinition` to a `PartitionSubset`.
3030
- Fixed an issue where the "Reload definitions" button didn't work when using `dagster dev` on Windows, starting in the 1.9.10 release.
3131
- Fixed an issue where dagster could not be imported alongside some other libraries using gRPC with an 'api.proto' file.
32-
- Fixed an issue where assets using ProcessPoolExecutor or multiprocessing with a spawn context sometimes failed to work with a ModuleNotFoundError.
3332
- [ui] Fixed an issue where non-`None` default config fields weren't being displayed in the Launchpad view.
3433
- [ui] Fixed an issue with the search bar on the Asset partitions page incorrectly filtering partitions when combined with a status filter.
3534
- [ui] Fixed Asset page header display of long key values.

python_modules/dagster/dagster/_core/code_pointer.py

+42-31
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from dagster._core.errors import DagsterImportError, DagsterInvariantViolationError
1212
from dagster._serdes import whitelist_for_serdes
1313
from dagster._seven import get_import_error_message, import_module_from_path
14-
from dagster._utils import hash_collection
14+
from dagster._utils import alter_sys_path, hash_collection
1515

1616

1717
class CodePointer(ABC):
@@ -74,11 +74,14 @@ def load_python_file(python_file: str, working_directory: Optional[str]) -> Modu
7474

7575
module_name = os.path.splitext(os.path.basename(python_file))[0]
7676

77-
if working_directory and working_directory not in sys.path:
78-
sys.path.insert(0, working_directory)
79-
77+
# Use the passed in working directory for local imports (sys.path[0] isn't
78+
# consistently set in the different entry points that Dagster uses to import code)
79+
script_path = sys.path[0]
8080
try:
81-
return import_module_from_path(module_name, python_file)
81+
with alter_sys_path(
82+
to_add=([working_directory] if working_directory else []), to_remove=[script_path]
83+
):
84+
return import_module_from_path(module_name, python_file)
8285
except ImportError as ie:
8386
python_file = os.path.abspath(os.path.expanduser(python_file))
8487

@@ -113,35 +116,43 @@ def load_python_file(python_file: str, working_directory: Optional[str]) -> Modu
113116
def load_python_module(
114117
module_name: str,
115118
working_directory: Optional[str],
119+
remove_from_path_fn: Optional[Callable[[], Sequence[str]]] = None,
116120
) -> ModuleType:
117121
check.str_param(module_name, "module_name")
118122
check.opt_str_param(working_directory, "working_directory")
119-
120-
if working_directory and working_directory not in sys.path:
121-
sys.path.insert(0, working_directory)
122-
123-
try:
124-
return importlib.import_module(module_name)
125-
except ImportError as ie:
126-
msg = get_import_error_message(ie)
127-
if working_directory:
128-
abs_working_directory = os.path.abspath(os.path.expanduser(working_directory))
129-
raise DagsterImportError(
130-
f"Encountered ImportError: `{msg}` while importing module {module_name}. "
131-
"Local modules were resolved using the working "
132-
f"directory `{abs_working_directory}`. If another working directory should be "
133-
"used, please explicitly specify the appropriate path using the `-d` or "
134-
"`--working-directory` for CLI based targets or the `working_directory` "
135-
"configuration option for workspace targets. "
136-
) from ie
137-
else:
138-
raise DagsterImportError(
139-
f"Encountered ImportError: `{msg}` while importing module {module_name}. "
140-
"If relying on the working directory to resolve modules, please "
141-
"explicitly specify the appropriate path using the `-d` or "
142-
"`--working-directory` for CLI based targets or the `working_directory` "
143-
"configuration option for workspace targets. "
144-
) from ie
123+
check.opt_callable_param(remove_from_path_fn, "remove_from_path_fn")
124+
125+
# Use the passed in working directory for local imports (sys.path[0] isn't
126+
# consistently set in the different entry points that Dagster uses to import code)
127+
remove_paths: list[str] = (
128+
list(remove_from_path_fn()) if remove_from_path_fn else []
129+
) # hook for tests
130+
remove_paths.insert(0, sys.path[0]) # remove the script path
131+
with alter_sys_path(
132+
to_add=([working_directory] if working_directory else []), to_remove=remove_paths
133+
):
134+
try:
135+
return importlib.import_module(module_name)
136+
except ImportError as ie:
137+
msg = get_import_error_message(ie)
138+
if working_directory:
139+
abs_working_directory = os.path.abspath(os.path.expanduser(working_directory))
140+
raise DagsterImportError(
141+
f"Encountered ImportError: `{msg}` while importing module {module_name}. "
142+
"Local modules were resolved using the working "
143+
f"directory `{abs_working_directory}`. If another working directory should be "
144+
"used, please explicitly specify the appropriate path using the `-d` or "
145+
"`--working-directory` for CLI based targets or the `working_directory` "
146+
"configuration option for workspace targets. "
147+
) from ie
148+
else:
149+
raise DagsterImportError(
150+
f"Encountered ImportError: `{msg}` while importing module {module_name}. "
151+
"If relying on the working directory to resolve modules, please "
152+
"explicitly specify the appropriate path using the `-d` or "
153+
"`--working-directory` for CLI based targets or the `working_directory` "
154+
"configuration option for workspace targets. "
155+
) from ie
145156

146157

147158
@whitelist_for_serdes

python_modules/dagster/dagster/_core/workspace/autodiscovery.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import inspect
22
from collections.abc import Sequence
33
from types import ModuleType
4-
from typing import NamedTuple, Optional, Union
4+
from typing import Callable, NamedTuple, Optional, Union
55

66
from dagster import DagsterInvariantViolationError, GraphDefinition, RepositoryDefinition
77
from dagster._core.code_pointer import load_python_file, load_python_module
@@ -28,19 +28,24 @@ def loadable_targets_from_python_file(
2828
def loadable_targets_from_python_module(
2929
module_name: str,
3030
working_directory: Optional[str],
31+
remove_from_path_fn: Optional[Callable[[], Sequence[str]]] = None,
3132
) -> Sequence[LoadableTarget]:
3233
module = load_python_module(
3334
module_name,
3435
working_directory=working_directory,
36+
remove_from_path_fn=remove_from_path_fn,
3537
)
3638
return loadable_targets_from_loaded_module(module)
3739

3840

3941
def loadable_targets_from_python_package(
4042
package_name: str,
4143
working_directory: Optional[str],
44+
remove_from_path_fn: Optional[Callable[[], Sequence[str]]] = None,
4245
) -> Sequence[LoadableTarget]:
43-
module = load_python_module(package_name, working_directory)
46+
module = load_python_module(
47+
package_name, working_directory, remove_from_path_fn=remove_from_path_fn
48+
)
4449
return loadable_targets_from_loaded_module(module)
4550

4651

python_modules/dagster/dagster_tests/cli_tests/command_tests/asset_with_process_pool_executor.py

-19
This file was deleted.

python_modules/dagster/dagster_tests/cli_tests/command_tests/test_materialize_command.py

-19
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import os
2-
import subprocess
31
from typing import Optional
42

53
from click.testing import CliRunner
@@ -181,23 +179,6 @@ def test_failure():
181179
assert result.exit_code == 1
182180

183181

184-
def test_asset_with_multiprocessing():
185-
with instance_for_test():
186-
subprocess.check_call(
187-
[
188-
"dagster",
189-
"asset",
190-
"materialize",
191-
"-f",
192-
file_relative_path(__file__, "asset_with_process_pool_executor.py"),
193-
"--select",
194-
"multiprocess_asset",
195-
"--working-directory",
196-
os.path.dirname(__file__),
197-
]
198-
)
199-
200-
201182
def test_run_cli_config_json():
202183
with instance_for_test() as instance:
203184
asset_key = "asset_assert_with_config"

python_modules/dagster/dagster_tests/cli_tests/workspace_tests/autodiscovery_tests/test_autodiscovery.py

+23-27
Original file line numberDiff line numberDiff line change
@@ -223,11 +223,11 @@ def test_local_directory_module_multiple_defs() -> None:
223223
DagsterInvariantViolationError,
224224
match="Cannot have more than one Definitions object defined at module scope. Found Definitions objects: autodiscover_in_module_multiple.defs, autodiscover_in_module_multiple.defs1, autodiscover_in_module_multiple.defs2",
225225
):
226-
with alter_sys_path(to_add=[], to_remove=_current_test_directory_paths()):
227-
loadable_targets_from_python_module(
228-
"autodiscover_in_module_multiple",
229-
working_directory=os.path.dirname(__file__),
230-
)
226+
loadable_targets_from_python_module(
227+
"autodiscover_in_module_multiple",
228+
working_directory=os.path.dirname(__file__),
229+
remove_from_path_fn=_current_test_directory_paths,
230+
)
231231

232232

233233
def _current_test_directory_paths():
@@ -251,25 +251,25 @@ def test_local_directory_module() -> None:
251251
if "autodiscover_in_module" in sys.modules:
252252
del sys.modules["autodiscover_in_module"]
253253

254-
with alter_sys_path(to_add=[], to_remove=_current_test_directory_paths()):
255-
with pytest.raises(DagsterImportError):
256-
loadable_targets_from_python_module(
257-
"complete_bogus_module",
258-
working_directory=os.path.dirname(__file__),
259-
)
260-
261-
with alter_sys_path(to_add=[], to_remove=_current_test_directory_paths()):
262-
with pytest.raises(DagsterImportError):
263-
loadable_targets_from_python_module(
264-
"autodiscover_in_module",
265-
working_directory=None,
266-
)
267-
268-
with alter_sys_path(to_add=[], to_remove=_current_test_directory_paths()):
269-
loadable_targets = loadable_targets_from_python_module(
270-
"autodiscover_in_module",
254+
with pytest.raises(DagsterImportError):
255+
loadable_targets_from_python_module(
256+
"complete_bogus_module",
271257
working_directory=os.path.dirname(__file__),
258+
remove_from_path_fn=_current_test_directory_paths,
272259
)
260+
261+
with pytest.raises(DagsterImportError):
262+
loadable_targets_from_python_module(
263+
"autodiscover_in_module",
264+
working_directory=None,
265+
remove_from_path_fn=_current_test_directory_paths,
266+
)
267+
268+
loadable_targets = loadable_targets_from_python_module(
269+
"autodiscover_in_module",
270+
working_directory=os.path.dirname(__file__),
271+
remove_from_path_fn=_current_test_directory_paths,
272+
)
273273
assert len(loadable_targets) == 1
274274

275275

@@ -282,12 +282,8 @@ def test_local_directory_file() -> None:
282282

283283
assert "No module named 'autodiscover_src'" in str(exc_info.value)
284284

285-
to_restore = [path for path in sys.path]
286-
try:
287-
alter_sys_path(to_add=[os.path.dirname(path)], to_remove=[])
285+
with alter_sys_path(to_add=[os.path.dirname(path)], to_remove=[]):
288286
loadable_targets_from_python_file(path, working_directory=os.path.dirname(path))
289-
finally:
290-
sys.path = to_restore
291287

292288

293289
def test_lazy_definitions() -> None:

0 commit comments

Comments
 (0)