3 ms·
What’s still annoying to this day is Python imports. I have been doing Python for a while now and I still get tripped up when some bit of code in a folder isn’t
by gigatexal 5y ago
What’s still annoying to this day is Python imports. I have been doing Python for a while now and I still get tripped up when some bit of code in a folder isn’t importable. I’ve found adding the package dir that I’m working on to PYTHON_PATH works but then my editor doesn’t resolve packages for autocomplete.
- georgyo 5y agoIf you have foo.py and bar.py in a directory and you want to import foo.py from bar.py you only need to add an empty __init__.py You would then `import .foo`
- terom 5y agohttps://www.python.org/dev/peps/pep-0420/ https://www.python.org/dev/peps/pep-0420/ Python 3.3+ no longer requires the `__init__.py` file to make a package. > You would then `import .foo` The `import .foo` is a syntax error, and `from . import foo` does not work for scripts [1]. The basic `import foo` works if the directory is on your PYTHONPATH. That will be the case if you run `bar.py` as a script. It gets more difficult if you want to separate scripts and importable modules into separate sibling directories (bin vs lib). You can't use relative imports to get around that, you need to use a virtualenv (or manual PYTHONPATH wrangling). [1] https://stackoverflow.com/a/14132912 https://stackoverflow.com/a/14132912
- BiteCode_dev 5y agoUse virtualenvs, that's the problem they solve. Python now ships with the venv cli tool. If you point your editor to the python interpreter in the venv, it will detect everything automatically.
- icegreentea2 5y agoAs sibling says, you really should use virtualenvs. But if you're not and you're using vscode, this is the relevant thingy to do to get vscode to play nice: https://code.visualstudio.com/docs/python/environments#_use-of-the-pythonpath-variable https://code.visualstudio.com/docs/python/environments#_use-...