Accessing Python variables in an extension module

Alex Martelli aleax at mac.com
Mon Jul 16 10:53:14 EDT 2007


MD <manasd at gmail.com> wrote:

> Hi Alex,
>    Thanks for your reply. It was exactly what I was looking for. Two
> additional questions
> 1) Is there anyway to find out which modules a variable belongs to
> when I have only its name (and its not qualified with the complete
> name like module.varname)

Loop through all modules in sys.modules and you will find a set (which
may be empty) of modules which happen to have that name as an attribute.
It's a very peculiar thing to do (not clear what you expect to do based
on that information) but not difficult.

> 2) Is there anyway to find the type of the object in C using something
> like a switch statement? I was looking for something like this
>    switch type(object) {
>       STRING: "This is a string object";
>               break;
>       INTEGER: "This is an integer object";
>               break;
>       BOOLEAN: "This is a boolean object";
>       .........
>       .........
>       }
> I don't want to run all the C Py***_Check functions on the object.
> Something like the switch statement above will lead to nice and clean
> code.

Each Python object, in C, carries a pointer to its type object.  Of
course there are unbounded numbers of types, but at least you can get
such information as the type's name and the module if any in which it
may have been defined, essentially like you'd do with type(somobj) if
you were working directly in Python.


Alex



More information about the Python-list mailing list