Howto: creating empty modules?

Alex Martelli aleax at aleax.it
Wed Jan 9 13:46:24 CET 2002


"Janko Hauser" <jhauser at ifm.uni-kiel.de> wrote in message
news:87sn9fk9m1.fsf at ifm.uni-kiel.de...
> "Alex Martelli" <aleax at aleax.it> writes:
>
> > "Ville Vainio" <vvainio at karhu.tp.spt.fi> wrote in message
> > news:yoxelkzrgnh.fsf at karhu.tp.spt.fi...
> > > How should I go about creating an empty module?
> > >
> > > I mean
> > >
> > > config = make_empty_module()
> > > config.someattr = "hi"
> >
> > Any module has a name, even an empty one.  As you don't
> > seem to want to pass a name to the make_empty_module function,
> > you presumably want that function to generate some artificial
> > unique name?  You'll have to clarify that.
> >
>
> It seems to me the name should be config. And with such a name it

In this case, config = new.module('config') will do the job.

> looks like the OP wants to share information between modules, which is
> not possible with this approach, if I'm not mistaken.

It's OK to insert this new module in sys.modules:

import sys
sys.modules.append(config)

and then any other module can get at it with

import config.


> If he just wants to have a place to store configuration in the calling
module
> an empty class would be enough.
>
> class EmptyClass:
>     pass
>
> config=EmptyClass()
> config.someattr = 'hi'
>
> For variations on this theme (singleton) look for posts from Alex
> Martelli :-).

A class gives peculiar problems and no advantages for the use you
surmise.  E.g., you can't just have one of the class's attributes
be a function -- you have to use the staticmethod built-in (in 2.2,
or build the equivalent yourself in previous releases).  If one is
using a Python release older than 2.1, a class or an instance
cannot be registered in sys.modules (it's OK from 2.1 onwards).

All in all, if one only wants to do stuff a module can do well, I
think it's better to use a module for this purpose, rather than a
class (or an instance or other things yet).  MHO, of course.


Alex






More information about the Python-list mailing list