bazelbuild / rules_python

Bazel Python Rules
https://rules-python.readthedocs.io
Apache License 2.0
513 stars 521 forks source link

Bazel 7 namespace collision #1897

Open Ryang20718 opened 2 months ago

Ryang20718 commented 2 months ago

🐞 bug report

with rules_python 0.31.0 and bazel 7.1.2, there seems to be an issue with naming certain directories with certain names. Wondering if this is expected?

Description

There is a namespace collision with certain directories

🔬 Minimal Reproduction

Build file example/time/BUILD

load("@rules_python//python:defs.bzl", "py_test", "py_library")

py_library(
    name = "time_py",
    srcs = ["py_test.py"],
)

py_test(
    main = "py_test.py",
    srcs = [":time_py"],
)

example/time/__init__.py

import time

example/time/py_test.py

import time

bazel test //example/time:all --noincompatible_default_to_explicit_init_py will result in an import error

🔥 Exception or Error


```
ImportError while importing test module 
Hint: make sure your test modules/packages have valid Python names.
Traceback:
../pip_pytest/site-packages/_pytest/python.py:617: in _importtestmodule
    mod = import_path(self.path, mode=importmode, root=self.config.rootpath)
../pip_pytest/site-packages/_pytest/pathlib.py:564: in import_path
    importlib.import_module(module_name)
/home/ryang/.cache/bazel/_bazel_ryang/7071f3e24af240fa9a28f67dc16192b3/execroot/waabi-av/external/python3/lib/python310.zip/importlib/__init__.py:126: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
:1050: in _gcd_import
    ???
:1027: in _find_and_load
    ???
:1001: in _find_and_load_unlocked
    ???
E   ModuleNotFoundError: No module named 'time.py_test'; 'time' is not a package
```

🌍 Your Environment

Operating System:

ubuntu 20.04

Output of bazel version:

7.1.2 Rules_python version:

0.31.0

aignas commented 2 months ago

This is aligned to how python itself would work. The best way to structure your project would be to have:

<root>/<name-of-the-project>/time

So that then you can import it as:

from <name-of-the-project> import time
Ryang20718 commented 2 months ago

problem is i'm not trying to import from my module, but rather the native time library. @aignas This example works in a native venv and also in our bazel 6.5 & rules_python 0.31 so we're trying to understand what changed in the uprev to 7

aignas commented 2 months ago

I think that the problem might by sys.path ordering where the standard lib is added last and example/time.py is overriding that value. What is the location of the MODULE.bazel file? is it in example directory? You will have to move it somewhere else as there is no way we can work around this if that is true.

Ryang20718 commented 2 months ago

currently we've disabled bzlmod with --noenable_bzlmod. our MODULE.bazel file lives in the at the same level as the example dir (root level of the repo)

so it looks like

repo