[Tutor] Should a "data" directory have a __init__.py file?

Ben Finney ben+python at benfinney.id.au
Sun Jan 17 23:27:03 EST 2016


boB Stepp <robertvstepp at gmail.com> writes:

> I can see no reason why I would need an __init__.py file for a data
> directory. Yes, files will be read there, but there will be no code
> there. Is this correct?

That is correct. A directory of files is accessed just fine using the
normal filesystem access features.

What's more, I would say that if a directory is not positively intended
to be a Python package, that directory *should not* contain any
‘__init__.py’ file.

The module import system will only recognise a directory as a “package”
(Python's technical term for “a point in the import hierarchy which
contains other things to import”) if that directory contains a file
named ‘__init__.py’. If you do not need the directory to also be
recognised as a package, it should not have such a file.

See <URL:https://docs.python.org/3/reference/import.html#packages> for
the full details of how Python recognises and uses packages in the
import system.

Also be aware Python's use of “package” conflicts with the broader
computing use of that term (“a unit of software to install on the
operating system”); but it's too late to change either of them,
unfortunately.

-- 
 \        “The deepest sin against the human mind is to believe things |
  `\           without evidence.” —Thomas Henry Huxley, _Evolution and |
_o__)                                                    Ethics_, 1893 |
Ben Finney



More information about the Tutor mailing list