How to use setuptools packages and ext_modules with the same name?

青春壹個敷衍的年華 提交于 2019-12-01 12:32:15

You cannot. The first one imported wins. You cannot have scripts/modules/packages/extensions with the same name — one overrides all others.

But you can to have one inside another. Make your extension named fastfilepackage.fastfilepackage and you can import fastfilepackage to import the Python package and import fastfilepackage.fastfilepackage to import the extension; or from fastfilepackage import fastfilepackage.

As a final solution, I completely removed all Python *.py code because they caused the C Extensions code to become 30% slower. Now my setup.py become like this:

from setuptools import setup, Extension

setup(
        name = 'fastfilepackage',
        version = '0.1.1',

        ext_modules = [
            Extension(
                name = 'fastfilepackage',
                sources = [
                    'source/fastfile.cpp',
                ],
                include_dirs = ['source'],
            )
        ],
    )

File structure:

.
├── setup.py
├── MANIFEST.in
├── README.md
├── LICENSE.txt
└── source
    ├── fastfile.cpp
    └── version.h

MANIFEST.in

include README.md
include LICENSE.txt

recursive-include source *.h

This is the installed file structure: (No *.py files anywhere = 100% performance)

.
└── dist-packages
    ├── fastfilepackage-0.1.1.dist-info
    │   ├── INSTALLER
    │   ├── LICENSE.txt
    │   ├── METADATA
    │   ├── RECORD
    │   ├── top_level.txt
    │   └── WHEEL
    └── fastfilepackage.cpython-36m-x86_64-linux-gnu.so

I just replaced the version.py directly by a C Extensions module attribute:

// https://docs.python.org/3/c-api/arg.html#c.Py_BuildValue
const char* __version__ = "0.1.1";
PyObject_SetAttrString( thismodule, "__version__", Py_BuildValue( "s", __version__ ) );

References:

  1. Define a global in a Python module from a C API
  2. Original commit: Deprecated the Python implementation *.py
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!