Commits

camlspotter  committed 669071e Merge

merge

  • Participants
  • Parent commits 419e294, 02bcacf
  • Branches dev

Comments (0)

Files changed (33)

 .*~$
 \.(sp[io]t|annot|o|cm[a-z]+|orig|omc|lock|so|a|exe|byt|opt|run)$
 \.omakedb$
-^auto\.(idl|ml|mli)
-^.*\.idl
-^auto_stubs\.c
-autoapi\.ml
+^auto\.(idl|ml|mli)$
+^.*\.idl$
+^auto_stubs\.c$
+autoapi\.ml$
+autoclasses.*$
+test$
+test_bug1$
 
 [stolen] : For argument only. The function ``steals'' reference of the argument.
 
-[internal] : For function name only. ML function is prefixed with ``_internal_''
+[internal] : For function name only. ML function is prefixed with ``_internal_''. A Wrapper ML code should be writtein in api.ml
+
+[wrap] : C function needs manual wrapping. Stub calls <function name>_wrap instead of <function name>.
+         Some example are found in auto.h
 
 Currently these new attributes are implemented by pretty dirty perl hack. They may not be used in conjunction.
 
 	omake
         perl :-)
 
+To compile:
+
+  If you are enough lucky:
+
+    % omake
+
+  just do the build.
+
+    % omake install
+
+  installs opycaml as an ocamlfind package.
+
+  Reinstall requires ocamlfind remove opycaml beforehand.
+name = "OPyCaml"
+version = "1.0.0"
+description = "( ゚∀゚)o彡°O'PyCaml"
+
+requires = ""
+
+archive(byte) = "opycaml.cma"
+archive(native) = "opycaml.cmxa"
 PY_VERSION=2.6
 CFLAGS+= -fPIC -I $(OCAML_WHERE) -I $(PY_PREFIX)/include/python$(PY_VERSION)
 
-IDLS= auto err object base string number sequence mapping misc type int import bytearray module dict tuple high
+IDLS[] = 
+    auto
+    base
+    bytearray
+    dict
+    err
+    high
+    import
+    int
+    mapping
+    misc
+    module
+    number
+    object
+    sequence
+    string
+    tuple
+    type
 
 %.idl: %.idl.in idlconvert.pl
     ./idlconvert.pl $< > $@
 
-auto.ml auto.mli auto_stubs.c: $(addsuffix .idl, $(IDLS)) $(Installed camlidl)
+autoclasses.idl autoclasses.h: classes.h.in classes.idl.in classes.pl apitype.ml
+    ./classes.pl apitype.ml
+
+auto.ml auto.mli auto_stubs.c: $(addsuffix .idl, $(IDLS)) $(Installed camlidl) autoclasses.idl autoclasses.h
 	camlidl auto.idl
 
-autoapi.ml : auto.ml automodular.pl
-    ./automodular.pl *.idl.in > $@
+autoapi.ml : auto.ml module.pl
+    ./module.pl *.idl.in > $@
 
-auto_stubs.o: auto_stubs.c auto.h api_ml.h
+auto_stubs.o: auto_stubs.c auto.h api_ml.h autoclasses.h
 
 clean:
   rm -f $(filter-proper-targets $(ls R, .))
 .DEFAULT: $(OCamlProgram test, test)
 .DEFAULT: $(OCamlProgram test_bug1, test_bug1)
 
-# 
-# PROGRAM=test
-# FILOCAML_LIBS+=opycaml.cma
-# 
-# MLMODULES= test 
-# CMOS=$(addsuffix .cmo, $(MLMODULES)) 
-# CMXS=$(addsuffix .cmx, $(MLMODULES)) 
-# CMXOS=$(addsuffix .o, $(MLMODULES)) 
-# 
-# test.byt: $(CMOS) opycaml.cma libopycaml.a dllopycaml.so
-#     $(OCamlC) -verbose -o $@ opycaml.cma $(CMOS)
-# 
-# test.exe: $(CMXS) $(CMXOS) opycaml.cmxa libopycaml.a dllopycaml.so
-#     $(OCamlOpt) -verbose -o $@ opycaml.cmxa $(CMXS)
-# 
-# .DEFAULT: test.exe
+.PHONY: install
+install: opycaml.cma opycaml.cmxa
+	$(OCAMLFIND) install opycaml opycaml.cmi opycaml.cma opycaml.cmxa opycaml.a dllopycaml.so libopycaml.a autoapi.ml api.ml META
 module Base : sig
   include module type of Base
 
-  external none : unit -> t = "opycaml_none"
+  external none : unit -> _None t = "opycaml_none"
     (** Get Py_None object. *)
 
-  external phys_eq : t -> t -> bool = "opycaml_physical_equal"
+  external phys_eq : [>_Object] t -> [>_Object] t -> bool = "opycaml_physical_equal"
     (** Checks physical equality of objects *)
 
   (* reference count functions: use with care *)
-  external refcnt : t -> int = "opycaml_refcnt"
-  external incref : t -> unit = "opycaml_incref"
-  external decref : t -> unit = "opycaml_decref"
+  external refcnt : [>_Object] t -> int = "opycaml_refcnt"
+  external incref : [>_Object] t -> unit = "opycaml_incref"
+  external decref : [>_Object] t -> unit = "opycaml_decref"
 
   (* get address of objects for debugging *)
-  external address : t -> nativeint = "opycaml_address"
+  external address : [>_Object] t -> nativeint = "opycaml_address"
 
   val initialize : unit -> unit
     (** Python api initialization with OCaml exception registeration.
 	Any other function in OPyCaml must be called after [initialize ()].
     *)
 
-  val debug : string -> t -> unit
+  val debug : string -> [>_Object] t -> unit
     (** debug print of objects *) 
 
   val main : string list -> int
 end = struct
   include Base
 
-  external none : unit -> t = "opycaml_none"
-  external phys_eq : t -> t -> bool = "opycaml_physical_equal"
-  external refcnt : t -> int = "opycaml_refcnt"
-  external incref : t -> unit = "opycaml_incref"
-  external decref : t -> unit = "opycaml_decref"
-  external address : t -> nativeint = "opycaml_address"
+  external none : unit -> _None t = "opycaml_none"
+  external poly_none : unit -> 'a t = "opycaml_none" (* unsafe *)
+  external phys_eq : [>_Object] t -> [>_Object] t -> bool = "opycaml_physical_equal"
+  external refcnt : [>_Object] t -> int = "opycaml_refcnt"
+  external incref : [>_Object] t -> unit = "opycaml_incref"
+  external decref : [>_Object] t -> unit = "opycaml_decref"
+  external address : [>_Object] t -> nativeint = "opycaml_address"
 
   external internal_init : unit -> unit = "opycaml_init"
   let initialize () =
-    Callback.register_exception "OPyCaml exception" (Error (none (), none ()));
+    Callback.register_exception "OPyCaml exception" (Error (poly_none (), poly_none ()));
     internal_init ();
     _internal_initialize ()
 
 	Err.Occured() must be return Some. Otherwise Failwith is
     raised instead. *)
 
-  val normalizeException : unit -> (t * t * t) option
+  val normalizeException : unit -> (_Object t * _Object t * _Object t) option
 end = struct
   include Err
     
 module Int : sig
   include module type of Int
 
-  val asLong : t -> int
+  val asLong : [>_Int] t -> int
     (** raises Error at overflow *)
 end = struct
   include Int
