Importing class from file in package

Peter Hansen peter at engcorp.com
Sat Dec 4 21:44:07 CET 2004


Florian Lindner wrote:
> I've two files in my package.
> In the first file I want to inport a class which is declared in the 
> second file. How can do that without stating the absolute path to the 
> file, just the relative one?

Assuming you mean by "package" that you have a folder named, say,
"mypkg" and an __init__.py file in it (that last part is required
for it to be a package in Python), and files a.py and b.py, this
works just fine if you do nothing special:

file mypkg/a.py contains:

class A:
     pass


file mypkg/b.py contains:

import a
print a.A()

If I run the interpreter in the folder above mypkg,
this works just fine:

 >>> import mypkg.b
<mypkg.a.A instance at 0x00AE8120>


So that leads me to think that either you didn't try this,
or I misunderstood the question...

-Peter



More information about the Python-list mailing list