5 ms·
Once I wrapped my head around when you can and can't use relative imports, I've been pretty ok with them. The think that irks me is whether they work changes ba
by Xavdidtheshadow 5y ago
Once I wrapped my head around when you can and can't use relative imports, I've been pretty ok with them. The think that irks me is whether they work changes based on where you've invoked Python from. `./bin/my_script.py` behaves differently from `./my_script.py`.
Coming from JS, that was a pretty frustrating realization.
- codethief 5y ago> The think that irks me is whether they work changes based on where you've invoked Python from. `./bin/my_script.py` behaves differently from `./my_script.py`. This. IMO that's also one of the main issues of Bash – you can't modularize a script unless you make sure your working directory is the directory containing the script. (And good luck with finding out the latter! [0]) [0]: https://stackoverflow.com/questions/4774054/reliable-way-for-a-bash-script-to-get-the-full-path-to-itself https://stackoverflow.com/questions/4774054/reliable-way-for...
- deleted 5y ago[deleted]
- not_skynet 5y agoI actually spent time wrestling with exactly this earlier today, and I think I finally have a 2 line solution for it: https://pastebin.com/5WCXb2Gg https://pastebin.com/5WCXb2Gg Assuming `foo.bar` is a script inside the package `foo` that you want to both import and run directly (without `python -m ...`), this lets you do so without too much hassle.
- masklinn 5y ago> The think that irks me is whether they work changes based on where you've invoked Python from. `./bin/my_script.py` behaves differently from `./my_script.py`. It does not though, unless you have altered the default sys.path to always contains `.`. When running a file / script, Python will add that file's directory as the first lookup path, so these two invocations should have the exact same sys.path, and thus the same module resolution throughout[0]. If you have added `.` to sys.path (which is not the default), then the first invocation will also have the "grand-parent" folder on the sys.path, while the second won't. This also doesn't seem to have anything to do with relative imports, you need to already be inside a package for relative imports to do anything. [0] that is not the case of `-c` and `-m`, both add CWD to the path, and they differ in what they do: `-c` adds `''` to sys.path, which is the in-process CWD. `-m` stores the actual value of CWD at invocation, so changes to CWD while the program runs don't influence module resolution