0

When I wraps a library with swig

swig -python my_ext.i

This generate a my_ext.py file.

How to add file encoding in the first line, when creating my extension with distutils.extension.Extension ?

# -*- coding: utf-8

I have tried:

%pythonbegin %{
# -*- coding: utf-8
%}

But my comment is append after swig banner.

4
  • Why? This seems pointless. Commented Nov 23, 2021 at 17:02
  • Does your SWIG output include non-ASCII characters without an encoding declaration? If so, that's a SWIG bug. (Wait, no, they changed the default in 3.0 - no encoding declaration is necessary for UTF-8.) Commented Nov 23, 2021 at 17:06
  • I use docstrings to generate the documentation. So my .i file is utf-8 and contains lots of é, è, à, ... And I also need to maintain py2 code. Commented Nov 23, 2021 at 17:08
  • Oh, you're still on Python 2? That'd explain some things. Commented Nov 23, 2021 at 17:12

1 Answer 1

1

The only solution I have found is to override the build_ext command:

from setuptools.command.build_ext import build_ext as _build_ext

if sys.version_info[0] == 2:

    class build_ext(_build_ext):

        def swig_sources(self, sources, extension):
            new_sources = _build_ext.swig_sources(self, sources, extension)
            for src in sources:
                py_src = os.path.splitext(src)[0].replace("-", "_") + ".py"
                if os.path.exists(py_src):
                    with open(py_src) as infile:
                        content = infile.read()
                    with open(py_src, "w") as outfile:
                        outfile.write("# -*- coding: utf-8 -*-\n")
                        outfile.write(content)
            return new_sources

else:

    build_ext = _build_ext

...

setup(
    cmdclass={"build_ext": build_ext},
    ...
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.