summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authoralex <alex@pdp7.net>2023-09-11 22:04:23 +0200
committeralex <alex@pdp7.net>2023-09-11 22:04:23 +0200
commit52caef286f01456232d21e3b8a68b9a49d239f1b (patch)
tree7c57b887626d081789c408d15e294b06f0ebe890
parent7e3e7adc6c1806cbca81ae319a53cd12fe96a5e8 (diff)
Add information about sys.path including the current directory
-rw-r--r--programming/python/python_modules_primer.md33
1 files changed, 33 insertions, 0 deletions
diff --git a/programming/python/python_modules_primer.md b/programming/python/python_modules_primer.md
index c42f2a31..365f05a2 100644
--- a/programming/python/python_modules_primer.md
+++ b/programming/python/python_modules_primer.md
@@ -124,3 +124,36 @@ __all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo",
```
`/usr/lib64/python3.9` contains the modules in [the Python standard library](https://docs.python.org/3/library/).
+
+### Importing your Python files
+
+If you create a file with the `a.py` name:
+
+```
+def f():
+ return 2
+```
+
+, and another with the `b.py` name:
+
+```
+import a
+
+print(a.f())
+```
+
+, then:
+
+```
+$ python b.py
+2
+```
+
+
+This works, because `sys.path` contains `''`, which means "the current directory".
+
+(`sys.path` is very similar to the `PATH` variable. However, `sys.path` contains the current directory by default, whereas `PATH` does not.)
+
+When `import a` is executed, then Python searches the directories in `sys.path` for an `a.py` file; it is found when checking the `''` path.
+When `import datetime` is executed, Python searches in the current directory (because `''` comes first in the path), doesn't find it, but then finds it in the following `/usr/lib64/python3.9` directory.
+Python iterates over the `sys.path` directories, and loads the *first* matching file.