skip to main content

@tonyfast s notebooks

site navigation
notebook summary
title
making __main__ a __package__
description
to make an interactive computing session, or a python module generally, appear like a package we need to set two varaiables.
cells
13 total
6 code
state
executed in order
kernel
Python [conda env:root] *
language
python
name
conda-root-py
lines of code
22
outputs
0
table of contents
{"kernelspec": {"display_name": "Python [conda env:root] *", "language": "python", "name": "conda-root-py"}, "language_info": {"codemirror_mode": {"name": "ipython", "version": 3}, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.13"}, "title": "making __main__ a __package__", "description": "to make an interactive computing session, or a python module generally, appear like a package we need to set two varaiables."}
notebook toolbar
Activate
cell ordering
1

making a

to make an interactive computing session, or a python module generally, appear like a package we need to set two varaiables.

2
    import pytest; from pathlib import Path
3

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.

4
    with pytest.raises(ImportError, match="attempted relative import with no known parent package"):
        from . import mkdocs
5

to be a package we need __package__ and __path__

6
    __package__, __path__ = __name__, [""]
7

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.

8
    with pytest.raises(ImportError, match="cannot import name 'mkdocs' from '__main__' \(unknown location\)"):
        from . import mkdocs
9

append the parent to the __path__

10
    __path__ += [".."]
11

and boom!

12
    from . import mkdocs#!
13

how is this different from

it is probably not much different, but more a cheat code you can abuse at your own âš