Creating classes and objects more than once?

Carl Banks pavlovevidence at
Fri Nov 28 17:01:45 CET 2008

On Nov 28, 3:24 am, Viktor Kerkez <alefn... at> wrote:
> On Nov 28, 9:35 am, Carl Banks <pavlovevide... at> wrote:
> > However, I'm not so sure the effect of os.chdir() on the import path
> > is a good idea.
> I'm not actually using os.chidir(), I just used it here to create a
> clearer example.
> Here is the simplest representation of the problem:
> $ cd singleton_test
> $ export PYTHONPATH=.
> $ python application/
> Creating class Singleton
> Creating class MySingleton
> Creating class Singleton
> Creating class MySingleton
> $

Ah ha.  That's a slightly different issue.  Here's the problem: when
you type "python application/", Python doens't call the
module it runs "application,main_script" like you'd expect.  Instead
it calls the module "__main__".  Thus, when you later import
"application.main_script", Python doesn't see any already-loaded
modules called application.main_script, so it imports the file again
(this time calling the module "application.main_script").

Try it this way:

python -c 'import application.main_script'

In this example, Python the string passed to "-c" is considered the
__main__ module, so when you import application.main_script it calls
the module it imports "application.main_script", so you will get the
behavior you expect.

The thing you have to remember is, "Never try to reimport the main
script; it just won't work."  If you find yourself doing that, create
a tiny script whose sole job is to import the real main script (and
maybe set up sys.path), and run that.  (Also, some people consider
reciprocal imports to be bad style.  I'm not one of them per se but I
find that it's worth the effort to avoid them if it's easy to do so.)

Carl Banks

More information about the Python-list mailing list