create a class instance from C API?

Discussion in 'Python' started by lallous, Sep 28, 2009.

  1. lallous

    lallous Guest

    Hello

    How to programmatically create a class instance of a given Python class?

    For example to create a new list there is the PyObject *PyList_New() but
    suppose the user already defined a class:

    class X: pass

    How to create an instance of it from my C extension module?

    Regards,
    Elias
     
    lallous, Sep 28, 2009
    #1
    1. Advertising

  2. lallous

    Carl Banks Guest

    On Sep 28, 8:19 am, "lallous" <> wrote:
    > Hello
    >
    > How to programmatically create a class instance of a given Python class?
    >
    > For example to create a new list there is the PyObject *PyList_New() but
    > suppose the user already defined a class:
    >
    > class X: pass
    >
    > How to create an instance of it from my C extension module?


    Same way you'd do it in Python: call it. Use PyObject_Call or any of
    it's convenient variants. Example (leaving off all the error-checking
    stuff):

    mod = PyImport_ImportModule(modname);
    cls = PyObject_GetAttrStr(mod,classname);
    inst = PyObject_CallFunctionObjArgs(cls,NULL);


    Carl Banks
     
    Carl Banks, Sep 28, 2009
    #2
    1. Advertising

  3. lallous

    lallous Guest

    Thanks Carl, that does it!

    --
    Elias

    "Carl Banks" <> wrote in message
    news:...
    > On Sep 28, 8:19 am, "lallous" <> wrote:
    >> Hello
    >>
    >> How to programmatically create a class instance of a given Python class?
    >>
    >> For example to create a new list there is the PyObject *PyList_New() but
    >> suppose the user already defined a class:
    >>
    >> class X: pass
    >>
    >> How to create an instance of it from my C extension module?

    >
    > Same way you'd do it in Python: call it. Use PyObject_Call or any of
    > it's convenient variants. Example (leaving off all the error-checking
    > stuff):
    >
    > mod = PyImport_ImportModule(modname);
    > cls = PyObject_GetAttrStr(mod,classname);
    > inst = PyObject_CallFunctionObjArgs(cls,NULL);
    >
    >
    > Carl Banks
     
    lallous, Sep 29, 2009
    #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. Matt
    Replies:
    10
    Views:
    620
    Chris Smith
    Apr 7, 2004
  2. Sridhar R
    Replies:
    14
    Views:
    1,414
    =?iso-8859-1?Q?Fran=E7ois?= Pinard
    Feb 10, 2004
  3. Robert Oschler
    Replies:
    3
    Views:
    479
    Christopher T King
    Jul 27, 2004
  4. Sandra-24
    Replies:
    18
    Views:
    1,879
    Steve Holden
    Apr 29, 2006
  5. Martin P. Hellwig
    Replies:
    1
    Views:
    377
    Martin P. Hellwig
    Mar 26, 2010
Loading...

Share This Page