[Python-Dev] Re: PEP 328 -- relative and multi-line import (original) (raw)

Aahz aahz at pythoncraft.com
Mon Apr 5 13:36:24 EDT 2004


On Mon, Apr 05, 2004, Shane Holloway (IEEE) wrote:

Aahz wrote:

On Mon, Apr 05, 2004, Shane Holloway (IEEE) wrote:

Aahz:

Good point. Here's what I think the semantics are; as soon as I get agreement, I'll update the PEP. Given a package layout::

package subpackage1 moduleX moduleY subpackage2 moduleZ moduleA Each leading "." refers to one level of parent. Assuming that the current file is moduleX.py, following are correct usages of the new syntax:: from .moduleY import spam from ..subpackage1 import moduleY from ..subpackage2.moduleZ import eggs from ..moduleA import foo from ...package import bar What about names inside package init? from .. import bar Is this also valid? Do you mean subpackage1's init.py? If so, yes. For most purposes, a package's init.py is treated as if it were a module with the name of the package. Actually, no I meant package's init.py -- so that:: from .. import bar as barA from ...package import bar as barB assert barA is barB

That makes no sense at all; both of those imports are wrong from package's init.py.

Hmmmm... I think I see what you're getting at: how do you access subpackage1 from package's init.py using relative imports? Seems to me that you'd have to do ::

from .package import subpackage1 Normally, though, subpackages import from their parents, not the other way around. I would intuit that one would import subpackage1 from package as:: from . import subpackage1 but that's not explicitly spelled out. Is this correct?

Your intuition is wrong. From package's init.py, from . refers to package's parent; to get back into the package, you need to use from .package. It's precisely the same as the example above with moduleX getting bar -- but because moduleX is two levels down, it needs two more dots. You're getting confused because you think of init.py as being a level below the package that contains it; however, init.py IS the package level. It's the code for the package.

If anyone else has been confused by this, please let me know and I'll add clarification to the PEP, but I think these consequences are pretty clear if you understand how packages work.

Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/

Why is this newsgroup different from all other newsgroups?



More information about the Python-Dev mailing list