3

I have a file structure that looks like this:

Liquid
|
[Truncate]
|_General_parsing
[Truncate]
.....|_'__init__.py'
.....|_'Processer.py'
.....|'TOKENIZER.py'
|_'__init__.py'
|_'errors.py'
[Truncate]

I want to import errors.py from Processer.py. Is that possible? I tried to use this:

from ..errors import *; error_manager = errorMaster()

Which causes this:

Traceback (most recent call last):
  File "/Users/MYNAME/projects/Liquid/General_parsing/Processer.py", line 17, in <module>
    from ..errors import *; error_manager = errorMaster()
ImportError: attempted relative import with no known parent package
[Finished in 0.125s]

I've seen this post, but it's no help, even if it tries to solve the same ImportError. This isn't, either (at least not until I edited it), since I tried:

import sys
sys.path.insert(1, '../Liquid')
from errors import *; error_manager = errorMaster()

That gives


Traceback (most recent call last):
  File "/Users/MYNAME/projects/Liquid/General_parsing/Processer.py", line 19, in <module>
    from errors import *; error_manager = errorMaster()
ModuleNotFoundError: No module named 'errors'
[Finished in 0.162s]

EDIT: Nevermind! I solved it! I just need to add .. to sys.path! Or . if .. doesn't solve your problem. But if those don't solve your problem: use some pathlib (came in python3.4+) magic and do:

from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).parent))

or, if you want to use os: (gotten from this StackOverflow answer)

import os
os.path.join(os.path.dirname(__file__), '..')
theX
  • 1,008
  • 7
  • 22
  • Kind of... Now any python module or subdirectory in that directory is importable and you have to be careful what you put there. And life gets problematic if you are using source control and want to checkout multiple versions of modules. In the end, as a project grows it needs to be installable and the [disutils](https://docs.python.org/3/library/distutils.html) page is a good place to start. – tdelaney Jul 14 '20 at 01:52

1 Answers1

2

I solved it! I have to add .. to sys.path instead

theX
  • 1,008
  • 7
  • 22