[C++-sig] Re: sub module support in V2

Dave Hawkes daveh at cadlink.com
Wed Jun 5 19:44:23 CEST 2002


"Dave Hawkes" <daveh at cadlink.com> wrote in message
news:adlgit$hmf$1 at main.gmane.org...
>
>
> Unfortuantely, yes, something will have to be done about Py_InitModule,
> which call PyImport_AddModule. Maybe we should just delete the sys.modules
> entry that is produced as a result? Unless there is a more elegant
solution.
>
> I'd also like to add some code that checks if a sub-module of the same
name
> already exists and return a reference to that rather than a new sub-module
> so we don't lose previous definitions.
>

No, this is not correct! I think we need to do something along these lines:

class sub_module : public module {
public:
  sub_module(const char* name) : module(name) {}
  sub_module(module& parent, const char* name) :
module(get_sub_module_name(parent, name).c_str()) {
    parent.setattr(name, object());
  }
  sub_module sub(const char* name) {
    return sub_module(*this, name);
  }
  template <class Fn>
  sub_module& def(char const* name, Fn fn) {
    this->module::def(name, fn);
    return  *this;
  }
  static std::string get_sub_module_name(module parent, const char *name) {
    ref module_name(PyObject_GetAttrString(parent.object().get(),
const_cast<char*>("__name__")));
    from_python<std::string> converter(module_name.get());
    std::string n = converter(module_name.get()) + '.';
    n += name;
    return n;
  }
};

This ensures sys.modules contains the correct dotted reference for the
sub-module.

Dave Hawkes










More information about the Cplusplus-sig mailing list