title: How can I set __package__ of a script from within an imported library?
body: <p>The <code>__package__</code> attribute can be set to allow directly executing a python script that is also part of a module (e.g. uses relative imports). Without <code>__package__</code>, one can only run it as <code>python3 -m parent.child.script</code> but with <code>__package__ = 'child'</code>, one can also run more easily as <code>python3 script.py</code>.</p>
  <p>From <a href="https://www.python.org/dev/peps/pep-0366/" rel="nofollow noreferrer">PEP 366</a>:</p>
  <blockquote>
  <p>When the main module is specified by its filename, then the <strong>package</strong> attribute will be set to None. To allow relative imports when the module is executed directly, boilerplate similar to the following would be needed before the first relative import statement:</p>
  <pre><code>if __name__ == &quot;__main__&quot; and __package__ is None:
      __package__ = &quot;expected.package.name&quot;
  </code></pre>
  <p>Note that this boilerplate is sufficient only if the top level package is already accessible via sys.path. Additional code that manipulates sys.path would be needed in order for direct execution to work without the top level package already being importable.</p>
  </blockquote>
  <p>I'm trying to move this boilerplate into a library that each script can import. I already have code available to import the package, resulting in this boilerplate snippet:</p>
  <pre class="lang-py prettyprint-override"><code>import pathlib, imptools
  if __name__ == '__main__' and __package__ == None:
    __package__ = pathlib.Path(__file__).parent.name
    imptools.import_from_path(__package__, '..')
  </code></pre>
  <p>Now I would like to simplify this to the following, which requires setting <code>__package__</code> for the script from within the library rather than the script itself.</p>
  <pre class="lang-py prettyprint-override"><code>import relative_import
  relative_import.enable()
  </code></pre>
  <p>I know how to find out what script file the library function is called from. This can be done via <code>inspect</code>:</p>
  <pre class="lang-py prettyprint-override"><code>import inspect
  for info in inspect.stack():
    if info.filename == __file__:
      continue
    break
  script = info.filename
  </code></pre>
  <p>The only problem left is, how can I set <code>__package__</code> of the script module from within the library?</p>