cha cha - 1 year ago 76
Python Question

Purpose of some boilerplate code in

I've seen the following code in a couple Python projects, in
. Could someone explain the purpose? Of course it puts the directory containing
at the head of
, but why? And why the tests (
__package__ is None and not hasattr(sys, 'frozen')
? Also, in the
, why is
called twice?

import sys

if __package__ is None and not hasattr(sys, 'frozen'):
# direct call of
import os.path
path = os.path.realpath(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(os.path.dirname(path)))

Answer Source

The test for __package__ lets the code run when package/ has been run with a command like python or python package/ (naming the file directly or naming the package folder's path), not the more normal way of running the main module of a package python -m package. The other check (for sys.frozen) tests if the package has been packed up with something like py2exe into a single file, rather than being in a normal file system.

What the code does is put the parent folder of the package into sys.path. That is, if is located at /some/path/to/package/, the code will put /some/path/to in sys.path. Each call to dirname strips off one item off the right side of the path ("/some/path/to/package/" => "/some/path/to/package" => "/some/path/to").