Python C api: create a new object class

"Martin v. Löwis" martin at v.loewis.de
Tue Nov 10 23:17:27 CET 2009


> How can I create an instance class in Python, currently I do:
> 
> class empty:
>  pass
> 
> Then anytime I want that class (which I treat like a dictionary):
> 
> o = empty()
> o.myattr = 1
> etc....
> 
> Is there is a one line syntax to instantiate an instance?
> 
> Any other ways than this:
> o = new.classobj('object', (), {})

Most certainly:

o = empty(1) # or: o = empty(1, etc)

This requires you to define

class empty:
  def __init__(self, myattr, etc):
    self.myattr = myattr
    etc

> 2)
> 
> How can I, similarly, create an object "o" in C api:
> 
> PyObject *o = what_to_call(....)

o = PyObject_CallFunction(pointer_to_class_object, "")

> 3)
> 
> Given a PyObject* is there is a way to tell if one can call
> PyObject_SetAttrString() on that object w/o getting an error?
> 
> For example, before calling a PyObject* one can see if it is callable,
> but can I test if an object supports setattr?
> 
> (from C api)

You could check whether the object supports setattr at all, but that
would be pretty useless, since most objects do.

What you want to test (would it support setting "myattr" to the specific
value, at this point) is impossible to test: the object may give you
an exception on every third call only (or only if the value is not
an integer, etc). So just call SetAttr, and clear any exception you
get that you don't want to get.

Regards,
Martin



More information about the Python-list mailing list