Search code examples
pythonc++swigdistutils

Install SWIGged Python library into dist-packages/myfoo.py, not dist-packages/myfoo/myfoo.py


I have a directory structure like

 setup.py
 myfoo/
     myfoo.i
     myfoo.cpp
     myfoo.hpp

with setup.py,

from distutils.core import setup, Extension

setup(
    name='myfoo',
    ext_modules=[
        Extension(
            '_myfoo',
            [
                'myfoo/myfoo.cpp',
                'myfoo/myfoo.i'
            ],
            swig_opts=['-c++'],
            )
        ],
    version='0.0.1',
    packages=['myfoo'],
    requires=[]
    )

myfoo.hpp

#ifndef MYFOO_HPP
#define MYFOO_HPP

int myfoo();

#endif  // MYFOO_HPP

myfoo.cpp

#include "myfoo.hpp"

#include <iostream>

int myfoo() {
  std::cout << "hey!" << std::endl;
  return 42;
}

When running python setup.py install, the package builds correctly and installs the files

/usr/local/lib/python2.7/dist-packages/
    _myfoo.so
    myfoo/
        myfoo.py
        myfoo.pyc

By default, only /usr/local/lib/python2.7/dist-packages/ is in the $PYTHONPATH, so import myfoo from anywhere yields an import error. For that to work, either both myfoo.py[c] should be in /usr/local/lib/python2.7/dist-packages/ or be renamed to __init__.py. It seems that I didn't call setup.py correctly.

Any hints?


Solution

  • Removing

    packages=['myfoo'],
    

    and adding

    py_modules = ['myfoo'],
    package_dir = {'' : 'myfoo'}
    

    to setup.py does the trick.