[docs] [issue26160] Tutorial incorrectly claims that (explicit) relative imports don't work in the main module

Kevin Norris report at bugs.python.org
Wed Jan 20 02:02:32 EST 2016


New submission from Kevin Norris:

The tutorial contains this statement:

Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application must always use absolute imports.

See <https://docs.python.org/3/tutorial/modules.html#intra-package-references>.  The wording is slightly different in the 2.7 version of the tutorial to account for the existence of implicit relative imports, but it clearly states that explicit relative imports suffer from this limitation.

As of PEP 366, this is no longer true.  You can do (explicit) relative imports in the main module just fine (though with some minor caveats w.r.t. using the -m flag vs. specifying the .py file directly).  PEP 366 has a Python-Version of 2.6, 3.0, so every sufficiently recent version of the tutorial is wrong.

It's probably not a good idea to get too far into those caveats in the tutorial.  I'd suggest wording like this:

Note that relative imports are based on the name of the current package.  If Python is invoked with the -m switch, it can determine the package name automatically, but if it is invoked directly as ``python file.py``, relative imports will not work because Python doesn't know what package file.py belongs to.

It might be worth mentioning __package__ here, too, but we don't want to get too far down the rabbit hole of trivia (e.g. PEP 366 discusses sys.path manipulation, and for that you probably want to use __file__ instead of hard-coding the path, and then you have to talk about zipimports, and then, and then, and then...!).

(For the record, is the 2.7 tutorial still under active support?  Is it okay to report bugs in it?)

----------
assignee: docs at python
components: Documentation
messages: 258650
nosy: Kevin.Norris, docs at python
priority: normal
severity: normal
status: open
title: Tutorial incorrectly claims that (explicit) relative imports don't work in the main module
type: behavior
versions: Python 2.7, Python 3.2, Python 3.3, Python 3.4, Python 3.5, Python 3.6

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue26160>
_______________________________________


More information about the docs mailing list