string to type object (C)

castironpi castironpi at gmail.com
Wed Aug 6 00:55:10 EDT 2008


On Aug 5, 7:59 pm, Miles <semantic... at gmail.com> wrote:
> On Tue, Aug 5, 2008 at 2:30 AM, castironpi <castiro... at gmail.com> wrote:
> > I'm looking for a one-to-one function from strings to the built-in
> > data types in C.  I will be keeping the string in a file.  I need the
> > PyTypeObject* back from it.  If nothing else I'll just do a bunch of
> > strcmp( "tuple" ) { return &PyTuple_Type; } commands, provided
> > &PyTuple_Type; will be linking the right address.
>
> Something along the lines of this?
> b = PyImport_Import("__builtin__");
> return PyObject_GetAttrString(b, typestring);
>
> -Miles

Miles,

That's what I was looking for.  I wanted to avoid the heavy Import but
I thought I remembered that imports are free after the first time.

Import needed a PyString.

	PyObject* s= PyString_FromString( "__builtin__" );
	PyObject* b= PyImport_Import(s);
	return PyObject_GetAttrString(b, "str");

I expect I need a Py_DECREF on s and b.

Do you know if uncooperative (not necc'ly malicious) code could
interfere:

>>> __builtin__.int= None
>>> __builtin__.int
>>> __builtin__.int= type( 0 )
>>> __builtin__.int
<type 'int'>

?  Or would PyImport_Import(s) create a namespace that had the int
type in it from scratch?



More information about the Python-list mailing list