0

I have the following setup:

`- MyLibrary
  `- pyproject.toml
  `- setup.cfg
  `- setup.py
  `- Package1
    `- ...
  `- Package2
    `- ...
  `- CodeGen
    `- __init__.py
    `- Generate.py

and I need the install script to run a generate() function from CodeGen.Generate to include some extra code in the distribution.

I have tried the following:

from setuptools import setup, find_packages
from setuptools.command.install import install

from .CodeGen import generate

class CustomInstall(install):
    def run(self):
        install.run(self)
        generate()

setup(
    cmdclass={"install": CustomInstall},
    name="MyLibrary",
    packages=find_packages(),
)

With setuptools as my build backend. But running pip install . fails with the following error:

ImportError: attempted relative import with no known parent package

on the line from .CodeGen import generate.

How can I make it so that the CodeGen script is importable in my setup.py? Note that it depends on some package dependencies, which are listed in the [build-system] requires field of my pyproject.toml.

Alternatively, how would I achieve this differently?

sinoroc
  • 18,409
  • 2
  • 39
  • 70
Ptival
  • 9,167
  • 36
  • 53
  • In principle `from CodeGen import generate`, without leading dot `.`, as absolute import, not sure why you would want a relative import here. -- I am not 100% sure, but I think `pip install...` does not actually go through the `install` command of the `setup.py`. I think maybe you should override the `build_py` command instead, I do not remember exactly. – sinoroc Mar 17 '23 at 23:23
  • Inspiration: https://stackoverflow.com/a/71137790 – sinoroc Mar 17 '23 at 23:31
  • Ah yeah I should have mentioned, I also tried `from CodeGen import generator`, and it fails instead with something along the lines of "no such package/module". – Ptival Mar 19 '23 at 00:46
  • "*Something along the lines*"? Knowing the exact error message and the exact project structure are essential to finding the issue. -- So, is it `generate` or `generator`? Is it a function that is placed in `CodeGen/__init__.py` or what is it and in which file is it defined? -- I recreated what I "**think**" your project structure is (but I am not sure), and `from CodeGen import generate` works perfectly fine for me, as expected, no surprise. – sinoroc Mar 19 '23 at 09:19

0 Answers0