making __main__
a __package__
¤
to make an interactive computing session, or a python module generally, appear like a package we need to set two varaiables.
import pytest; from pathlib import Path
there is a python file one directory up called mkdocs.py
.
we should be able to get at this file, and we will.
our first transgression is not being a package.
with pytest.raises(ImportError, match="attempted relative import with no known parent package"):
from . import mkdocs
to be a package we need __package__
and __path__
__package__, __path__ = __name__, [""]
the __path__
contains the lookup directories for parts of the package;
this is a feature of namespace packages AND where shit gets weird.
now that we quack like a package we can attempt relative imports,
but mkdocs.py
is still out of reach.
with pytest.raises(ImportError, match="cannot import name 'mkdocs' from '__main__' \(unknown location\)"):
from . import mkdocs
append the parent to the __path__
__path__ += [".."]
and boom!
from . import mkdocs#!
how is this different from sys.paths
¤
it is probably not much different, but more a cheat code you can abuse at your own ⚠