Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

4
  • 238
    What does this mean: "this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path"?
    – Carl G
    Commented Jan 25, 2014 at 4:43
  • 129
    @CarlG Python searches a list of directories to resolve names in, e.g., import statements. Because these can be any directory, and arbitrary ones can be added by the end user, the developers have to worry about directories that happen to share a name with a valid Python module, such as 'string' in the docs example. To alleviate this, it ignores directories which do not contain a file named _ _ init _ _.py (no spaces), even if it is blank. Commented Mar 7, 2014 at 20:56
  • 257
    @CarlG Try this. Make a directory called 'datetime' and in it make two blank files, the init.py file (with underscores) and datetime.py. Now open an interpreter, import sys, and issue sys.path.insert(0, '/path/to/datetime'), replacing that path with the path to whatever directory you just made. Now try something like from datetime import datetime;datetime.now(). You should get an AttributeError (because it is importing your blank file now). If you were to repeat these steps without creating the blank init file, this would not happen. That's what it's intended to prevent. Commented Mar 7, 2014 at 21:03
  • 1
    All I get is ImportError: attempted relative import with no known parent package. My structure: /PyToHtml init.py pytohtml.py test.py where test.py has: from .pytohtml import HTML Commented May 11, 2022 at 13:20