Getting module object by name in C extension module

Discussion in 'Python' started by Ilariu Raducan, Jul 14, 2004.

  1. Hi All,

    Is it possible in a C extension module to get a reference to an already loaded module?
    Something like:
    PyObject* module_object = Py......("module_name");

    Thank You,
    Ilariu
    Ilariu Raducan, Jul 14, 2004
    #1
    1. Advertising

  2. "Ilariu Raducan" <> wrote in message
    news:ps7Jc.4541$...
    > Hi All,
    >
    > Is it possible in a C extension module to get a reference to an already

    loaded module?
    > Something like:
    > PyObject* module_object = Py......("module_name");
    >
    > Thank You,
    > Ilariu


    I haven't written any C extensions for a while, but looking at the
    documentation this seems to be the way to go:

    PyObject * modules = PyImport_GetModuleDict();
    PyObject * module_object = PyDict_GetItemString(modules, "module_name");

    The first line gets the value of sys.modules, and the second line looks up
    the module name in it. Both of those are borrowed references, so you don't
    need to Py_DECREF() them.

    If the module might not have been loaded, you can do this:

    PyObject * module_object = PyImport_Import("module_name");

    but then you have to Py_DECREF() module_object once you're finished.

    Nick
    Nick Smallbone, Jul 14, 2004
    #2
    1. Advertising

  3. Thank You,
    Ilariu
    >
    > I haven't written any C extensions for a while, but looking at the
    > documentation this seems to be the way to go:
    >
    > PyObject * modules = PyImport_GetModuleDict();
    > PyObject * module_object = PyDict_GetItemString(modules, "module_name");
    >
    > The first line gets the value of sys.modules, and the second line looks up
    > the module name in it. Both of those are borrowed references, so you don't
    > need to Py_DECREF() them.
    >
    > If the module might not have been loaded, you can do this:
    >
    > PyObject * module_object = PyImport_Import("module_name");
    >
    > but then you have to Py_DECREF() module_object once you're finished.
    >
    > Nick
    >
    >
    Ilariu Raducan, Jul 14, 2004
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. ding feng
    Replies:
    2
    Views:
    2,783
    ding feng
    Jun 25, 2003
  2. Anand
    Replies:
    3
    Views:
    874
    Tim Daneliuk
    Nov 8, 2003
  3. Neil.Fang.CN
    Replies:
    1
    Views:
    842
    Stefan Behnel
    Mar 10, 2008
  4. Alf P. Steinbach /Usenet
    Replies:
    0
    Views:
    208
    Alf P. Steinbach /Usenet
    Jul 10, 2010
  5. Martin
    Replies:
    6
    Views:
    172
    Richard Cornford
    Aug 20, 2004
Loading...

Share This Page