[Python] Is there a better way of making Python aware of module sources?

Discussão em 'Python' iniciado por Stack, Fevereiro 22, 2025.

  1. Stack

    Stack Membro Participativo

    I have a Python package that is supposed to be used interactively, mostly from a debugger. (It is indented for the classroom, and the students are expected to poke around.)

    https://github.com/PetrKryslUCSD/pystran

    When the package tutorials are loaded into the Spyder IDE, the current folder is set to the folder in which the tutorial lives. On the other hand, when the tutorial is run from a command line using py, it is typically from the top folder of the package.

    Consequently, I use a "context.py" file stored in the tutorials folder that inserts a couple of paths.

    import os
    import sys
    sys.path.insert(0, os.path.abspath("."))
    sys.path.insert(0, os.path.abspath(".."))


    and each tutorial includes import context.

    This device modifies the path for the running python so that it sees the source files of the package.

    Disconcertingly, it feels hacky, and I'm wondering if there is a better way?

    The trick with the "context" file works. However, it feels ad hoc, and the question is: is there a more pythonic way of doing this?

    Continue reading...

Compartilhe esta Página