Alan Isaac <[EMAIL PROTECTED]> wrote: > "Alex Martelli" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > > If you're running test1.py as your main module, then it's not part of a > > package, so the relative import should indeed fail as you mention. > > So if I understand you, > in a package, any module that I wish > to make available for execution as a script > (in the usual way, with a main function) > cannot have any relative imports. > Is this right? What is the reason for > this restriction? (And where is it > documented?)
The most up-to-date documentation for import and from statements is at <http://docs.python.org/dev/ref/import.html> but it's still somewhat incomplete -- it gives the grammar for relative imports, but does not explain its semantics, nor, for that matter, any of the semantics of pakages. The discussions about relative imports in particular are recorded as PEP 328, while an old essay about the semantics of packages is recorded at a link give on the docs page I mentioned. Very simply, PEP 328 explains: """ Relative Imports and __name__ Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system. """ and points to four discussion threads on python-dev which, after much give and take, led to Guido picking these semantics. To me, it makes sense: if a module is top-level, and thus not part of a package (and __main__ in particular is always in that state), then saying "import from the current package" has no well defined meaning, because there IS no "current package". Using __name__ rather than __file__, in turn, makes a lot of sense, because a package's _logical_ structure is defined by its __path__, and need not coincide with any _physical_ arrangement of directories. If you have a better and sharper idea about how relative imports should work in toplevel modules (those whose __name__ indicates they have NOT been imported as part of a package, including __main__), feel free to make a case for it on python-dev (python-list is fine for preliminary discussions and brainstorming, but nothing will happen about any idea until and unless it's taken to python-dev, survives the scathing barrage of objections that strongly characterizes that mailing list, and finally manages to convince Guido:-). Alex -- http://mail.python.org/mailman/listinfo/python-list