Is pants meant to autogenerate _init_.py files whe...
# general
p
Is pants meant to autogenerate init.py files when using pants run?
f
I am sorry, what do you mean?
pants run
would execute an arbitrary script/program you pass as input arguments e.g.
pants run src/foo.py
. It is not going to create any Python files for you (unless your
src/foo.py
has the code to do this for you). There's another goal,
tailor
which will populate the BUILD files metadata, but it won't create any Python files.
p
So python needs init.py files in the directories you are importing from. Having empty init files in the src tree is a little annoying. Pex generation seems to automatically generate these empty init files when packaging pex files. FWIW Bazel generates empty init files when invoking run (though it also copies it over to a separate directory and doesn't run in place).
I found this in the issues, but am not really following the issue clearly https://github.com/pantsbuild/pants/issues/7715
f
If I remember correctly, Python doesn't require
__init__.py
files to be present in a package (it's going to be a namespace package). Pants is okay with these types of packages, e.g. if you check out https://github.com/pantsbuild/example-python and delete
Copy code
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        deleted:    helloworld/__init__.py
        deleted:    helloworld/greet/__init__.py
        deleted:    helloworld/translator/__init__.py
you can still do
Copy code
❯ pants --keep-sandboxes=always run helloworld/main.py
11:36:02.78 [INFO] Preserving local process execution dir /tmp/pants-sandbox-Rs97Xj for interactive process
Hola, pantsbuild!

❯ find  /tmp/pants-sandbox-Rs97Xj -name "__init__.py"    
/tmp/pants-sandbox-Rs97Xj/lib.pex/__pex__/__init__.py
with no
__init__.py
files added by Pants:
Copy code
❯ tree /tmp/pants-sandbox-Rs97Xj/helloworld -L 2
/tmp/pants-sandbox-Rs97Xj/helloworld
├── greet
│   ├── greeting.py
│   ├── __pycache__
│   └── translations.json
├── main.py
├── __pycache__
│   └── main.cpython-39.pyc
└── translator
    ├── __pycache__
    └── translator.py

5 directories, 5 files
there have been some work done for Pants v1 to inject the
__init__.py
files in certain cases, but it's not something I see being done in v2.
would you please create a GitHub issue with this feature request? I think it may be helpful indeed when you want to store all the code as namespace packages (without creating the
__init__.py
files at all), but be able to prevent directories with a common name, such as
string
, from unintentionally hiding valid modules that occur later on the module search path.