0

Getting the file system path of a python module by module name is easy if the module exists. For example like this:

importlib.machinery.PathFinder.find_module('my.module').path

But when the module does not exist, how can I still get the theoretical path that would be used to check whether the module exists?

Background: I want to watch the file system to be notified when a module (specified by module name like in an import statement) comes into existence.

saluto
  • 77
  • 7
  • Does this answer your question? [Where are the python modules stored?](https://stackoverflow.com/questions/2927993/where-are-the-python-modules-stored) – wjandrea Dec 13 '20 at 21:22

1 Answers1

1

Python uses it's own path variable to know where to look for modules. The path variable is a list containing all the directories where python looks for modules, going from start to finish. To get a look at it, you can use the sys module:

import sys

print(sys.path)

The first item in the list is the directory of the script, unless you're in an interactive session, in which case an empty string will be present, representing the current working directory.

tralph3
  • 452
  • 4
  • 13
  • 1
    The empty string actually means the working directory. From the [docs](https://docs.python.org/3/library/sys.html#sys.path): *"As initialized upon program startup, the first item of this list, `path[0]`, is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available, `path[0]` is the empty string, which directs Python to search modules in the **current directory** first."* (added bold) – wjandrea Dec 13 '20 at 21:24
  • Well that's what I wanted to say. Thanks for clarifying it tho, I'll edit the answer. – tralph3 Dec 13 '20 at 21:26
  • Oh, that's still not quite right. Python will try to add "the directory containing the script", but if it can't, like in an interactive session, *then* it'll add the empty string. – wjandrea Dec 13 '20 at 21:29
  • Thanks. So, do I have to watch all the paths in `sys.path` for changes recursively? Maybe the paths could be made a bit more specific by appending to each of them the module name where the dots are replaced by `/`. Could that work? Is there a better way, maybe using an existing function from Python standard library? I want as little file watchers as possible, because of OS and memory limitations. – saluto Dec 14 '20 at 17:59