-type t
+(** class hierarchy *)
+type _Object = [`_Object]
+
+type _None = [_Object | `_None]
+
+type _Number = [_Object | `_Number]
+type _Integral = [_Number | `_Integral]
+type _Int = [_Integral | `_Int]
+type _Long = [_Integral | `_Long]
+(* Integral + bool *)
+type _Float = [_Number | `_Float]
+(* Number + real and  complex *)
+ 
+type _Sequence = [_Object | `_Sequence]
+type _String = [_Sequence | `_String]
+type _Unicode = [_String (* ? *) | `_Unicode]
+type _Tuple = [_Sequence | `_Tuple]
+type _Mutable = [_Sequence | `Mutable]
+type _List = [_Mutable | `_List]
+type _ByteArray = [_Mutable | `_ByteArray]
+(* _Set
+   _FrozenSet
+*)
+type _Mapping = [_Object | `_Mapping]
+type _Dict = [_Mapping | `_Dict]
+
+type _Callable = [_Object | `_Callable]
+
+type _Module = [_Object | `_Module]
+
+type _Type = [_Object | `_Type]
+type _Index = [_Object | `_Index]
+type _Iter = [_Object | `_Iter]
+
+type _Class = [_Object | `_Class]
+type _Slice = [_Object | `_Slice]
+
+(** the Python Object type *)
+type 'a t
+
 type unit_or_fail = unit
 type bool_or_fail = bool
 type size_or_fail = int
 type py_ssize_t = int
 type size_t = int
 
-exception Error of t (* type *) * t (* detail value *)
+exception Error of _Object t (* type *) * _Object t (* detail value *)
 
+exception Coercion
 
+(** change the type of the object. Unsafe. *)
+let unsafe_coerce : [>_Object] t -> 'a t = fun t -> Obj.magic t
 #include "api_ml.h"
-typedef PyObject * PyObject_p;
-typedef PyObject * PyObject_p_noincr;
-typedef PyObject * PyObject_p_incr;
-typedef PyObject * PyObject_p_option;
-typedef PyTypeObject * PyTypeObject_p;
-#define PyObject_ml2c(value,c) (*c = PyObject_val(value))
-#define PyObject_c2ml(c) (Val_PyObject_exc_at_null(*c))
-#define PyObject_noincr_c2ml(c) (Val_PyObject_noincr_exc_at_null(*c))
-#define PyObject_incr_ml2c(value,c) (*c = PyObject_val(value), Py_INCREF(*c))
-#define PyObject_option_ml2c(value,c) (*c = PyObject_opt_val(value))
-#define PyObject_option_c2ml(c) (Val_PyObject_opt(*c, 0))
+
+#include "autoclasses.h"
+
 #define unit_or_fail_c2ml(p) (Plus_or_fail(*p))
 #define bool_or_fail_c2ml(p) (Plus_or_fail(*p))
 #define size_or_fail_c2ml(p) (Plus_or_fail(*p))
 typedef int bool_or_fail;
 typedef int size_or_fail;
 typedef long hash_or_fail;
+
+// [wrap] wrappers
+#define PyType_HasFeature_wrap(o,i) PyType_HasFeature((PyTypeObject*)o,i)
+#define PyType_IS_GC_wrap(o) PyType_IS_GC((PyTypeObject*)o)
+#define PyType_IsSubtype_wrap(o,i) PyType_IsSubtype((PyTypeObject*)o,i)
+#define PyType_Modified_wrap(o) PyType_Modified((PyTypeObject*)o)
-typedef [abstract,ml2c(PyObject_ml2c),c2ml(PyObject_c2ml)] void * PyObject_p;
-typedef [abstract,c2ml(PyObject_noincr_c2ml)] void * PyObject_p_noincr;
-typedef [abstract,ml2c(PyObject_incr_ml2c)] void * PyObject_p_incr;
-typedef [abstract,ml2c(PyObject_option_ml2c),c2ml(PyObject_option_c2ml)] void * PyObject_p_option;
-// typedef [abstract,ml2c(PyTypeObject_ml2c),c2ml(PyTypeObject_c2ml)] void * PyTypeObject_p;
+#include "autoclasses.idl"
+
 typedef [abstract,c2ml(unit_or_fail_c2ml)] int unit_or_fail;
 typedef [abstract,c2ml(bool_or_fail_c2ml)] int bool_or_fail;
 typedef [abstract,c2ml(hash_or_fail_c2ml)] long hash_or_fail;

File automodular.pl

-#!/usr/bin/perl
-
-get_comments();
-filter();
-
-sub get_comments {
-    for $i (@ARGV){
-	open(IN, "$i");
-	while(<IN>){
-	    if( /^typedef/ ){ next; }
-	    if( /^\s*$/ ){ next; }
-	    if( /^\s*\/\// ){ next; }
-	    if( /(Py[A-Za-z_0-9]+)\(/ ){
-		$func_name = $1;
-		if( /\[internal\]/ ){
-		    $internal{$func_name} = 1;
-		}
-		while(<IN>){
-		    if( /^\/\/\s*/ ){
-			$_ = $';
-		        s/\(\*/( */g;
-		        $comment{$func_name} = "$comment{$func_name}$_";
-		    } else { last; }
-                }  
-	    }
-	}
-    }
-}
-
-sub filter {
-    open(IN, "auto.ml");
-    while(<IN>){
-        if( /^(type|and) [a-z][A-Za-z_0-9]+( =.*)?$/ ){ next; }
-        if ( s/^external // ){
-	    $def = <IN>;
-	    s/^py([A-Za-z]*)?_([^ ]*)//;
-
-	    $k = $1; # kind
-	    $f = $2;
-	    $rem = $';
-
-	    $fname = $&;
-	    $fname =~ s/py/Py/;
-	    $comment = $comment{$fname};
-            $comment =~ s/\n/\n      /g;
-            $internal = $internal{$fname};
-
-            # $f =~ s/GET_SIZE/get_size/;
-            if( $f =~ /^[A-Z_]+$/ ){
-                $f = "_$f";
-            } else {
-      	        $f = lcfirst($f);
-            }
-    	    $f =~ s/^(type|and|or|new)$/$1_/;
-            if( $internal ){ $f = "_internal_$f"; }
-    
-            # rem includes type 
-            $rem =~ s/pyObject_p_option/t option/g;
-            $rem =~ s/pyObject_p_noincr/t/g;
-            $rem =~ s/pyObject_p_incr/t/g;
-            $rem =~ s/pyObject_p/t/g;
-    
-    	    if ( $k eq "" ){ $k = "Base"; }
-            if( $comment ne "" ){
-    	        $mod{$k} = "$mod{$k}  external $f $rem$def  (** $comment **)\n\n";
-            } else {
-    	        $mod{$k} = "$mod{$k}  external $f $rem$def\n";
-            }
-        } 
-    }
-
-    print "open Apitype\n\n";
-    for $k (keys %mod){
-        print "module $k = struct\n";
-        print $mod{$k};
-        print "end\n\n";
-    }
-}
-

File bytearray.idl.in

 boolean PyByteArray_CheckExact(PyObject *o);
 //    Return true if the object o is a bytearray object, but not an instance of a subtype of the bytearray type.
 
-[new] PyObject* PyByteArray_FromObject(PyObject *o);
+[new] PyByteArrayObject* PyByteArray_FromObject(PyObject *o);
 //    Return a new bytearray object from any object, o, that implements the buffer protocol.
 
-[new] PyObject* PyByteArray_FromStringAndSize([string] const char *string, Py_ssize_t len);
+[new] PyByteArrayObject* PyByteArray_FromStringAndSize([string] const char *string, Py_ssize_t len);
 //    Create a new bytearray object from string and its length, len. On failure, NULL is returned.
 
-[new] PyObject* PyByteArray_Concat(PyObject *a, PyObject *b);
+[new] PyByteArrayObject* PyByteArray_Concat(PyByteArrayObject *a, PyByteArrayObject *b);
 //    Concat bytearrays a and b and return a new bytearray with the result.
 
-size_or_fail PyByteArray_Size(PyObject *bytearray);
+size_or_fail PyByteArray_Size(PyByteArrayObject *bytearray);
 //    Return the size of bytearray after checking for a NULL pointer.
 
-[string] char* PyByteArray_AsString(PyObject *bytearray);
+[string] char* PyByteArray_AsString(PyByteArrayObject *bytearray);
 //    Return the contents of bytearray as a char array after checking for a NULL pointer.
 
-unit_or_fail /* ? */ PyByteArray_Resize(PyObject *bytearray, Py_ssize_t len); // return type is int
+unit_or_fail /* ? */ PyByteArray_Resize(PyByteArrayObject *bytearray, Py_ssize_t len); // return type is int
 //    Resize the internal buffer of bytearray to len.
 
 // These macros trade safety for speed and they don’t check pointers.
 
-[string] char* PyByteArray_AS_STRING(PyObject *bytearray);
+[string] char* PyByteArray_AS_STRING(PyByteArrayObject *bytearray);
 //    Macro version of PyByteArray_AsString().
 
-Py_ssize_t PyByteArray_GET_SIZE(PyObject *bytearray);
+Py_ssize_t PyByteArray_GET_SIZE(PyByteArrayObject *bytearray);
 //    Macro version of PyByteArray_Size().
 

File classes.h.in

+typedef PyObject * Py##name##_p;
+typedef PyObject * Py##name##_p_noincr;
+typedef PyObject * Py##name##_p_incr;
+typedef PyObject * Py##name##_p_option;
+#define Py##name##_ml2c(value,c) (*c = PyObject_val(value))
+#define Py##name##_c2ml(c) (Val_PyObject_exc_at_null(*c))
+#define Py##name##_noincr_c2ml(c) (Val_PyObject_noincr_exc_at_null(*c))
+#define Py##name##_incr_ml2c(value,c) (*c = PyObject_val(value), Py_INCREF(*c))
+#define Py##name##_option_ml2c(value,c) (*c = PyObject_opt_val(value))
+#define Py##name##_option_c2ml(c) (Val_PyObject_opt(*c, 0))

File classes.idl.in

+typedef [abstract,ml2c(Py##name##_ml2c),c2ml(Py##name##_c2ml)] void * Py##name##_p;
+typedef [abstract,c2ml(Py##name##_noincr_c2ml)] void * Py##name##_p_noincr;
+typedef [abstract,ml2c(Py##name##_incr_ml2c)] void * Py##name##_p_incr;
+typedef [abstract,ml2c(Py##name##_option_ml2c),c2ml(Py##name##_option_c2ml)] void * Py##name##_p_option;
+#!/usr/bin/perl
+
+while(<>){
+    if( /^type\s+_([A-Z][A-Za-z]+)\s*=/ ){
+	$cls = $1;
+	if( !$done{$cls} ){
+	    print STDERR "CLASS: $cls\n";
+	    $done{$cls} = 1;
+	}
+	$_ = $';
+    }
+}
+
+$str="";
+open(IN, "classes.h.in");
+while(<IN>){
+    $str = "$str$_";
+}
+open(OUT, "> autoclasses.h");
+for $cls (keys %done) {
+    if( $cls ne "Object" ){ $cls = $cls . "Object"; }
+    $mystr = $str;
+    $mystr =~ s/##name##/$cls/g;
+    print OUT $mystr;
+}
+close OUT;
+
+$str="";
+open(IN, "classes.idl.in");
+while(<IN>){
+    $str = "$str$_";
+}
+open(OUT, "> autoclasses.idl");
+for $cls (keys %done) {
+    if( $cls ne "Object" ){ $cls = $cls . "Object"; }
+    $mystr = $str;
+    $mystr =~ s/##name##/$cls/g;
+    print OUT $mystr;
+}
+close OUT;
 boolean PyDict_CheckExact(PyObject *p);
 // aReturn true if p is a dict object, but not an instance of a subtype of the dict type.
 
-[new] PyObject* PyDict_New();
+[new] PyDictObject* PyDict_New();
 // Return value: New reference.
 // Return a new empty dictionary, or NULL on failure.
 
-[new] PyObject* PyDictProxy_New(PyObject *dict);
+[new] PyObject* PyDictProxy_New(PyDictObject *dict);
 // Return value: New reference.
 // Return a proxy object for a mapping which enforces read-only behavior. This is normally used to create a proxy to prevent modification of the dictionary for non-dynamic class types.
 
 // No error ?!?!
-void PyDict_Clear(PyObject *p);
+void PyDict_Clear(PyDictObject *p);
 // Empty an existing dictionary of all key-value pairs.
 
-bool_or_fail PyDict_Contains(PyObject *p, PyObject *key);
+bool_or_fail PyDict_Contains(PyDictObject *p, PyObject *key);
 // Determine if dictionary p contains key. If an item in p is matches key, return 1, otherwise return 0. On error, return -1. This is equivalent to the Python expression key in p.
 
-[new] PyObject* PyDict_Copy(PyObject *p);
+[new] PyDictObject* PyDict_Copy(PyDictObject *p);
 // Return value: New reference.
 // Return a new dictionary that contains the same key-value pairs as p.
 
-unit_or_fail PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val);
+unit_or_fail PyDict_SetItem(PyDictObject *p, PyObject *key, PyObject *val);
 // Insert value into the dictionary p with a key of key. key must be hashable; if it isn’t, TypeError will be raised. Return 0 on success or -1 on failure.
 
-unit_or_fail PyDict_SetItemString(PyObject *p, [string] const char *key, PyObject *val);
+unit_or_fail PyDict_SetItemString(PyDictObject *p, [string] const char *key, PyObject *val);
 // Insert value into the dictionary p using key as a key. key should be a char*. The key object is created using PyString_FromString(key). Return 0 on success or -1 on failure.
 
-unit_or_fail PyDict_DelItem(PyObject *p, PyObject *key);
+unit_or_fail PyDict_DelItem(PyDictObject *p, PyObject *key);
 // Remove the entry in dictionary p with key key. key must be hashable; if it isn’t, TypeError is raised. Return 0 on success or -1 on failure.
 
-int PyDict_DelItemString(PyObject *p, [string] char *key);
+int PyDict_DelItemString(PyDictObject *p, [string] char *key);
 // Remove the entry in dictionary p which has a key specified by the string key. Return 0 on success or -1 on failure.
 
-PyObject* PyDict_GetItem(PyObject *p, PyObject *key);
+PyObject* PyDict_GetItem(PyDictObject *p, PyObject *key);
 // Return value: Borrowed reference.
 // Return the object from dictionary p which has a key key. Return NULL if the key key is not present, but without setting an exception.
 
-PyObject* PyDict_GetItemString(PyObject *p, [string] const char *key);
+PyObject* PyDict_GetItemString(PyDictObject *p, [string] const char *key);
 // Return value: Borrowed reference.
 // This is the same as PyDict_GetItem(), but key is specified as a char*, rather than a PyObject*.
 
-[new] PyObject* PyDict_Items(PyObject *p);
+[new] PyObject* PyDict_Items(PyDictObject *p);
 // Return value: New reference.
 // Return a PyListObject containing all the items from the dictionary, as in the dictionary method dict.items().
 
-[new] PyObject* PyDict_Keys(PyObject *p);
+[new] PyObject* PyDict_Keys(PyDictObject *p);
 // Return value: New reference.
 // Return a PyListObject containing all the keys from the dictionary, as in the dictionary method dict.keys().
 
-[new] PyObject* PyDict_Values(PyObject *p);
+[new] PyObject* PyDict_Values(PyDictObject *p);
 // Return value: New reference.
 // Return a PyListObject containing all the values from the dictionary p, as in the dictionary method dict.values().
 
-size_or_fail PyDict_Size(PyObject *p);
+size_or_fail PyDict_Size(PyDictObject *p);
 // Return the number of items in the dictionary. This is equivalent to len(p) on a dictionary.
 
-// int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
+// int PyDict_Next(PyDictObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
 // Iterate over all key-value pairs in the dictionary p. The Py_ssize_t referred to by ppos must be initialized to 0 prior to the first call to this function to start the iteration; the function returns true for each pair in the dictionary, and false once all pairs have been reported. The parameters pkey and pvalue should either point to PyObject* variables that will be filled in with each key and value, respectively, or may be NULL. Any references returned through them are borrowed. ppos should not be altered during iteration. Its value represents offsets within the internal dictionary structure, and since the structure is sparse, the offsets are not consecutive.
 // 
 // For example:
 //     Py_DECREF(o);
 // }
 
-unit_or_fail PyDict_Merge(PyObject *a, PyObject *b, boolean override);
+unit_or_fail PyDict_Merge(PyDictObject *a, PyObject *b, boolean override);
 // Iterate over mapping object b adding key-value pairs to dictionary a. b may be a dictionary, or any object supporting PyMapping_Keys() and PyObject_GetItem(). If override is true, existing pairs in a will be replaced if a matching key is found in b, otherwise pairs will only be added if there is not a matching key in a. Return 0 on success or -1 if an exception was raised.
 
-unit_or_fail PyDict_Update(PyObject *a, PyObject *b);
+unit_or_fail PyDict_Update(PyDictObject *a, PyObject *b);
 // This is the same as PyDict_Merge(a, b, 1) in C, or a.update(b) in Python. Return 0 on success or -1 if an exception was raised.
 
-unit_or_fail PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, boolean override);
+unit_or_fail PyDict_MergeFromSeq2(PyDictObject *a, PyObject *seq2, boolean override);
 // Update or merge into dictionary a, from the key-value pairs in seq2. seq2 must be an iterable object producing iterable objects of length 2, viewed as key-value pairs. In case of duplicate keys, the last wins if override is true, else the first wins. Return 0 on success or -1 if an exception was raised. Equivalent Python (except for the return value):
 // 
 // def PyDict_MergeFromSeq2(a, seq2, override):

File example/OMakefile

+USE_OCAMLFIND=true
+
+OCAMLPACKS = opycaml
+
+.DEFAULT: $(OCamlProgram test, test)
+
+.PHONY: clean
+clean:
+  rm -f $(filter-proper-targets $(ls R, .))

File example/OMakeroot

+########################################################################
+# Permission is hereby granted, free of charge, to any person
+# obtaining a copy of this file, to deal in the File without
+# restriction, including without limitation the rights to use,
+# copy, modify, merge, publish, distribute, sublicense, and/or
+# sell copies of the File, and to permit persons to whom the
+# File is furnished to do so, subject to the following condition:
+#
+# THE FILE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE FILE OR
+# THE USE OR OTHER DEALINGS IN THE FILE.
+
+########################################################################
+# The standard OMakeroot file.
+# You will not normally need to modify this file.
+# By default, your changes should be placed in the
+# OMakefile in this directory.
+#
+# If you decide to modify this file, note that it uses exactly
+# the same syntax as the OMakefile.
+#
+
+#
+# Include the standard installed configuration files.
+# Any of these can be deleted if you are not using them,
+# but you probably want to keep the Common file.
+#
+open build/C
+open build/OCaml
+open build/LaTeX
+
+#
+# The command-line variables are defined *after* the
+# standard configuration has been loaded.
+#
+DefineCommandVars()
+
+#
+# Include the OMakefile in this directory.
+#
+.SUBDIRS: .

File example/test.ml

+open Opycaml.Api
+
+let _ = 
+  prerr_endline "start";
+  Base.initialize ()
+;;
+
+let _ =
+  try
+    ignore (Import.importModule "hogehoge")
+  with
+  | Error (e, detail) ->
+      Printf.eprintf "Error: %s %s\n%!" (String.asString (Object.repr e)) (String.asString (Object.repr detail))
+;;
+
+let _ =
+  let o = String.fromString "hello world" in
+  Base.debug "o" o;
+
+  assert (Base.phys_eq o o);
+  let repr = Object.repr o in
+  Base.debug "repr" repr;
+  let hash = Object.hash o in
+  Printf.eprintf "hash=%nd\n%!" hash;
+
+  try
+    let stringModule = Import.importModule "string" in (* from string import * *)
+    Base.debug "stringModule" stringModule;
+    let dict = Module.getDict stringModule in
+    (* Base.debug "dict" dict; *)
+    let lowercase = Dict.getItemString dict "lowercase" in
+    Base.debug "lowercase" lowercase;
+
+    let capitalize = Dict.getItemString dict "capitalize" in
+    Base.debug "capitalize" capitalize;
+
+    if not (Callable.check capitalize) then begin
+      prerr_endline "capitalize is not a function!";
+      failwith "capitalize is not a function!";
+    end;
+
+    let tpl = Tuple.new_ 1 in
+    Base.debug "tpl" tpl;
+
+    Base.debug "o" o;
+
+    prerr_endline "tuple setting";
+    
+    Tuple.setItem tpl 0 o;
+
+    prerr_endline "tuple set";
+    Base.debug "tuple" tpl;
+    Base.debug "o" o; (* ref by tuple and o *)
+
+    prerr_endline "getItem";
+    let x = Tuple.getItem tpl 0 in
+    Base.debug "x" x; (* ref by tuple, o and x *) 
+    Base.debug "o" o; (* ref by tuple, o and x *) 
+
+    let xx = Tuple._GET_ITEM tpl 0 in
+    Base.debug "xx" xx; (* ref by tuple, o, x and xx *)
+    Base.debug "o" o;
+
+    prerr_endline "calling function";
+    let res = Object.callObject capitalize (Some tpl) in
+    Printf.eprintf "res : refcnt = %d\n%!" (Base.refcnt res);
+    prerr_endline "function called!";
+    prerr_endline (String.asString res);
+    prerr_endline (String.asString o);
+
+    let minus_1 = Int.fromLong (-1) in
+    assert (Int.asLong minus_1 = -1); 
+
+    Run.simpleString "print 'Run.simpleString'";
+    (* Run.simpleString "print(string.lowercase)"; *) (* does not work *)
+    (* Run.simpleString "print(lowercase)"; *) (* does not work *)
+
+    ignore (Base.main []);
+    prerr_endline "exited from toploop";
+
+  with
+  | Error (e, detail) -> 
+      Printf.eprintf "Error: %s %s\n%!" (String.asString (Object.repr e)) (String.asString (Object.repr detail))
+;;
+
+let _ = Base.finalize ()

File idlconvert.pl

 #!/usr/bin/perl
 while(<>){
-    s/Py([A-Za-z]*)Object[ ]*\*/Py$1Object_p /g;
+    s/Py([A-Za-z]*)[ ]*\*/Py$1_p /g;
     s/\[option\]\s*([A-Za-z0-9_]+)/$1_option/g;
     s/\[new\]\s*([A-Za-z0-9_]+)/$1_noincr/g;
     s/\[stolen\]\s*([A-Za-z0-9_]+)/$1_incr/g;
     s/\[internal\]//g;
+    s/\[wrap\] ([A-Za-z0-9_]+)/$1_wrap/g; # in ML side, _wrap must be removed (module.pl)
     if( /^[^\/]/ ){
         s/value/value_/g;
     }

File import.idl.in

 // ------------------ Importing modules
 
-[new] PyObject* PyImport_ImportModule([string] const char  *name);
+[new] PyModuleObject* PyImport_ImportModule([string] const char  *name);
 //    Return value: New reference.
 //    This is a simplified interface to PyImport_ImportModuleEx() below, leaving the globals and locals arguments set to NULL and level set to 0. When the name argument contains a dot (when it specifies a submodule of a package), the fromlist argument is set to the list ['*'] so that the return value is the named module rather than the top-level package containing it as would otherwise be the case. (Unfortunately, this has an additional side effect when name in fact specifies a subpackage instead of a submodule: the submodules specified in the package’s __all__ variable are loaded.) Return a new reference to the imported module, or NULL with an exception set on failure. Before Python 2.4, the module may still be created in the failure case — examine sys.modules to find out. Starting with Python 2.4, a failing import of a module no longer leaves the module in sys.modules.
 
-[new] PyObject* PyImport_ImportModuleNoBlock([string] const char *name);
+[new] PyModuleObject* PyImport_ImportModuleNoBlock([string] const char *name);
 //    This version of PyImport_ImportModule() does not block. It’s intended to be used in C functions that import other modules to execute a function. The import may block if another thread holds the import lock. The function PyImport_ImportModuleNoBlock() never blocks. It first tries to fetch the module from sys.modules and falls back to PyImport_ImportModule() unless the lock is held, in which case the function will raise an ImportError.
 
 // PyObject* PyImport_ImportModuleEx([string] char *name, PyObject *globals, PyObject *locals, PyObject *fromlist);
 //    Import a module. This is best described by referring to the built-in Python function __import__(), as the standard __import__() function calls this function directly.
 //    The return value is a new reference to the imported module or top-level package, or NULL with an exception set on failure. Like for __import__(), the return value when a submodule of a package was requested is normally the top-level package, unless a non-empty fromlist was given.
 
-[new] PyObject* PyImport_Import(PyObject *name);
+[new] PyModuleObject* PyImport_Import(PyObject *name);
 //    Return value: New reference.
 //    This is a higher-level interface that calls the current “import hook function”. It invokes the __import__() function from the __builtins__ of the current globals. This means that the import is done using whatever import hooks are installed in the current environment, e.g. by rexec or ihooks.
 
-[new] PyObject* PyImport_ReloadModule(PyObject *m);
+[new] PyModuleObject* PyImport_ReloadModule(PyObject *m);
 //    Return value: New reference.
 //    Reload a module. This is best described by referring to the built-in Python function reload(), as the standard reload() function calls this function directly. Return a new reference to the reloaded module, or NULL with an exception set on failure (the module still exists in this case).
 
-PyObject* PyImport_AddModule([string] const char *name);
+PyModuleObject* PyImport_AddModule([string] const char *name);
 //    Return value: Borrowed reference.
 //    Return the module object corresponding to a module name. The name argument may be of the form package.module. First check the modules dictionary if there’s one there, and if not, create a new one and insert it in the modules dictionary. Return NULL with an exception set on failure.
 //    Note
 //    This function does not load or import the module; if the module wasn’t already loaded, you will get an empty module object. Use PyImport_ImportModule() or one of its variants to import a module. Package structures implied by a dotted name for name are not created if not already present.
 
-[new] PyObject* PyImport_ExecCodeModule([string] char *name, PyObject *co);
+[new] PyModuleObject* PyImport_ExecCodeModule([string] char *name, PyObject *co);
 //    Return value: New reference.
 //    Given a module name (possibly of the form package.module) and a code object read from a Python bytecode file or obtained from the built-in function compile(), load the module. Return a new reference to the module object, or NULL with an exception set if an error occurred. Before Python 2.4, the module could still be created in error cases. Starting with Python 2.4, name is removed from sys.modules in error cases, and even if name was already in sys.modules on entry to PyImport_ExecCodeModule(). Leaving incompletely initialized modules in sys.modules is dangerous, as imports of such modules have no way to know that the module object is an unknown (and probably damaged with respect to the module author’s intents) state.
 //    The module’s __file__ attribute will be set to the code object’s co_filename.
 //    This function will reload the module if it was already imported. See PyImport_ReloadModule() for the intended way to reload a module.
 //    If name points to a dotted name of the form package.module, any package structures not already created will still not be created.
 
-[new] PyObject* PyImport_ExecCodeModuleEx([string] char *name, PyObject *co, [string] char *pathname);
+[new] PyModuleObject* PyImport_ExecCodeModuleEx([string] char *name, PyObject *co, [string] char *pathname);
 //    Return value: New reference.
 //    Like PyImport_ExecCodeModule(), but the __file__ attribute of the module object is set to pathname if it is non-NULL.
 
 long PyImport_GetMagicNumber();
 //    Return the magic number for Python bytecode files (a.k.a. .pyc and .pyo files). The magic number should be present in the first four bytes of the bytecode file, in little-endian byte order.
 
-PyObject* PyImport_GetModuleDict(); // Borrowed reference!
+PyDictObject* PyImport_GetModuleDict(); // Borrowed reference!
 //    Return value: Borrowed reference.
 //    Return the dictionary used for the module administration (a.k.a. sys.modules). Note that this is a per-interpreter variable.
 
 //    Return value: New reference.
 //    Return a new PyIntObject or PyLongObject based on the string value in str, which is interpreted according to the radix in base. If pend is non-NULL, *pend will point to the first character in str which follows the representation of the number. If base is 0, the radix will be determined based on the leading characters of str: if str starts with '0x' or '0X', radix 16 will be used; if str starts with '0', radix 8 will be used; otherwise radix 10 will be used. If base is not 0, it must be between 2 and 36, inclusive. Leading spaces are ignored. If there are no digits, ValueError will be raised. If the string represents a number too large to be contained within the machine’s long int type and overflow warnings are being suppressed, a PyLongObject will be returned. If overflow warnings are not being suppressed, NULL will be returned in this case.
 
-[new] PyObject* PyInt_FromLong(long ival);
+[new] PyIntObject* PyInt_FromLong(long ival);
 //    Return value: New reference.
 //    Create a new integer object with a value of ival.
 //    The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)
 
-[new] PyObject* PyInt_FromSsize_t(Py_ssize_t ival);
+[new] PyIntObject* PyInt_FromSsize_t(Py_ssize_t ival);
 //    Return value: New reference.
 //    Create a new integer object with a value of ival. If the value is larger than LONG_MAX or smaller than LONG_MIN, a long integer object is returned.
 
-[new] PyObject* PyInt_FromSize_t(size_t ival);
+[new] PyIntObject* PyInt_FromSize_t(size_t ival);
 //    Create a new integer object with a value of ival. If the value exceeds LONG_MAX, a long integer object is returned.
 
-long [internal] PyInt_AsLong(PyObject *io);
+long [internal] PyInt_AsLong(PyIntObject *io);
 //    Will first attempt to cast the object to a PyIntObject, if it is not already one, and then return its value. If there is an error, -1 is returned, and the caller should check PyErr_Occurred() to find out whether there was an error, or whether the value just happened to be -1.
 
 // long PyInt_AS_LONG(PyObject *io);
 // unsigned PY_LONG_LONG PyInt_AsUnsignedLongLongMask(PyObject *io);
 //    Will first attempt to cast the object to a PyIntObject or PyLongObject, if it is not already one, and then return its value as unsigned long long, without checking for overflow.
 
-size_or_fail PyInt_AsSsize_t(PyObject *io);
+size_or_fail PyInt_AsSsize_t(PyIntObject *io);
 //    Will first attempt to cast the object to a PyIntObject or PyLongObject, if it is not already one, and then return its value as Py_ssize_t.
 
 long PyInt_GetMax();

File mapping.idl.in

 boolean PyMapping_Check(PyObject  *o);
 // Return 1 if the object provides mapping protocol, and 0 otherwise. This function always succeeds.
 
-size_or_fail PyMapping_Size(PyObject *o);
-size_or_fail PyMapping_Length(PyObject *o);
+size_or_fail PyMapping_Size(PyMappingObject *o);
+size_or_fail PyMapping_Length(PyMappingObject *o);
 // Returns the number of keys in object o on success, and -1 on failure. For objects that do not provide mapping protocol, this is equivalent to the Python expression len(o).
 
-unit_or_fail PyMapping_DelItemString(PyObject *o, [string] char *key);
+unit_or_fail PyMapping_DelItemString(PyMappingObject *o, [string] char *key);
 // Remove the mapping for object key from the object o. Return -1 on failure. This is equivalent to the Python statement del o[key].
 
-unit_or_fail PyMapping_DelItem(PyObject *o, PyObject *key);
+unit_or_fail PyMapping_DelItem(PyMappingObject *o, PyObject *key);
 // Remove the mapping for object key from the object o. Return -1 on failure. This is equivalent to the Python statement del o[key].
 
-boolean PyMapping_HasKeyString(PyObject *o, [string] char *key);
+boolean PyMapping_HasKeyString(PyMappingObject *o, [string] char *key);
 // On success, return 1 if the mapping object has the key key and 0 otherwise. This is equivalent to o[key], returning True on success and False on an exception. This function always succeeds.
 
-boolean PyMapping_HasKey(PyObject *o, PyObject *key);
+boolean PyMapping_HasKey(PyMappingObject *o, PyObject *key);
 // Return 1 if the mapping object has the key key and 0 otherwise. This is equivalent to o[key], returning True on success and False on an exception. This function always succeeds.
 
-[new] PyObject* PyMapping_Keys(PyObject *o);
+[new] PyListObject* PyMapping_Keys(PyMappingObject *o);
 // Return value: New reference.
 // On success, return a list of the keys in object o. On failure, return NULL. This is equivalent to the Python expression o.keys().
 
-[new] PyObject* PyMapping_Values(PyObject *o);
+[new] PyListObject* PyMapping_Values(PyMappingObject *o);
 // Return value: New reference.
 // On success, return a list of the values in object o. On failure, return NULL. This is equivalent to the Python expression o.values().
 
-[new] PyObject* PyMapping_Items(PyObject *o);
+[new] PyListObject* PyMapping_Items(PyMappingObject *o);
 // Return value: New reference.
 // On success, return a list of the items in object o, where each item is a tuple containing a key-value pair. On failure, return NULL. This is equivalent to the Python expression o.items().
 
-[new] PyObject* PyMapping_GetItemString(PyObject *o, [string] char *key);
+[new] PyObject* PyMapping_GetItemString(PyMappingObject *o, [string] char *key);
 // Return value: New reference.
 // Return element of o corresponding to the object key or NULL on failure. This is the equivalent of the Python expression o[key].
 
-unit_or_fail PyMapping_SetItemString(PyObject *o, [string] char *key, PyObject *v);
+unit_or_fail PyMapping_SetItemString(PyMappingObject *o, [string] char *key, PyObject *v);
 // Map the object key to the value v in object o. Returns -1 on failure. This is the equivalent of the Python statement o[key] = v.
 
 boolean PyIter_Check(PyObject *o);
 // Return true if the object o supports the iterator protocol.
 
-[new] PyObject* PyIter_Next(PyObject *o);
+[new] PyObject* PyIter_Next(PyIterObject *o);
 // Return value: New reference.
 // Return the next value from the iteration o. If the object is an iterator, this retrieves the next value from the iteration, and returns NULL with no exception set if there are no remaining items. If the object is not an iterator, TypeError is raised, or if there is an error in retrieving the item, returns NULL and passes along the exception.
 

File module.idl.in

 boolean PyModule_CheckExact(PyObject *p);
 // Return true if p is a module object, but not a subtype of PyModule_Type.
 
-[new] PyObject* PyModule_New([string] const char *name);
+[new] PyModuleObject* PyModule_New([string] const char *name);
 // Return value: New reference.
 // Return a new module object with the __name__ attribute set to name. Only the module’s __doc__ and __name__ attributes are filled in; the caller is responsible for providing a __file__ attribute.
 
-PyObject* PyModule_GetDict(PyObject *module);
+PyDictObject* PyModule_GetDict(PyModuleObject *module);
 // Return value: Borrowed reference.
 // Return the dictionary object that implements module‘s namespace; this object is the same as the __dict__ attribute of the module object. This function never fails. It is recommended extensions use other PyModule_*() and PyObject_*() functions rather than directly manipulate a module’s __dict__.
 
-[string] char* PyModule_GetName(PyObject *module);
+[string] char* PyModule_GetName(PyModuleObject *module);
 // Return module‘s __name__ value. If the module does not provide one, or if it is not a string, SystemError is raised and NULL is returned.
 
-[string] char* PyModule_GetFilename(PyObject *module);
+[string] char* PyModule_GetFilename(PyModuleObject *module);
 // Return the name of the file from which module was loaded using module‘s __file__ attribute. If this is not defined, or if it is not a string, raise SystemError and return NULL.
 
-unit_or_fail PyModule_AddObject(PyObject *module, [string] const char *name, [stolen] PyObject *value);
+unit_or_fail PyModule_AddObject(PyModuleObject *module, [string] const char *name, [stolen] PyObject *value);
 // Add an object to module as name. This is a convenience function which can be used from the module’s initialization function. This steals a reference to value. Return -1 on error, 0 on success.
 
-unit_or_fail PyModule_AddIntConstant(PyObject *module, [string] const char *name, long value);
+unit_or_fail PyModule_AddIntConstant(PyModuleObject *module, [string] const char *name, long value);
 // Add an integer constant to module as name. This convenience function can be used from the module’s initialization function. Return -1 on error, 0 on success.
 
-unit_or_fail PyModule_AddStringConstant(PyObject *module, [string] const char *name, [string] const char *value);
+unit_or_fail PyModule_AddStringConstant(PyModuleObject *module, [string] const char *name, [string] const char *value);
 // Add a string constant to module as name. This convenience function can be used from the module’s initialization function. The string value must be null-terminated. Return -1 on error, 0 on success.
 
 // unit_or_fail PyModule_AddIntMacro(PyObject *module, macro);
+#!/usr/bin/perl
+
+get_comments();
+filter();
+
+sub get_comments {
+    for $i (@ARGV){
+	open(IN, "$i");
+	while(<IN>){
+	    if( /^typedef/ ){ next; }
+	    if( /^\s*$/ ){ next; }
+	    if( /^\s*\/\// ){ next; }
+	    if( /(Py[A-Za-z_0-9]+)\(/ ){
+		$func_name = $1;
+		if( /\[internal\]/ ){
+		    $internal{$func_name} = 1;
+		}
+		while(<IN>){
+		    if( /^\/\/\s*/ ){
+			$_ = $';
+		        s/\(\*/( */g;
+		        $comment{$func_name} = "$comment{$func_name}$_";
+		    } else { last; }
+                }  
+	    }
+	}
+    }
+}
+
+sub filter {
+    open(IN, "auto.ml");
+    while(<IN>){
+        if( /^(type|and) [a-z][A-Za-z_0-9]+( =.*)?$/ ){ next; }
+        if ( s/^external // ){
+	    $def = <IN>;
+	    s/^py([A-Za-z]*)?_([^ ]*)//;
+
+	    $k = $1; # kind
+	    $f = $2;
+	    $rem = $';
+
+	    $fname = $&;
+	    $fname =~ s/py/Py/;
+	    $comment = $comment{$fname};
+            $comment =~ s/\n/\n      /g;
+            $internal = $internal{$fname};
+
+            # $f =~ s/GET_SIZE/get_size/;
+            if( $f =~ /^[A-Z_]+$/ ){
+                $f = "_$f";
+            } else {
+      	        $f = lcfirst($f);
+            }
+    	    $f =~ s/^(type|and|or|new)$/$1_/;
+            if( $internal ){ $f = "_internal_$f"; }
+            $f =~ s/_wrap$//; # [wrap] cleanup
+
+	    # pyAbcObject => pyAbc (but keep pyObject )
+            $rem =~ s/py([A-z]+)Object/py$1/g;
+
+            # rem includes type 
+            $rem =~ s/py([A-z]+)_p_option/py$1 option/g;
+            $rem =~ s/py([A-z]+)_p_noincr/py$1/g;
+            $rem =~ s/py([A-z]+)_p_incr/py$1/g;
+            $rem =~ s/py([A-z]+)_p/py$1/g;
+    
+	    # introduce polymorphism (pretty dirty)
+	    # pyAbcd ... -> ==> [>_Abcd] t ... ->
+	    while( $rem =~ s/py([A-Z][A-z]+)(.*->)/[>_$1] t$2/g ){
+	    }
+	    # return types have no polymorphism
+	    $rem =~ s/py([A-Z][A-z]+)/_$1 t/g;
+
+    	    if ( $k eq "" ){ $k = "Base"; }
+            if( $comment ne "" ){
+    	        $mod{$k} = "$mod{$k}  external $f $rem$def  (** $comment **)\n\n";
+            } else {
+    	        $mod{$k} = "$mod{$k}  external $f $rem$def\n";
+            }
+        } 
+    }
+
+    print "open Apitype\n\n";
+    for $k (keys %mod){
+        print "module $k = struct\n";
+        print $mod{$k};
+	if( $mod{$k} =~ /external check +: \[>_Object\] t -> bool/ ){
+	    print 
+"  (** coercion to [_$k t]. Raises Coercion when impossible *)
+  let coerce : [>_Object] t -> _$k t = fun t ->
+    if check t then unsafe_coerce t else raise Coercion
+  ;;
+
+  (** coercion to [_$k t]. Return None when impossible *)
+  let coerce_opt : [>_Object] t -> _$k t option = fun t ->
+    if check t then Some (unsafe_coerce t) else None
+  ;;
+";
+	}
+        print "end\n\n";
+    }
+}
+

File number.idl.in

 boolean PyNumber_Check(PyObject  *o);
 // Returns 1 if the object o provides numeric protocols, and false otherwise. This function always succeeds.
 
-[new] PyObject* PyNumber_Add(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_Add(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the result of adding o1 and o2, or NULL on failure. This is the equivalent of the Python expression o1 + o2.
 
-[new] PyObject* PyNumber_Subtract(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_Subtract(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the result of subtracting o2 from o1, or NULL on failure. This is the equivalent of the Python expression o1 - o2.
 
-[new] PyObject* PyNumber_Multiply(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_Multiply(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the result of multiplying o1 and o2, or NULL on failure. This is the equivalent of the Python expression o1 * o2.
 
-[new] PyObject* PyNumber_Divide(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_Divide(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the result of dividing o1 by o2, or NULL on failure. This is the equivalent of the Python expression o1 / o2.
 
-[new] PyObject* PyNumber_FloorDivide(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_FloorDivide(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Return the floor of o1 divided by o2, or NULL on failure. This is equivalent to the “classic” division of integers.
 
-[new] PyObject* PyNumber_TrueDivide(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_TrueDivide(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Return a reasonable approximation for the mathematical value of o1 divided by o2, or NULL on failure. The return value is “approximate” because binary floating point numbers are approximate; it is not possible to represent all real numbers in base two. This function can return a floating point value when passed two integers.
 
-[new] PyObject* PyNumber_Remainder(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_Remainder(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the remainder of dividing o1 by o2, or NULL on failure. This is the equivalent of the Python expression o1 % o2.
 
-[new] PyObject* PyNumber_Divmod(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_Divmod(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // See the built-in function divmod(). Returns NULL on failure. This is the equivalent of the Python expression divmod(o1, o2).
 
-[new] PyObject* PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3);
+[new] PyNumberObject* PyNumber_Power(PyNumberObject *o1, PyNumberObject *o2, PyNumberObject *o3);
 // Return value: New reference.
 // See the built-in function pow(). Returns NULL on failure. This is the equivalent of the Python expression pow(o1, o2, o3), where o3 is optional. If o3 is to be ignored, pass Py_None in its place (passing NULL for o3 would cause an illegal memory access).
 
-[new] PyObject* PyNumber_Negative(PyObject *o);
+[new] PyNumberObject* PyNumber_Negative(PyNumberObject *o);
 // Return value: New reference.
 // Returns the negation of o on success, or NULL on failure. This is the equivalent of the Python expression -o.
 
-[new] PyObject* PyNumber_Positive(PyObject *o);
+[new] PyNumberObject* PyNumber_Positive(PyNumberObject *o);
 // Return value: New reference.
 // Returns o on success, or NULL on failure. This is the equivalent of the Python expression +o.
 
-[new] PyObject* PyNumber_Absolute(PyObject *o);
+[new] PyNumberObject* PyNumber_Absolute(PyNumberObject *o);
 // Return value: New reference.
 // Returns the absolute value of o, or NULL on failure. This is the equivalent of the Python expression abs(o).
 
-[new] PyObject* PyNumber_Invert(PyObject *o);
+[new] PyNumberObject* PyNumber_Invert(PyNumberObject *o);
 // Return value: New reference.
 // Returns the bitwise negation of o on success, or NULL on failure. This is the equivalent of the Python expression ~o.
 
-[new] PyObject* PyNumber_Lshift(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_Lshift(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the result of left shifting o1 by o2 on success, or NULL on failure. This is the equivalent of the Python expression o1 << o2.
 
-[new] PyObject* PyNumber_Rshift(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_Rshift(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the result of right shifting o1 by o2 on success, or NULL on failure. This is the equivalent of the Python expression o1 >> o2.
 
-[new] PyObject* PyNumber_And(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_And(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the “bitwise and” of o1 and o2 on success and NULL on failure. This is the equivalent of the Python expression o1 & o2.
 
-[new] PyObject* PyNumber_Xor(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_Xor(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the “bitwise exclusive or” of o1 by o2 on success, or NULL on failure. This is the equivalent of the Python expression o1 ^ o2.
 
-[new] PyObject* PyNumber_Or(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_Or(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the “bitwise or” of o1 and o2 on success, or NULL on failure. This is the equivalent of the Python expression o1 | o2.
 
-[new] PyObject* PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_InPlaceAdd(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the result of adding o1 and o2, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 += o2.
 
-[new] PyObject* PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_InPlaceSubtract(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the result of subtracting o2 from o1, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 -= o2.
 
-[new] PyObject* PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_InPlaceMultiply(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the result of multiplying o1 and o2, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 *= o2.
 
-[new] PyObject* PyNumber_InPlaceDivide(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_InPlaceDivide(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the result of dividing o1 by o2, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 /= o2.
 
-[new] PyObject* PyNumber_InPlaceFloorDivide(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_InPlaceFloorDivide(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the mathematical floor of dividing o1 by o2, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 //= o2.
 
-[new] PyObject* PyNumber_InPlaceTrueDivide(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_InPlaceTrueDivide(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Return a reasonable approximation for the mathematical value of o1 divided by o2, or NULL on failure. The return value is “approximate” because binary floating point numbers are approximate; it is not possible to represent all real numbers in base two. This function can return a floating point value when passed two integers. The operation is done in-place when o1 supports it.
 
-[new] PyObject* PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_InPlaceRemainder(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the remainder of dividing o1 by o2, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 %= o2.
 
-[new] PyObject* PyNumber_InPlacePower(PyObject *o1, PyObject *o2, PyObject *o3);
+[new] PyNumberObject* PyNumber_InPlacePower(PyNumberObject *o1, PyNumberObject *o2, PyNumberObject *o3);
 // Return value: New reference.
 // See the built-in function pow(). Returns NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 **= o2 when o3 is Py_None, or an in-place variant of pow(o1, o2, o3) otherwise. If o3 is to be ignored, pass Py_None in its place (passing NULL for o3 would cause an illegal memory access).
 
-[new] PyObject* PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_InPlaceLshift(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the result of left shifting o1 by o2 on success, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 <<= o2.
 
-[new] PyObject* PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_InPlaceRshift(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the result of right shifting o1 by o2 on success, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 >>= o2.
 
-[new] PyObject* PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_InPlaceAnd(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the “bitwise and” of o1 and o2 on success and NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 &= o2.
 
-[new] PyObject* PyNumber_InPlaceXor(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_InPlaceXor(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the “bitwise exclusive or” of o1 by o2 on success, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 ^= o2.
 
-[new] PyObject* PyNumber_InPlaceOr(PyObject *o1, PyObject *o2);
+[new] PyNumberObject* PyNumber_InPlaceOr(PyNumberObject *o1, PyNumberObject *o2);
 // Return value: New reference.
 // Returns the “bitwise or” of o1 and o2 on success, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 |= o2.
 
 // int PyNumber_CoerceEx(PyObject **p1, PyObject **p2);
 // This function is similar to PyNumber_Coerce(), except that it returns 1 when the conversion is not possible and when no error is raised. Reference counts are still not increased in this case.
 
-[new] PyObject* PyNumber_Int(PyObject *o);
+[new] PyIntObject* PyNumber_Int(PyNumberObject *o);
 // Return value: New reference.
 // Returns the o converted to an integer object on success, or NULL on failure. If the argument is outside the integer range a long object will be returned instead. This is the equivalent of the Python expression int(o).
 
-[new] PyObject* PyNumber_Long(PyObject *o);
+[new] PyLongObject* PyNumber_Long(PyNumberObject *o);
 // Return value: New reference.
 // Returns the o converted to a long integer object on success, or NULL on failure. This is the equivalent of the Python expression long(o).
 
-[new] PyObject* PyNumber_Float(PyObject *o);
+[new] PyFloatObject* PyNumber_Float(PyNumberObject *o);
 // Return value: New reference.
 // Returns the o converted to a float object on success, or NULL on failure. This is the equivalent of the Python expression float(o).
 
-PyObject* PyNumber_Index(PyObject *o);
+[new] PyIntegralObject* PyNumber_Index(PyNumberObject *o); /* [new] ?? not sure */ 
 // Returns the o converted to a Python int or long on success or NULL with a TypeError exception raised on failure.
 
-PyObject* PyNumber_ToBase(PyObject *n, int base);
+PyIntObject* PyNumber_ToBase(PyNumberObject *n, int base);
 // Returns the integer n converted to base as a string with a base marker of '0b', '0o', or '0x' if applicable. When base is not 2, 8, 10, or 16, the format is 'x#num' where x is the base. If n is not an int object, it is converted with PyNumber_Index() first.
 
-size_or_fail PyNumber_AsSsize_t(PyObject *o, PyObject *exc);
+size_or_fail PyNumber_AsSsize_t(PyNumberObject *o, PyObject *exc);
 // Returns o converted to a Py_ssize_t value if o can be interpreted as an integer. If o can be converted to a Python int or long but the attempt to convert to a Py_ssize_t value would raise an OverflowError, then the exc argument is the type of exception that will be raised (usually IndexError or OverflowError). If exc is NULL, then the exception is cleared and the value is clipped to PY_SSIZE_T_MIN for a negative integer or PY_SSIZE_T_MAX for a positive integer.
 
 boolean PyIndex_Check(PyObject *o); // or bool_or_fail ?
 // Returns True if o is an index integer (has the nb_index slot of the tp_as_number structure filled in).
-

File object.idl.in

 // int PyObject_Print(PyObject *o, FILE *fp, int flags)
 // Print an object o, on file fp. Returns -1 on error. The flags argument is used to enable certain printing options. The only option currently supported is Py_PRINT_RAW; if given, the str() of the object is written instead of the repr().
 
-boolean PyObject_HasAttr(PyObject *o, PyObject *attr_name);
+boolean PyObject_HasAttr(PyObject *o, PyStringObject *attr_name);
 // Returns 1 if o has the attribute attr_name, and 0 otherwise. This is equivalent to the Python expression hasattr(o, attr_name). This function always succeeds.
 
 boolean PyObject_HasAttrString(PyObject *o, [string] const char *attr_name);
 // Returns 1 if o has the attribute attr_name, and 0 otherwise. This is equivalent to the Python expression hasattr(o, attr_name). This function always succeeds.
 
-[new] PyObject* PyObject_GetAttr(PyObject *o, PyObject *attr_name);
+[new] PyObject* PyObject_GetAttr(PyObject *o, PyStringObject *attr_name);
 // Return value: New reference.
 // Retrieve an attribute named attr_name from object o. Returns the attribute value on success, or NULL on failure. This is the equivalent of the Python expression o.attr_name.
 
 // Return value: New reference.
 // Retrieve an attribute named attr_name from object o. Returns the attribute value on success, or NULL on failure. This is the equivalent of the Python expression o.attr_name.
 
-PyObject* PyObject_GenericGetAttr(PyObject *o, PyObject *name); // Guess it is borrowed, since there is a case when this function returns the result of PyDict_GetItem.
+PyObject* PyObject_GenericGetAttr(PyObject *o, PyStringObject *name); // Guess it is borrowed, since there is a case when this function returns the result of PyDict_GetItem.
 // Generic attribute getter function that is meant to be put into a type object’s tp_getattro slot. It looks for a descriptor in the dictionary of classes in the object’s MRO as well as an attribute in the object’s __dict__ (if present). As outlined in Implementing Descriptors, data descriptors take preference over instance attributes, while non-data descriptors don’t. Otherwise, an AttributeError is raised.
 
-unit_or_fail PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v);
+unit_or_fail PyObject_SetAttr(PyObject *o, PyStringObject *attr_name, PyObject *v);
 // Set the value of the attribute named attr_name, for object o, to the value v. Returns -1 on failure. This is the equivalent of the Python statement o.attr_name = v.
 
 unit_or_fail PyObject_SetAttrString(PyObject *o, [string] const char *attr_name, PyObject *v);
 // Set the value of the attribute named attr_name, for object o, to the value v. Returns -1 on failure. This is the equivalent of the Python statement o.attr_name = v.
 
-unit_or_fail PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value);
+unit_or_fail PyObject_GenericSetAttr(PyObject *o, PyStringObject *name, PyObject *value);
 // Generic attribute setter function that is meant to be put into a type object’s tp_setattro slot. It looks for a data descriptor in the dictionary of classes in the object’s MRO, and if found it takes preference over setting the attribute in the instance dictionary. Otherwise, the attribute is set in the object’s __dict__ (if present). Otherwise, an AttributeError is raised and -1 is returned.
 
-unit_or_fail PyObject_DelAttr(PyObject *o, PyObject *attr_name);
+unit_or_fail PyObject_DelAttr(PyObject *o, PyStringObject *attr_name);
 // Delete attribute named attr_name, for object o. Returns -1 on failure. This is the equivalent of the Python statement del o.attr_name.
 
 unit_or_fail PyObject_DelAttrString(PyObject *o, [string] const char *attr_name);
 // int PyObject_Compare(PyObject *o1, PyObject *o2);
 // Compare the values of o1 and o2 using a routine provided by o1, if one exists, otherwise with a routine provided by o2. Returns the result of the comparison on success. On error, the value returned is undefined; use PyErr_Occurred() to detect an error. This is equivalent to the Python expression cmp(o1, o2).
 
-[new] PyObject* PyObject_Repr(PyObject *o);
+[new] PyStringObject* PyObject_Repr(PyObject *o);
 // Return value: New reference.
 // Compute a string representation of object o. Returns the string representation on success, NULL on failure. This is the equivalent of the Python expression repr(o). Called by the repr() built-in function and by reverse quotes.
 
-[new] PyObject* PyObject_Str(PyObject *o);
+[new] PyStringObject* PyObject_Str(PyObject *o);
 // Return value: New reference.
-// aCompute a string representation of object o. Returns the string representation on success, NULL on failure. This is the equivalent of the Python expression str(o). Called by the str() built-in function and by the print statement.
+// Compute a string representation of object o. Returns the string representation on success, NULL on failure. This is the equivalent of the Python expression str(o). Called by the str() built-in function and by the print statement.
 
-[new] PyObject* PyObject_Bytes(PyObject *o);
+[new] PyByteArrayObject* /* ??? */ PyObject_Bytes(PyObject *o);
 // Compute a bytes representation of object o. In 2.x, this is just a alias for PyObject_Str().
 
-[new] PyObject* PyObject_Unicode(PyObject *o);
+[new] PyUnicodeObject* PyObject_Unicode(PyObject *o);
 // Return value: New reference.
 // Compute a Unicode string representation of object o. Returns the Unicode string representation on success, NULL on failure. This is the equivalent of the Python expression unicode(o). Called by the unicode() built-in function.
 
-bool_or_fail PyObject_IsInstance(PyObject *inst, PyObject *cls);
+bool_or_fail PyObject_IsInstance(PyObject *inst, PyClassObject *cls);
 // Returns 1 if inst is an instance of the class cls or a subclass of cls, or 0 if not. On error, returns -1 and sets an exception. If cls is a type object rather than a class object, PyObject_IsInstance() returns 1 if inst is of type cls. If cls is a tuple, the check will be done against every entry in cls. The result will be 1 when at least one of the checks returns 1, otherwise it will be 0. If inst is not a class instance and cls is neither a type object, nor a class object, nor a tuple, inst must have a __class__ attribute  the class relationship of the value of that attribute with cls will be used to determine the result of this function.
 
 // Subclass determination is done in a fairly straightforward way, but includes a wrinkle that implementors of extensions to the class system may want to be aware of. If A and B are class objects, B is a subclass of A if it inherits from A either directly or indirectly. If either is not a class object, a more general mechanism is used to determine the class relationship of the two objects. When testing if B is a subclass of A, if A is B, PyObject_IsSubclass() returns true. If A and B are different objects, B‘s __bases__ attribute is searched in a depth-first fashion for A  the presence of the __bases__ attribute is considered sufficient for this determination.
 
-bool_or_fail PyObject_IsSubclass(PyObject *derived, PyObject *cls);
+bool_or_fail PyObject_IsSubclass(PyClassObject *derived, PyClassObject *cls);
 // Returns 1 if the class derived is identical to or derived from the class cls, otherwise returns 0. In case of an error, returns -1. If cls is a tuple, the check will be done against every entry in cls. The result will be 1 when at least one of the checks returns 1, otherwise it will be 0. If either derived or cls is not an actual class object (or tuple), this function uses the generic algorithm described above.
 
 boolean PyCallable_Check(PyObject *o);
 // Determine if the object o is callable. Return 1 if the object is callable and 0 otherwise. This function always succeeds.
 
 // Need to think about NULL
-[new] PyObject* PyObject_Call(PyObject *callable_object, PyObject *args, [option] PyObject *kw);
+[new] PyObject* PyObject_Call(PyCallableObject *callable_object, PyTupleObject *args, [option] PyDictObject *kw);
 // Return value: New reference.
 // Call a callable Python object callable_object, with arguments given by the tuple args, and named arguments given by the dictionary kw. If no named arguments are needed, kw may be NULL. args must not be NULL, use an empty tuple if no arguments are needed. Returns the result of the call on success, or NULL on failure. This is the equivalent of the Python expression apply(callable_object, args, kw) or callable_object(*args, **kw).
 
-[new] PyObject* PyObject_CallObject(PyObject *callable_object, [option] PyObject *args);
+[new] PyObject* PyObject_CallObject(PyCallableObject *callable_object, [option] PyTupleObject *args);
 // Return value: New reference.
 // Call a callable Python object callable_object, with arguments given by the tuple args. If no arguments are needed, then args may be NULL. Returns the result of the call on success, or NULL on failure. This is the equivalent of the Python expression apply(callable_object, args) or callable_object(*args).
 
-[new] PyObject* PyEval_CallObject(PyObject *callable_object, [option] PyObject *args);
+[new] PyObject* PyEval_CallObject(PyCallableObject *callable_object, [option] PyTupleObject *args);
 // Return value: New reference.
 // Call a callable Python object callable_object, with arguments given by the tuple args. If no arguments are needed, then args may be NULL. Returns the result of the call on success, or NULL on failure. This is the equivalent of the Python expression apply(callable_object, args) or callable_object(*args).
 // Same as PyObject_CallObject but with sanity checks
 // Return value: New reference.
 // This is equivalent to the Python expression dir(o), returning a (possibly empty) list of strings appropriate for the object argument, or NULL if there was an error. If the argument is NULL, this is like the Python dir(), returning the names of the current locals; in this case, if no execution frame is active then NULL is returned but PyErr_Occurred() will return false.
 
-[new] PyObject* PyObject_GetIter(PyObject *o);
+[new] PyIterObject* PyObject_GetIter(PyObject *o);
 // Return value: New reference.
 // This is equivalent to the Python expression iter(o). It returns a new iterator for the object argument, or the object itself if the object is already an iterator. Raises TypeError and returns NULL if the object cannot be iterated.
 

File sequence.idl.in

 boolean PySequence_Check(PyObject  *o);
 // Return 1 if the object provides sequence protocol, and 0 otherwise. This function always succeeds.
 
-size_or_fail PySequence_Size(PyObject *o);
-size_or_fail PySequence_Length(PyObject *o);
+size_or_fail PySequence_Size(PySequenceObject *o);
+size_or_fail PySequence_Length(PySequenceObject *o);
 // Returns the number of objects in sequence o on success, and -1 on failure. For objects that do not provide sequence protocol, this is equivalent to the Python expression len(o).
 
-[new] PyObject* PySequence_Concat(PyObject *o1, PyObject *o2);
+[new] PySequenceObject* PySequence_Concat(PySequenceObject *o1, PySequenceObject *o2);
 // Return value: New reference.
 // Return the concatenation of o1 and o2 on success, and NULL on failure. This is the equivalent of the Python expression o1 + o2.
 
-[new] PyObject* PySequence_Repeat(PyObject *o, Py_ssize_t count);
+[new] PySequenceObject* PySequence_Repeat(PySequenceObject *o, Py_ssize_t count);
 // Return value: New reference.
 // Return the result of repeating sequence object o count times, or NULL on failure. This is the equivalent of the Python expression o * count.
 
-[new] PyObject* PySequence_InPlaceConcat(PyObject *o1, PyObject *o2);
+[new] PySequenceObject* PySequence_InPlaceConcat(PySequenceObject *o1, PySequenceObject *o2);
 // Return value: New reference.
 // Return the concatenation of o1 and o2 on success, and NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python expression o1 += o2.
 
-[new] PyObject* PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count);
+[new] PySequenceObject* PySequence_InPlaceRepeat(PySequenceObject *o, Py_ssize_t count);
 // Return value: New reference.
 // Return the result of repeating sequence object o count times, or NULL on failure. The operation is done in-place when o supports it. This is the equivalent of the Python expression o *= count.
 
-[new] PyObject* PySequence_GetItem(PyObject *o, Py_ssize_t i);
+[new] PyObject* PySequence_GetItem(PySequenceObject *o, Py_ssize_t i);
 // Return value: New reference.
 // Return the ith element of o, or NULL on failure. This is the equivalent of the Python expression o[i].
 
-[new] PyObject* PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2);
+[new] PySliceObject* PySequence_GetSlice(PySequenceObject *o, Py_ssize_t i1, Py_ssize_t i2);
 // Return value: New reference.
 // Return the slice of sequence object o between i1 and i2, or NULL on failure. This is the equivalent of the Python expression o[i1:i2].
 
-unit_or_fail PySequence_SetItem(PyObject *o, Py_ssize_t i, [stolen] PyObject *v);
+unit_or_fail PySequence_SetItem(PySequenceObject *o, Py_ssize_t i, [stolen] PyObject *v);
 // Assign object v to the ith element of o. Returns -1 on failure. This is the equivalent of the Python statement o[i] = v. This function does not steal a reference to v.
 
-unit_or_fail PySequence_DelItem(PyObject *o, Py_ssize_t i);
+unit_or_fail PySequence_DelItem(PySequenceObject *o, Py_ssize_t i);
 // Delete the ith element of object o. Returns -1 on failure. This is the equivalent of the Python statement del o[i].
 
-unit_or_fail PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2, PyObject *v);
+unit_or_fail PySequence_SetSlice(PySequenceObject *o, Py_ssize_t i1, Py_ssize_t i2, PySequenceObject *v);
 // Assign the sequence object v to the slice in sequence object o from i1 to i2. This is the equivalent of the Python statement o[i1:i2] = v.
 
-unit_or_fail PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2);
+unit_or_fail PySequence_DelSlice(PySequenceObject *o, Py_ssize_t i1, Py_ssize_t i2);
 // Delete the slice in sequence object o from i1 to i2. Returns -1 on failure. This is the equivalent of the Python statement del o[i1:i2].
 
-size_or_fail PySequence_Count(PyObject *o, PyObject *value_);
+size_or_fail PySequence_Count(PySequenceObject *o, PyObject *value_);
 // Return the number of occurrences of value in o, that is, return the number of keys for which o[key] == value. On failure, return -1. This is equivalent to the Python expression o.count(value).
 
-bool_or_fail PySequence_Contains(PyObject *o, PyObject *value_);
+bool_or_fail PySequence_Contains(PySequenceObject *o, PyObject *value_);
 // Determine if o contains value. If an item in o is equal to value, return 1, otherwise return 0. On error, return -1. This is equivalent to the Python expression value in o.
 
-size_or_fail PySequence_Index(PyObject *o, PyObject *value_);
+size_or_fail PySequence_Index(PySequenceObject *o, PyObject *value_);
 // Return the first index i for which o[i] == value. On error, return -1. This is equivalent to the Python expression o.index(value).
 
-[new] PyObject* PySequence_List(PyObject *o);
+[new] PyListObject* PySequence_List(PySequenceObject *o);
 // Return value: New reference.
 // Return a list object with the same contents as the arbitrary sequence o. The returned list is guaranteed to be new.
 
-[new] PyObject* PySequence_Tuple(PyObject *o);
+[new] PyTupleObject* PySequence_Tuple(PySequenceObject *o);
 // Return value: New reference.
 // Return a tuple object with the same contents as the arbitrary sequence o or NULL on failure. If o is a tuple, a new reference will be returned, otherwise a tuple will be constructed with the appropriate contents. This is equivalent to the Python expression tuple(o).
 
-[new] PyObject* PySequence_Fast(PyObject *o, [string] const char *m);
+[new] PyTupleObject* PySequence_Fast(PySequenceObject *o, [string] const char *m);
 // Return value: New reference.
 // Returns the sequence o as a tuple, unless it is already a tuple or list, in which case o is returned. Use PySequence_Fast_GET_ITEM() to access the members of the result. Returns NULL on failure. If the object is not a sequence, raises TypeError with m as the message text.
 
-PyObject* PySequence_Fast_GET_ITEM(PyObject *o, Py_ssize_t i);
+PyObject* PySequence_Fast_GET_ITEM(PySequenceObject *o, Py_ssize_t i);
 // Return value: Borrowed reference.
 // Return the ith element of o, assuming that o was returned by PySequence_Fast(), o is not NULL, and that i is within bounds.
 
-// PyObject** PySequence_Fast_ITEMS(PyObject *o);
+// PyObject** PySequence_Fast_ITEMS(PySequenceObject *o);
 // Return the underlying array of PyObject pointers. Assumes that o was returned by PySequence_Fast() and o is not NULL.
 // Note, if a list gets resized, the reallocation may relocate the items array. So, only use the underlying array pointer in contexts where the sequence cannot change.
 
-[new] PyObject* PySequence_ITEM(PyObject *o, Py_ssize_t i);
+[new] PyObject* PySequence_ITEM(PySequenceObject *o, Py_ssize_t i);
 // Return value: New reference.
 //Return the ith element of o or NULL on failure. Macro form of PySequence_GetItem() but without checking that PySequence_Check(o)() is true and without adjustment for negative indices.
 
-size_or_fail PySequence_Fast_GET_SIZE(PyObject *o);
+size_or_fail PySequence_Fast_GET_SIZE(PySequenceObject *o);
 // Returns the length of o, assuming that o was returned by PySequence_Fast() and that o is not NULL. The size can also be gotten by calling PySequence_Size() on o, but PySequence_Fast_GET_SIZE() is faster because it can assume o is a list or tuple.
 

File standard_class_hier.txt

+None
+This type has a single value. There is a single object with this value. This object is accessed through the built-in name None. It is used to signify the absence of a value in many situations, e.g., it is returned from functions that don’t explicitly return anything. Its truth value is false.
+
+NotImplemented
+This type has a single value. There is a single object with this value. This object is accessed through the built-in name NotImplemented. Numeric methods and rich comparison methods may return this value if they do not implement the operation for the operands provided. (The interpreter will then try the reflected operation, or some other fallback, depending on the operator.) Its truth value is true.
+
+Ellipsis
+This type has a single value. There is a single object with this value. This object is accessed through the built-in name Ellipsis. It is used to indicate the presence of the ... syntax in a slice. Its truth value is true.
+
+numbers.Number
+These are created by numeric literals and returned as results by arithmetic operators and arithmetic built-in functions. Numeric objects are immutable; once created their value never changes. Python numbers are of course strongly related to mathematical numbers, but subject to the limitations of numerical representation in computers.
+
+Python distinguishes between integers, floating point numbers, and complex numbers:
+
+numbers.Integral
+These represent elements from the mathematical set of integers (positive and negative).
+
+There are three types of integers:
+
+Plain integers
+These represent numbers in the range -2147483648 through 2147483647. (The range may be larger on machines with a larger natural word size, but not smaller.) When the result of an operation would fall outside this range, the result is normally returned as a long integer (in some cases, the exception OverflowError is raised instead). For the purpose of shift and mask operations, integers are assumed to have a binary, 2’s complement notation using 32 or more bits, and hiding no bits from the user (i.e., all 4294967296 different bit patterns correspond to different values).
+
+Long integers
+These represent numbers in an unlimited range, subject to available (virtual) memory only. For the purpose of shift and mask operations, a binary representation is assumed, and negative numbers are represented in a variant of 2’s complement which gives the illusion of an infinite string of sign bits extending to the left.
+
+Booleans
+These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of plain integers, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.
+
+The rules for integer representation are intended to give the most meaningful interpretation of shift and mask operations involving negative integers and the least surprises when switching between the plain and long integer domains. Any operation, if it yields a result in the plain integer domain, will yield the same result in the long integer domain or when using mixed operands. The switch between domains is transparent to the programmer.
+
+numbers.Real (float)
+These represent machine-level double precision floating point numbers. You are at the mercy of the underlying machine architecture (and C or Java implementation) for the accepted range and handling of overflow. Python does not support single-precision floating point numbers; the savings in processor and memory usage that are usually the reason for using these is dwarfed by the overhead of using objects in Python, so there is no reason to complicate the language with two kinds of floating point numbers.
+
+numbers.Complex
+These represent complex numbers as a pair of machine-level double precision floating point numbers. The same caveats apply as for floating point numbers. The real and imaginary parts of a complex number z can be retrieved through the read-only attributes z.real and z.imag.
+
+Sequences
+These represent finite ordered sets indexed by non-negative numbers. The built-in function len() returns the number of items of a sequence. When the length of a sequence is n, the index set contains the numbers 0, 1, ..., n-1. Item i of sequence a is selected by a[i].
+
+Sequences also support slicing: a[i:j] selects all items with index k such that i <= k < j. When used as an expression, a slice is a sequence of the same type. This implies that the index set is renumbered so that it starts at 0.
+
+Some sequences also support “extended slicing” with a third “step” parameter: a[i:j:k] selects all items of a with index x where x = i + n*k, n >= 0 and i <= x < j.
+
+Sequences are distinguished according to their mutability:
+
+Immutable sequences
+An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be changed; however, the collection of objects directly referenced by an immutable object cannot change.)
+
+The following types are immutable sequences:
+
+Strings
+The items of a string are characters. There is no separate character type; a character is represented by a string of one item. Characters represent (at least) 8-bit bytes. The built-in functions chr() and ord() convert between characters and nonnegative integers representing the byte values. Bytes with the values 0-127 usually represent the corresponding ASCII values, but the interpretation of values is up to the program. The string data type is also used to represent arrays of bytes, e.g., to hold data read from a file.
+
+(On systems whose native character set is not ASCII, strings may use EBCDIC in their internal representation, provided the functions chr() and ord() implement a mapping between ASCII and EBCDIC, and string comparison preserves the ASCII order. Or perhaps someone can propose a better rule?)
+
+Unicode
+The items of a Unicode object are Unicode code units. A Unicode code unit is represented by a Unicode object of one item and can hold either a 16-bit or 32-bit value representing a Unicode ordinal (the maximum value for the ordinal is given in sys.maxunicode, and depends on how Python is configured at compile time). Surrogate pairs may be present in the Unicode object, and will be reported as two separate items. The built-in functions unichr() and ord() convert between code units and nonnegative integers representing the Unicode ordinals as defined in the Unicode Standard 3.0. Conversion from and to other encodings are possible through the Unicode method encode() and the built-in function unicode().
+
+Tuples
+The items of a tuple are arbitrary Python objects. Tuples of two or more items are formed by comma-separated lists of expressions. A tuple of one item (a ‘singleton’) can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions). An empty tuple can be formed by an empty pair of parentheses.
+
+Mutable sequences
+Mutable sequences can be changed after they are created. The subscription and slicing notations can be used as the target of assignment and del (delete) statements.
+
+There are currently two intrinsic mutable sequence types:
+
+Lists
+The items of a list are arbitrary Python objects. Lists are formed by placing a comma-separated list of expressions in square brackets. (Note that there are no special cases needed to form lists of length 0 or 1.)
+
+Byte Arrays
+A bytearray object is a mutable array. They are created by the built-in bytearray() constructor. Aside from being mutable (and hence unhashable), byte arrays otherwise provide the same interface and functionality as immutable bytes objects.
+
+The extension module array provides an additional example of a mutable sequence type.
+
+Set types
+These represent unordered, finite sets of unique, immutable objects. As such, they cannot be indexed by any subscript. However, they can be iterated over, and the built-in function len() returns the number of items in a set. Common uses for sets are fast membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.
+
+For set elements, the same immutability rules apply as for dictionary keys. Note that numeric types obey the normal rules for numeric comparison: if two numbers compare equal (e.g., 1 and 1.0), only one of them can be contained in a set.
+
+There are currently two intrinsic set types:
+
+Sets
+These represent a mutable set. They are created by the built-in set() constructor and can be modified afterwards by several methods, such as add().
+
+Frozen sets
+These represent an immutable set. They are created by the built-in frozenset() constructor. As a frozenset is immutable and hashable, it can be used again as an element of another set, or as a dictionary key.
+
+Mappings
+These represent finite sets of objects indexed by arbitrary index sets. The subscript notation a[k] selects the item indexed by k from the mapping a; this can be used in expressions and as the target of assignments or del statements. The built-in function len() returns the number of items in a mapping.
+
+There is currently a single intrinsic mapping type:
+
+Dictionaries
+These represent finite sets of objects indexed by nearly arbitrary values. The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (e.g., 1 and 1.0) then they can be used interchangeably to index the same dictionary entry.
+
+Dictionaries are mutable; they can be created by the {...} notation (see section Dictionary displays).
+
+The extension modules dbm, gdbm, and bsddb provide additional examples of mapping types.
+
+Callable types
+These are the types to which the function call operation (see section Calls) can be applied:
+
+User-defined functions
+A user-defined function object is created by a function definition (see section Function definitions). It should be called with an argument list containing the same number of items as the function’s formal parameter list.
+
+Special attributes:
+
+Attribute	Meaning	 
+func_doc	The function’s documentation string, or None if unavailable	Writable
+__doc__	Another way of spelling func_doc	Writable
+func_name	The function’s name	Writable
+__name__	Another way of spelling func_name	Writable
+__module__	The name of the module the function was defined in, or None if unavailable.	Writable
+func_defaults	A tuple containing default argument values for those arguments that have defaults, or None if no arguments have a default value	Writable
+func_code	The code object representing the compiled function body.	Writable
+func_globals	A reference to the dictionary that holds the function’s global variables  the global namespace of the module in which the function was defined.	Read-only
+func_dict	The namespace supporting arbitrary function attributes.	Writable
+func_closure	None or a tuple of cells that contain bindings for the function’s free variables.	Read-only
+Most of the attributes labelled “Writable” check the type of the assigned value.
+
+Changed in version 2.4: func_name is now writable.
+
+Function objects also support getting and setting arbitrary attributes, which can be used, for example, to attach metadata to functions. Regular attribute dot-notation is used to get and set such attributes. Note that the current implementation only supports function attributes on user-defined functions. Function attributes on built-in functions may be supported in the future.
+
+Additional information about a function’s definition can be retrieved from its code object; see the description of internal types below.
+
+User-defined methods
+A user-defined method object combines a class, a class instance (or None) and any callable object (normally a user-defined function).
+
+Special read-only attributes: im_self is the class instance object, im_func is the function object; im_class is the class of im_self for bound methods or the class that asked for the method for unbound methods; __doc__ is the method’s documentation (same as im_func.__doc__); __name__ is the method name (same as im_func.__name__); __module__ is the name of the module the method was defined in, or None if unavailable.
+
+Changed in version 2.2: im_self used to refer to the class that defined the method.
+
+Changed in version 2.6: For 3.0 forward-compatibility, im_func is also available as __func__, and im_self as __self__.
+
+Methods also support accessing (but not setting) the arbitrary function attributes on the underlying function object.
+
+User-defined method objects may be created when getting an attribute of a class (perhaps via an instance of that class), if that attribute is a user-defined function object, an unbound user-defined method object, or a class method object. When the attribute is a user-defined method object, a new method object is only created if the class from which it is being retrieved is the same as, or a derived class of, the class stored in the original method object; otherwise, the original method object is used as it is.
+
+When a user-defined method object is created by retrieving a user-defined function object from a class, its im_self attribute is None and the method object is said to be unbound. When one is created by retrieving a user-defined function object from a class via one of its instances, its im_self attribute is the instance, and the method object is said to be bound. In either case, the new method’s im_class attribute is the class from which the retrieval takes place, and its im_func attribute is the original function object.
+
+When a user-defined method object is created by retrieving another method object from a class or instance, the behaviour is the same as for a function object, except that the im_func attribute of the new instance is not the original method object but its im_func attribute.
+
+When a user-defined method object is created by retrieving a class method object from a class or instance, its im_self attribute is the class itself (the same as the im_class attribute), and its im_func attribute is the function object underlying the class method.
+
+When an unbound user-defined method object is called, the underlying function (im_func) is called, with the restriction that the first argument must be an instance of the proper class (im_class) or of a derived class thereof.
+
+When a bound user-defined method object is called, the underlying function (im_func) is called, inserting the class instance (im_self) in front of the argument list. For instance, when C is a class which contains a definition for a function f(), and x is an instance of C, calling x.f(1) is equivalent to calling C.f(x, 1).
+
+When a user-defined method object is derived from a class method object, the “class instance” stored in im_self will actually be the class itself, so that calling either x.f(1) or C.f(1) is equivalent to calling f(C,1) where f is the underlying function.
+
+Note that the transformation from function object to (unbound or bound) method object happens each time the attribute is retrieved from the class or instance. In some cases, a fruitful optimization is to assign the attribute to a local variable and call that local variable. Also notice that this transformation only happens for user-defined functions; other callable objects (and all non-callable objects) are retrieved without transformation. It is also important to note that user-defined functions which are attributes of a class instance are not converted to bound methods; this only happens when the function is an attribute of the class.
+
+Generator functions
+A function or method which uses the yield statement (see section The yield statement) is called a generator function. Such a function, when called, always returns an iterator object which can be used to execute the body of the function: calling the iterator’s next() method will cause the function to execute until it provides a value using the yield statement. When the function executes a return statement or falls off the end, a StopIteration exception is raised and the iterator will have reached the end of the set of values to be returned.
+
+Built-in functions
+A built-in function object is a wrapper around a C function. Examples of built-in functions are len() and math.sin() (math is a standard built-in module). The number and type of the arguments are determined by the C function. Special read-only attributes: __doc__ is the function’s documentation string, or None if unavailable; __name__ is the function’s name; __self__ is set to None (but see the next item); __module__ is the name of the module the function was defined in or None if unavailable.
+
+Built-in methods
+This is really a different disguise of a built-in function, this time containing an object passed to the C function as an implicit extra argument. An example of a built-in method is alist.append(), assuming alist is a list object. In this case, the special read-only attribute __self__ is set to the object denoted by list.
+
+Class Types
+Class types, or “new-style classes,” are callable. These objects normally act as factories for new instances of themselves, but variations are possible for class types that override __new__(). The arguments of the call are passed to __new__() and, in the typical case, to __init__() to initialize the new instance.
+Classic Classes
+Class objects are described below. When a class object is called, a new class instance (also described below) is created and returned. This implies a call to the class’s __init__() method if it has one. Any arguments are passed on to the __init__() method. If there is no __init__() method, the class must be called without arguments.
+
+Class instances
+Class instances are described below. Class instances are callable only when the class has a __call__() method; x(arguments) is a shorthand for x.__call__(arguments).
+Modules
+Modules are imported by the import statement (see section The import statement). A module object has a namespace implemented by a dictionary object (this is the dictionary referenced by the func_globals attribute of functions defined in the module). Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.__dict__["x"]. A module object does not contain the code object used to initialize the module (since it isn’t needed once the initialization is done).
+
+Attribute assignment updates the module’s namespace dictionary, e.g., m.x = 1 is equivalent to m.__dict__["x"] = 1.
+
+Special read-only attribute: __dict__ is the module’s namespace as a dictionary object.
+
+CPython implementation detail: Because of the way CPython clears module dictionaries, the module dictionary will be cleared when the module falls out of scope even if the dictionary still has live references. To avoid this, copy the dictionary or keep the module around while using its dictionary directly.
+
+Predefined (writable) attributes: __name__ is the module’s name; __doc__ is the module’s documentation string, or None if unavailable; __file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.
+
+Classes
+Both class types (new-style classes) and class objects (old-style/classic classes) are typically created by class definitions (see section Class definitions). A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., C.x is translated to C.__dict__["x"] (although for new-style classes in particular there are a number of hooks which allow for other means of locating attributes). When the attribute name is not found there, the attribute search continues in the base classes. For old-style classes, the search is depth-first, left-to-right in the order of occurrence in the base class list. New-style classes use the more complex C3 method resolution order which behaves correctly even in the presence of ‘diamond’ inheritance structures where there are multiple inheritance paths leading back to a common ancestor. Additional details on the C3 MRO used by new-style classes can be found in the documentation accompanying the 2.3 release at http://www.python.org/download/releases/2.3/mro/.
+
+When a class attribute reference (for class C, say) would yield a user-defined function object or an unbound user-defined method object whose associated class is either C or one of its base classes, it is transformed into an unbound user-defined method object whose im_class attribute is C. When it would yield a class method object, it is transformed into a bound user-defined method object whose im_class and im_self attributes are both C. When it would yield a static method object, it is transformed into the object wrapped by the static method object. See section Implementing Descriptors for another way in which attributes retrieved from a class may differ from those actually contained in its __dict__ (note that only new-style classes support descriptors).
+
+Class attribute assignments update the class’s dictionary, never the dictionary of a base class.
+
+A class object can be called (see above) to yield a class instance (see below).
+
+Special attributes: __name__ is the class name; __module__ is the module name in which the class was defined; __dict__ is the dictionary containing the class’s namespace; __bases__ is a tuple (possibly empty or a singleton) containing the base classes, in the order of their occurrence in the base class list; __doc__ is the class’s documentation string, or None if undefined.
+
+Class instances
+A class instance is created by calling a class object (see above). A class instance has a namespace implemented as a dictionary which is the first place in which attribute references are searched. When an attribute is not found there, and the instance’s class has an attribute by that name, the search continues with the class attributes. If a class attribute is found that is a user-defined function object or an unbound user-defined method object whose associated class is the class (call it C) of the instance for which the attribute reference was initiated or one of its bases, it is transformed into a bound user-defined method object whose im_class attribute is C and whose im_self attribute is the instance. Static method and class method objects are also transformed, as if they had been retrieved from class C; see above under “Classes”. See section Implementing Descriptors for another way in which attributes of a class retrieved via its instances may differ from the objects actually stored in the class’s __dict__. If no class attribute is found, and the object’s class has a __getattr__() method, that is called to satisfy the lookup.
+
+Attribute assignments and deletions update the instance’s dictionary, never a class’s dictionary. If the class has a __setattr__() or __delattr__() method, this is called instead of updating the instance dictionary directly.
+
+Class instances can pretend to be numbers, sequences, or mappings if they have methods with certain special names. See section Special method names.
+
+Special attributes: __dict__ is the attribute dictionary; __class__ is the instance’s class.
+
+Files
+A file object represents an open file. File objects are created by the open() built-in function, and also by os.popen(), os.fdopen(), and the makefile() method of socket objects (and perhaps by other functions or methods provided by extension modules). The objects sys.stdin, sys.stdout and sys.stderr are initialized to file objects corresponding to the interpreter’s standard input, output and error streams. See File Objects for complete documentation of file objects.
+
+Internal types
+A few types used internally by the interpreter are exposed to the user. Their definitions may change with future versions of the interpreter, but they are mentioned here for completeness.
+
+Code objects
+Code objects represent byte-compiled executable Python code, or bytecode. The difference between a code object and a function object is that the function object contains an explicit reference to the function’s globals (the module in which it was defined), while a code object contains no context; also the default argument values are stored in the function object, not in the code object (because they represent values calculated at run-time). Unlike function objects, code objects are immutable and contain no references (directly or indirectly) to mutable objects.
+
+Special read-only attributes: co_name gives the function name; co_argcount is the number of positional arguments (including arguments with default values); co_nlocals is the number of local variables used by the function (including arguments); co_varnames is a tuple containing the names of the local variables (starting with the argument names); co_cellvars is a tuple containing the names of local variables that are referenced by nested functions; co_freevars is a tuple containing the names of free variables; co_code is a string representing the sequence of bytecode instructions; co_consts is a tuple containing the literals used by the bytecode; co_names is a tuple containing the names used by the bytecode; co_filename is the filename from which the code was compiled; co_firstlineno is the first line number of the function; co_lnotab is a string encoding the mapping from bytecode offsets to line numbers (for details see the source code of the interpreter); co_stacksize is the required stack size (including local variables); co_flags is an integer encoding a number of flags for the interpreter.
+
+The following flag bits are defined for co_flags: bit 0x04 is set if the function uses the *arguments syntax to accept an arbitrary number of positional arguments; bit 0x08 is set if the function uses the **keywords syntax to accept arbitrary keyword arguments; bit 0x20 is set if the function is a generator.
+
+Future feature declarations (from __future__ import division) also use bits in co_flags to indicate whether a code object was compiled with a particular feature enabled: bit 0x2000 is set if the function was compiled with future division enabled; bits 0x10 and 0x1000 were used in earlier versions of Python.
+
+Other bits in co_flags are reserved for internal use.
+
+If a code object represents a function, the first item in co_consts is the documentation string of the function, or None if undefined.
+
+Frame objects
+Frame objects represent execution frames. They may occur in traceback objects (see below).
+
+Special read-only attributes: f_back is to the previous stack frame (towards the caller), or None if this is the bottom stack frame; f_code is the code object being executed in this frame; f_locals is the dictionary used to look up local variables; f_globals is used for global variables; f_builtins is used for built-in (intrinsic) names; f_restricted is a flag indicating whether the function is executing in restricted execution mode; f_lasti gives the precise instruction (this is an index into the bytecode string of the code object).
+
+Special writable attributes: f_trace, if not None, is a function called at the start of each source code line (this is used by the debugger); f_exc_type, f_exc_value, f_exc_traceback represent the last exception raised in the parent frame provided another exception was ever raised in the current frame (in all other cases they are None); f_lineno is the current line number of the frame  writing to this from within a trace function jumps to the given line (only for the bottom-most frame). A debugger can implement a Jump command (aka Set Next Statement) by writing to f_lineno.
+
+Traceback objects
+Traceback objects represent a stack trace of an exception. A traceback object is created when an exception occurs. When the search for an exception handler unwinds the execution stack, at each unwound level a traceback object is inserted in front of the current traceback. When an exception handler is entered, the stack trace is made available to the program. (See section The try statement.) It is accessible as sys.exc_traceback, and also as the third item of the tuple returned by sys.exc_info(). The latter is the preferred interface, since it works correctly when the program is using multiple threads. When the program contains no suitable handler, the stack trace is written (nicely formatted) to the standard error stream; if the interpreter is interactive, it is also made available to the user as sys.last_traceback.
+
+Special read-only attributes: tb_next is the next level in the stack trace (towards the frame where the exception occurred), or None if there is no next level; tb_frame points to the execution frame of the current level; tb_lineno gives the line number where the exception occurred; tb_lasti indicates the precise instruction. The line number and last instruction in the traceback may differ from the line number of its frame object if the exception occurred in a try statement with no matching except clause or with a finally clause.
+
+Slice objects
+Slice objects are used to represent slices when extended slice syntax is used. This is a slice using two colons, or multiple slices or ellipses separated by commas, e.g., a[i:j:step], a[i:j, k:l], or a[..., i:j]. They are also created by the built-in slice() function.
+
+Special read-only attributes: start is the lower bound; stop is the upper bound; step is the step value; each is None if omitted. These attributes can have any type.
+
+Slice objects support one method:
+
+slice.indices(self, length)
+This method takes a single integer argument length and computes information about the extended slice that the slice object would describe if applied to a sequence of length items. It returns a tuple of three integers; respectively these are the start and stop indices and the step or stride length of the slice. Missing or out-of-bounds indices are handled in a manner consistent with regular slices.
+
+New in version 2.3.
+
+Static method objects
+Static method objects provide a way of defeating the transformation of function objects to method objects described above. A static method object is a wrapper around any other object, usually a user-defined method object. When a static method object is retrieved from a class or a class instance, the object actually returned is the wrapped object, which is not subject to any further transformation. Static method objects are not themselves callable, although the objects they wrap usually are. Static method objects are created by the built-in staticmethod() constructor.
+Class method objects
+A class method object, like a static method object, is a wrapper around another object that alters the way in which that object is retrieved from classes and class instances. The behaviour of class method objects upon such retrieval is described above, under “User-defined methods”. Class method objects are created by the built-in classmethod() constructor.

File string.idl.in

 boolean /* or fail? */ PyString_CheckExact(PyObject *o);
 // Return true if the object o is a string object, but not an instance of a subtype of the string type.
 
-[new] PyObject* PyString_FromString([string] const char *v);
+[new] PyStringObject* PyString_FromString([string] const char *v);
 // Return value: New reference.
 // Return a new string object with a copy of the string v as value on success, and NULL on failure. The parameter v must not be NULL; it will not be checked.
 
-[new] PyObject* PyString_FromStringAndSize([string] const char *v, Py_ssize_t len);
+[new] PyStringObject* PyString_FromStringAndSize([string] const char *v, Py_ssize_t len);
 // Return value: New reference.
 // Return a new string object with a copy of the string v as value and length len on success, and NULL on failure. If v is NULL, the contents of the string are uninitialized.
 
-// PyObject* PyString_FromFormat(const char *format, ...);
+// PyStringObject* PyString_FromFormat(const char *format, ...);
 // Return value: New reference.
 // Take a C printf()-style format string and a variable number of arguments, calculate the size of the resulting Python string and return a string with the values formatted into it. The variable arguments must be C types and must correspond exactly to the format characters in the format string. The following format characters are allowed:
 //
 // Note The “%lld” and “%llu” format specifiers are only available when HAVE_LONG_LONG is defined.
 // Changed in version 2.7: Support for “%lld” and “%llu” added.
 
-// PyObject* PyString_FromFormatV(const char *format, va_list vargs);
+// PyStringObject* PyString_FromFormatV(const char *format, va_list vargs);
 // Return value: New reference.
 // Identical to PyString_FromFormat() except that it takes exactly two arguments.
 
-size_or_fail PyString_Size(PyObject *string);
+size_or_fail PyString_Size(PyStringObject *string);
 // Return the length of the string in string object string.
 
-size_or_fail PyString_GET_SIZE(PyObject *string);
+size_or_fail PyString_GET_SIZE(PyStringObject *string);
 // Macro form of PyString_Size() but without error checking.
 
-[string] char* PyString_AsString(PyObject *string);
+[string] char* PyString_AsString(PyStringObject *string);
 // Return a NUL-terminated representation of the contents of string. The pointer refers to the internal buffer of string, not a copy. The data must not be modified in any way, unless the string was just created using PyString_FromStringAndSize(NULL, size). It must not be deallocated. If string is a Unicode object, this function computes the default encoding of string and operates on that. If string is not a string object at all, PyString_AsString() returns NULL and raises TypeError.
 
-[string] char* PyString_AS_STRING(PyObject *string);
+[string] char* PyString_AS_STRING(PyStringObject *string);
 // Macro form of PyString_AsString() but without error checking. Only string objects are supported; no Unicode objects should be passed.
 
-size_or_fail /* int */ PyString_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length);
+size_or_fail /* int */ PyString_AsStringAndSize(PyStringObject *obj, char **buffer, Py_ssize_t *length);
 // Return a NUL-terminated representation of the contents of the object obj through the output variables buffer and length.
 // The function accepts both string and Unicode objects as input. For Unicode objects it returns the default encoded version of the object. If length is NULL, the resulting buffer may not contain NUL characters; if it does, the function returns -1 and a TypeError is raised.
 // The buffer refers to an internal string buffer of obj, not a copy. The data must not be modified in any way, unless the string was just created using PyString_FromStringAndSize(NULL, size). It must not be deallocated. If string is a Unicode object, this function computes the default encoding of string and operates on that. If string is not a string object at all, PyString_AsStringAndSize() returns -1 and raises TypeError.
 
-// void PyString_Concat(PyObject **string, PyObject *newpart);
+// void PyString_Concat(PyStringObject **string, PyStringObject *newpart);
 // Create a new string object in *string containing the contents of newpart appended to string; the caller will own the new reference. The reference to the old value of string will be stolen. If the new string cannot be created, the old reference to string will still be discarded and the value of *string will be set to NULL; the appropriate exception will be set.
 
-// void PyString_ConcatAndDel(PyObject **string, PyObject *newpart);
+// void PyString_ConcatAndDel(PyStringObject **string, PyStringObject *newpart);
 // Create a new string object in *string containing the contents of newpart appended to string. This version decrements the reference count of newpart.
 
-// int _PyString_Resize(PyObject **string, Py_ssize_t newsize);
+// int _PyString_Resize(PyStringObject **string, Py_ssize_t newsize);
 // A way to resize a string object even though it is “immutable”. Only use this to build up a brand new string object; don’t use this if the string may already be known in other parts of the code. It is an error to call this function if the refcount on the input string object is not one. Pass the address of an existing string object as an lvalue (it may be written into), and the new size desired. On success, *string holds the resized string object and 0 is returned; the address in *string may differ from its input value. If the reallocation fails, the original string object at *string is deallocated, *string is set to NULL, a memory exception is set, and -1 is returned.
 
-[new] PyObject* PyString_Format(PyObject *format, PyObject *args);
+[new] PyStringObject* PyString_Format(PyStringObject *format, PyTupleObject *args);
 // Return value: New reference.
 // Return a new string object from format and args. Analogous to format % args. The args argument must be a tuple.
 
-// void PyString_InternInPlace(PyObject **string);
+// void PyString_InternInPlace(PyStringObject **string);
 // Intern the argument *string in place. The argument must be the address of a pointer variable pointing to a Python string object. If there is an existing interned string that is the same as *string, it sets *string to it (decrementing the reference count of the old string object and incrementing the reference count of the interned string object), otherwise it leaves *string alone and interns it (incrementing its reference count). (Clarification: even though there is a lot of talk about reference counts, think of this function as reference-count-neutral; you own the object after the call if and only if you owned it before the call.)
 
-[new] PyObject* PyString_InternFromString([string] const char *v);
+[new] PyStringObject* PyString_InternFromString([string] const char *v);
 // Return value: New reference.
 // A combination of PyString_FromString() and PyString_InternInPlace(), returning either a new string object that has been interned, or a new (“owned”) reference to an earlier interned string object with the same value.
 
-// PyObject* PyString_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors)
+// PyStringObject* PyString_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors)
 // Return value: New reference.
 // Create an object by decoding size bytes of the encoded buffer s using the codec registered for encoding. encoding and errors have the same meaning as the parameters of the same name in the unicode() built-in function. The codec to be used is looked up using the Python codec registry. Return NULL if an exception was raised by the codec.
 
-// PyObject* PyString_AsDecodedObject(PyObject *str, const char *encoding, const char *errors);
+// PyStringObject* PyString_AsDecodedObject(PyStringObject *str, const char *encoding, const char *errors);
 // Return value: New reference.
 // Decode a string object by passing it to the codec registered for encoding and return the result as Python object. encoding and errors have the same meaning as the parameters of the same name in the string encode() method. The codec to be used is looked up using the Python codec registry. Return NULL if an exception was raised by the codec.
 
-// PyObject* PyString_Encode(const char *s, Py_ssize_t size, const char *encoding, const char *errors);
+// PyStringObject* PyString_Encode(const char *s, Py_ssize_t size, const char *encoding, const char *errors);
 // Return value: New reference.
 // Encode the char buffer of the given size by passing it to the codec registered for encoding and return a Python object. encoding and errors have the same meaning as the parameters of the same name in the string encode() method. The codec to be used is looked up using the Python codec registry. Return NULL if an exception was raised by the codec.
 
-// PyObject* PyString_AsEncodedObject(PyObject *str, const char *encoding, const char *errors);
+// PyStringObject* PyString_AsEncodedObject(PyStringObject *str, const char *encoding, const char *errors);
 // Return value: New reference.
 // Encode a string object using the codec registered for encoding and return the result as Python object. encoding and errors have the same meaning as the parameters of the same name in the string encode() method. The codec to be used is looked up using the Python codec registry. Return NULL if an exception was raised by the codec.
 
     Base.debug "o" o;
 
     prerr_endline "calling function";
-    let res = Object.callObject capitalize (Some tpl) in
+    let res = Object.callObject (Callable.coerce capitalize) (Some tpl) in
     Printf.eprintf "res : refcnt = %d\n%!" (Base.refcnt res);
     prerr_endline "function called!";
-    prerr_endline (String.asString res);
+    prerr_endline (String.asString (String.coerce res));
     prerr_endline (String.asString o);
 
     let minus_1 = Int.fromLong (-1) in

File tuple.idl.in

 boolean PyTuple_CheckExact(PyObject *p);
 // Return true if p is a tuple object, but not an instance of a subtype of the tuple type.
 
-[new] PyObject* PyTuple_New(Py_ssize_t len);
+[new] PyTupleObject* PyTuple_New(Py_ssize_t len);
 // Return value: New reference.
 // Return a new tuple object of size len, or NULL on failure.
 
 // Return value: New reference.
 // Return a new tuple object of size n, or NULL on failure. The tuple values are initialized to the subsequent n C arguments pointing to Python objects. PyTuple_Pack(2, a, b) is equivalent to Py_BuildValue("(OO)", a, b).
 
-size_or_fail PyTuple_Size(PyObject *p);
+size_or_fail PyTuple_Size(PyTupleObject *p);
 // Take a pointer to a tuple object, and return the size of that tuple.
 
-size_or_fail PyTuple_GET_SIZE(PyObject *p);
+size_or_fail PyTuple_GET_SIZE(PyTupleObject *p);
 // Return the size of the tuple p, which must be non-NULL and point to a tuple; no error checking is performed.
 
-PyObject* PyTuple_GetItem(PyObject *p, Py_ssize_t pos);
+PyObject* PyTuple_GetItem(PyTupleObject *p, Py_ssize_t pos);
 // Return value: Borrowed reference.
 // Return the object at position pos in the tuple pointed to by p. If pos is out of bounds, return NULL and sets an IndexError exception.
 
-PyObject* PyTuple_GET_ITEM(PyObject *p, Py_ssize_t pos);
+PyObject* PyTuple_GET_ITEM(PyTupleObject *p, Py_ssize_t pos);
 // Return value: Borrowed reference.
 // Like PyTuple_GetItem(), but does no checking of its arguments.
 
-[new] PyObject* PyTuple_GetSlice(PyObject *p, Py_ssize_t low, Py_ssize_t high);
+[new] PySliceObject* PyTuple_GetSlice(PyTupleObject *p, Py_ssize_t low, Py_ssize_t high);
 // Return value: New reference.
 // Take a slice of the tuple pointed to by p from low to high and return it as a new tuple.
 
-unit_or_fail PyTuple_SetItem(PyObject *p, Py_ssize_t pos, [stolen] PyObject *o);
+unit_or_fail PyTuple_SetItem(PyTupleObject *p, Py_ssize_t pos, [stolen] PyObject *o);
 // Insert a reference to object o at position pos of the tuple pointed to by p. Return 0 on success.
 // 
 // Note This function “steals” a reference to o.
 
-void PyTuple_SET_ITEM(PyObject *p, Py_ssize_t pos, [stolen] PyObject *o);
+void PyTuple_SET_ITEM(PyTupleObject *p, Py_ssize_t pos, [stolen] PyObject *o);
 // Like PyTuple_SetItem(), but does no error checking, and should only be used to fill in brand new tuples.
 //
 // Note This function “steals” a reference to o.
 // unsigned int PyType_ClearCache()¶
 int PyType_ClearCache(); // unsigned int actually
 
-//TYPE void PyType_Modified(PyTypeObject *type);
-//TYPE //    Invalidate the internal lookup cache for the type and all of its subtypes. This function must be called after any manual modification of the attributes or base classes of the type.
+void [wrap] PyType_Modified(PyTypeObject *type);
+//    Invalidate the internal lookup cache for the type and all of its subtypes. This function must be called after any manual modification of the attributes or base classes of the type.
 
-//TYPE bool_or_fail PyType_HasFeature(PyObject *o, int feature);
-//TYPE //    Return true if the type object o sets the feature feature. Type features are denoted by single bit flags.
+bool_or_fail [wrap] PyType_HasFeature(PyTypeObject *o, int feature);
+//    Return true if the type object o sets the feature feature. Type features are denoted by single bit flags.
 
-//TYPE bool_or_fail PyType_IS_GC(PyObject *o);
-//TYPE //    Return true if the type object includes support for the cycle detector; this tests the type flag Py_TPFLAGS_HAVE_GC.
+bool_or_fail [wrap] PyType_IS_GC(PyTypeObject *o);
+//    Return true if the type object includes support for the cycle detector; this tests the type flag Py_TPFLAGS_HAVE_GC.
 
-//TYPE bool_or_fail PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b);
-//TYPE //    Return true if a is a subtype of b.
-//TYPE 
-//TYPE PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems);
-//TYPE //    Return value: New reference.
-//TYPE 
-//TYPE PyObject* PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds);
-//TYPE //    Return value: New reference.
-//TYPE 
-//TYPE unit_or_fail PyType_Ready(PyTypeObject *type);
-//TYPE //    Finalize a type object. This should be called on all type objects to finish their initialization. This function is responsible for adding inherited slots from a type’s base class. Return 0 on success, or return -1 and sets an exception on error.
+bool_or_fail [wrap] PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b);
+//    Return true if a is a subtype of b.
 
+PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems);
+//    Return value: New reference.
+
+PyObject* PyType_GenericNew(PyTypeObject *type, PyTupleObject *args, PyDictObject *kwds);
+//    Return value: New reference.
+
+unit_or_fail PyType_Ready(PyTypeObject *type);
+//    Finalize a type object. This should be called on all type objects to finish their initialization. This function is responsible for adding inherited slots from a type’s base class. Return 0 on success, or return -1 and sets an exception on error.
+