2

I'm following the C Python extension tutorial to create new type. I created the file custom.c, setup.py and added the following line to my CMakeLists.txt:

execute_process(WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} COMMAND ${PYTHON_BIN} setup.py build)

But when I run

Py_Initialize();
PyImport_AddModule("custom"));
PyRun_SimpleString("import custom\nmycustom = custom.Custom()");
PyErr_Print();

I got Attribute error: module 'custom' has no attribute 'Custom' even if I add the path to generated .pyd to sys.path

Python help on module is

Help on module custom:

NAME
    custom

FILE
    (built-in)

I am running on Windows 10 with Python 3.8

But I can import and use the module directly from a Python terminal

adub
  • 53
  • 5
  • Maybe [this](https://stackoverflow.com/questions/1250103/attributeerror-module-object-has-no-attribute) can help you – Elikill58 Sep 30 '21 at 08:39
  • No it doesn't :/ Still got Attribute error – adub Sep 30 '21 at 08:58
  • 2
    This is not very complete... (see [example]) You have to follow the instruction in that external link to recreate the error. – user202729 Sep 30 '21 at 10:14
  • Perhaps check if the "current folder" that you build the program in doesn't happen to have a file named `custom.py`, or you don't have a package named `custom`? – user202729 Sep 30 '21 at 10:14

1 Answers1

1
PyImport_AddModule("custom"));

See https://docs.python.org/3/c-api/import.html#c.PyImport_AddModuleObject; this looks in sys.modules for "custom". If it can't find it then it creates a new empty module named "custom". It does not search the path for files.

import custom

This looks in sys.modules for "custom". If it finds a module there then it returns it. If it doesn't find a module then it searches the Python path for a suitable module.

You're programmatically creating a blank module, and that is getting used instead of the module on the Python path.

DavidW
  • 29,336
  • 6
  • 55
  • 86