[C++-sig] Executing scripts in other namespace than __main__

Fabzter faboster at gmail.com
Thu Mar 18 18:49:38 CET 2010


Hi. The only way I could deal with this issue was to keep track of
every class derived from the BaseClass, in order to _not_ using it
again to instantiate an object. I changed this:

> exec("import sys\n", namespace_module_main,
>                                namespace_module_main);

to:

> exec("import sys\n classes = []\n", namespace_module_main,
>                                namespace_module_main);

and:

> object ignored_ =
>        exec("l = dir()\n" //get everything defined in current dictionary
>             "class_ = None\n"
>             "for i in l:\n"
>             "    res = eval(i)\n"
>             "    if type(res) == type(BaseClass): class_ = res\n"
> //if we've got a class derived from BaseClass, we save it to "class_"
>             "if class_ is None: raise Error()\n"
>                , this->namespace_modulo_local, this->namespace_modulo_local);

to:

> object ignored_ =
>        exec("l = dir()\n" //get everything defined in current dictionary
>             "class_ = None\n"
>             "for i in l:\n"
>             "    res = eval(i)\n"
>             "    if type(res) == type(BaseClass) and res not in classes:\n
>             "        class_ = res\n"
>             "        classes.append( res); break\n"
> //if we've got a class derived from BaseClass, we save it to "class_"
>             "if class_ is None: raise Error()\n"
>                , this->namespace_modulo_local, this->namespace_modulo_local);

And it works quite well for my purposes, but I would like to know if
there's a more elegant way to extract a class which I know its base
class, but not its name.


More information about the Cplusplus-sig mailing list