-1

I had a file called mem.py in my directory and from another script I have imported:

from mem import get_val

Then I decided to move mem.py into funcs subdirectory. To make it visible to my script, from which I import, I have added into it:

import sys
sys.path.append('/home/myname/src/funcs/')

However, python cannot import mem anymore! It is interesting that it still can import other stuff from other files located in funcs.

I assume that python somehow memorises that mem.py in current directory and keep searching there and did not find it (because it is moved to funcs).

I want to __pycache__ subdirectory and found mem.pyc in there and thought that it was a problem. So, I have deleted it. However, it did not help, I still cannot import form mem.py. So, what am I doing wrong?

ADDED

I guess the problem was resolved when I have changes the order of imports. My interpretation is as follow:

  1. In my first (not working example) the first import was from mem. Python remembers that mem is in the current directory, tries to find it there, does not succeed and crashes.
  2. If I change the order of imports. Python sees a new library and starts to search it. It finds it in the 'funcs' sub-directory and creates the corresponding *.pyc file. This step kind of force Python to search other stuff (also the old one) in the funcs subdirectory.
Roman
  • 97,757
  • 149
  • 317
  • 426
  • you can use `from funcs.mem import get_val` – Matiiss Mar 31 '21 at 14:34
  • This sys path append should have worked. Please show a **reproducible** example of the problem. – wim Mar 31 '21 at 14:40
  • The order of imports is important, are you adding to the sys path after trying to import it? See also [python packages](https://docs.python.org/3/tutorial/modules.html#packages) – Sayse Mar 31 '21 at 14:46
  • No, I have imported sys before I import the other stuff. – Roman Mar 31 '21 at 14:54

1 Answers1

-1

to access files in subdirectories You can use '.'

for example:

from funcs.mem import get_val

this apparently tells python that it has to look for funcs and in there it has to look for mem. if you had multiple subdirectories You still use this same method

for example:

from funcs.sub.mem import get_val

also I think the reference directory is the one that has python dependencies like init directory

Matiiss
  • 1,793
  • 1
  • 3
  • 17