3

If I want to check whether a directory is a python package, is it enough to check whether a directory contains a __init__.py file?

Aaron de Windt
  • 16,794
  • 13
  • 47
  • 62
  • @vaultah Really? The `__init__.py` is no longer required? – Roy Prins Aug 16 '17 at 21:55
  • Is there any reason you could not do the "ask forgiveness not permission" thing here? So you would go `try: from foo import bar` and `except: ...` – Roy Prins Aug 16 '17 at 21:58
  • @RoyPrins I'm writing a command line tool to treats a directory as a project for my tool and I need to find the directories in there that python packages, so my tool know which packages it can use. Trying to import every directory seemed a bit unsafe since I could accidentally import a package with the same name as a non-package directory. – Aaron de Windt Aug 16 '17 at 22:04
  • I'm adding the project root directory at the front of sys.path – Aaron de Windt Aug 16 '17 at 22:06

2 Answers2

4

Before Python 3.3, only directories containing __init__.py files were considered packages (see regular package in Glossary).

Since the addition of namespace packages in Python 3.3, every directory is a Python package, technically.

vaultah
  • 44,105
  • 12
  • 114
  • 143
1

Based on the documentation:

The __init__.py files are required to make Python treat the directories as containing packages

Update

Based on the answer here: Is __init__.py not required for packages in Python 3? You can see that it's no longer a requirement.

Dekel
  • 60,707
  • 10
  • 101
  • 129