standard module and filename attributes, though the filename doesn’t end in a .py
or .pyc this time around—the only obvious way you can tell it’s a C library:
>>> dir(hello) # C module attributes
['__doc__', '__file__', '__name__', '__package__', 'message']
>>> hello.__name__, hello.__file__
('hello', 'hello.dll')
>>> hello.message # a C function object
<built-in function message>
>>> hello # a C module object
<module 'hello' from 'hello.dll'>
>>> hello.__doc__ # docstrings in C code
'mod doc'
>>> hello.message.__doc__
'func doc'
>>> hello.message() # errors work too
TypeError: argument must be sequence of length 1, not 0
Like any module in Python, you can also access the C extension from a script file. The
Python file in Example 20-3, for instance, imports and uses the C extension module in
Example 20-1.
Example 20-3. PP4E\Integrate\Extend\Hello\hellouse.py
"import and use a C extension library module"
import hello
print(hello.message('C'))
print(hello.message('module ' + hello.file))
for i in range(3):
reply = hello.message(str(i))
print(reply)
Run this script as any other—when the script first imports the module hello, Python
automatically finds the C module’s .dll object file in a directory on the module search
path and links it into the process dynamically. All of this script’s output represents
strings returned from the C function in the file hello.c:
.../PP4E/Integrate/Extend/Hello$ python hellouse.py
Hello, C
Hello, module /cygdrive/c/.../PP4E/Integrate/Extend/Hello/hello.dll
Hello, 0
Hello, 1
Hello, 2
See Python’s manuals for more details on the code in our C module, as well as tips for
compilation and linkage. Of note, as an alternative to makefiles, also see the
disthello.py and disthello-alt.py files in the examples package. Here’s a quick peek at
the source code of the first of these:
1490 | Chapter 20: Python/C Integration