views:

435

answers:

1

Hello all,

I'm having a spot of trouble getting my python classes to work within the python console. I want to automatically import all of my classes into the global namespace so I can use them without any prefix.module.names.

Here's what I've got so far...

projectname/
|-__init__.py
|
|-main_stuff/
  |-__init__.py
  |-main1.py
  |-main2.py
  |
  |-other_stuff/
    |-__init__.py
    |-other1.py
    |-other2.py

Each file defines a class of the same name, e.g. main1.py will define a class called Main1.

My PYTHONPATH is the absolute path to projectname/.

I've got a python startup file that contains this:

from projectname import *

But this doesn't let me use my classes at all. Upon starting a python console I would like to be able to write:

ob=Main1()

but Main1 isn't within the current namespace, so it doesn't work.

I tried adding things to the __init__.py files...

In projectname/__init__.py:

import main_stuff

In projectname/main_stuff/__init__.py:

import other_stuff
__all__ = ["main1", "main2", "main3"]

And so on. And in my startup file I added:

from projectname.main_stuff import *
from projectname.main_stuff/other_stuff import *

But to use the classes within the python console I still have to write:

ob=main1.Main1()

I'd prefer not to need the main1. part. Does anyone know how I can automatically put my classes in the global namespace when using the python console?

Thanks.

==== EDIT ====

What I need is to import a package at the class level, but from package import * gives me everything at the module level. I'm after an easy way of doing something like this:

for module in package do:
    from package.module import *
+1  A: 

You want to use a different form of import.

In projectname/main_stuff/__init__.py:

from other_stuff import *
__all__ = ["main1", "main2", "main3"]

When you use a statement like this:

import foo

You are defining the name foo in the current module. Then you can use foo.something to get at the stuff in foo.

When you use this:

from foo import *

You are taking all of the names defined in foo and defining them in this module (like pouring a bucket of names from foo into your module).

Ned Batchelder