Skip to content

Add a new python comment annotation that adds targets to deps #1862

@dougthor42

Description

@dougthor42

🚀 feature request

Relevant Rules

  • gazelle

Description

Some Python modules may have "hidden" imports. One prime example of this is pyvisa when using the pyvisa-py backend. A basic Python file that uses such looks like:

# foo.py
import pyvisa

if __name__ == "__main__":
    rm = pyvisa.ResourceManager('@py')
    print(rm.list_resources())  # ('USB0::0x1AB1::0x0588::DS1K00005888::INSTR')

Note that import pyvisa_py is not present in the file.

When Gazelle runs on this file, it generates:

py_binary(
    name = "foo",
    srcs = ["foo.py"],
    deps = ["@pypi//pyvisa"],
)

However, this fails to run with ModuleNotFoundError: No module named 'pyvisa_py'.

Describe the solution you'd like

Add a new Python annotation # gazelle:include_dep that allows users to add arbitrary targets to generated deps:

# foo.py
import pyvisa

# gazelle:include_dep @pypi//pyvisa_py

if __name__ == "__main__":
    rm = pyvisa.ResourceManager('@py')
    print(rm.list_resources())  # ('USB0::0x1AB1::0x0588::DS1K00005888::INSTR')
py_binary(
    name = "foo",
    srcs = ["foo.py"],
    deps = [
        "@pypi//pyvisa",
        "@pypi//pyvisa_py",
    ],
)

A corollary would be to also add a # gazelle:include_data annotation.

Describe alternatives you've considered

The current workaround is to import the module and then just not use it:

# foo.py
import pyvisa
import pyvisa_py

del pyvisa_py  # `del` it to satisfy linters.

if __name__ == "__main__":
    rm = pyvisa.ResourceManager('@py')
    print(rm.list_resources())  # ('USB0::0x1AB1::0x0588::DS1K00005888::INSTR')

However, this doesn't allow users to add dependencies on Python targets that happen to be (a) outside of the python_root and (b) auto-run during some event1.

Footnotes

  1. One prime example is pytest's conftest.py. Gazelle already has some code that automatically adds this, but Gazelle won't add it if conftest.py is outside of of the python_root dir. Perhaps I should make a separate Issue for such...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions