-3

I am working in python3 for a year now and I still don't get the import system....
I always put the empty init.py file on each folder.

But however if my project start to have nested directories (and it append a lot and often) I have to run a war to be able to import my own module (who python thinks he is ????)... It is driving me crazy.

So for now the 'best' trick I have found, but clearly I am not satisfied with it is to put ligne like this on top of my file:

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(file))))

I do not like it, first because when the directory is nested on several level the line is extraordinary long, then because my linter is always yelling at me because my import are not on top of my files.

So I was wondering, what am I missing ? Is there an information I missed ? What's your technique ?

Thank you !


Can't import my own modules in Python Someone suggested it's similar to this answer but it is not. First I do not want to use relative import.
Then the 'sys.path.append("..")' is not clean in my opinion, and my imports are still not on top of my files.

Basically let's say I have a structure like:

folder_a
----file_1
----file2
----folder_b
--------file_3
--------folder_c
-----------file_4

I am instanciating a class from file_1 in file_3,I have to do this:

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(file)))))
from folder_a.file_1 import class_1

doing this obviously won't work:

sys.path.append("..")
from folder_a.file_1 import class_1

This is so not logic for me

Kimor
  • 532
  • 4
  • 17
  • Does this answer your question? [Can't import my own modules in Python](https://stackoverflow.com/questions/9383014/cant-import-my-own-modules-in-python) – funie200 Oct 15 '20 at 08:32
  • I do not want to do relative import, and adding 'sys.path.append("..")' at the top of my file seems to be a patch to me too.. Isn't there a good way to use python that I missed ? – Kimor Oct 15 '20 at 08:35
  • 1
    @Kimor please take this advice: use explicit relative imports. Within a package that’s exactly what you need to be using. The advice you read is almost certainly about relative imports **in Python 2**, which were not explicit and created ambiguity between top-level names and nested names. Python 3 doesn’t have those problems. – Martijn Pieters Oct 15 '20 at 10:03

1 Answers1

1

If you don't want to use relative imports, and you don't want to mess with sys.path, the other option is to package your modules and install them using pip install.

I think that reading the import documentation instead of just trying to "make it work" will be beneficial. Python's documentation is really good. Focus for a while with a good cup of tea and read it :)

Shay Nehmad
  • 1,103
  • 1
  • 12
  • 25