0

I have a project that I imported. It has structure of:

my_package
|
 _ my_package
    | _
        operators
        |_
          myoperator.py (that contains MyOperator class)
 

imports in code of that project are shown as:

from my_package.operators.myoperator import MyOperator

However for some reason that I don't understand none of the imports are working for me. In order to make them work I need to add my_package as:

from my_package.my_package.operators.myoperator import MyOperator

This is something that I probably didn't configure correctly. How can I make the virtual env recognise the imports as they are? This is probably something with search paths of the virtual environment?

Slava
  • 325
  • 5
  • 13
  • You have too look the rules of [6.1.2. The Module Search Path](https://docs.python.org/3/tutorial/modules.html#the-module-search-path). The reason for this is only the directory that contains the outermost `my_package` is on your PYTHONPATH. The normal solution for this is writing you package [as being installable](https://stackoverflow.com/q/62498127) in which case you would install it having the innermost `my_package` as base. – bad_coder Jul 29 '21 at 10:28
  • Using only the PyCharm interface you could mark the directory that has the outermost `my_package` as a [sources root](https://www.jetbrains.com/help/pycharm/configuring-project-structure.html) also [see this post](https://stackoverflow.com/a/56738029) for an explanation. However the usual logic is putting what is in fact a package on PYTHONPATH and using the fully qualified name in the imports. – bad_coder Jul 29 '21 at 10:34
  • @bad_coder yes! the thing is that I have my_package, my_package2, my_package3 where each one of them is a standalone package. can I do the mark as source root for all of them? – Slava Jul 29 '21 at 11:13
  • Well, one option is using the IDE to mark each directory that contains each package as sources root. Then you have several options to [populate the `sys.path`](https://stackoverflow.com/a/38403654). What is more appropriate depends on what you are developing, but check the 2nd link in my 1st comment, frequently developing your packages as installable is the way to go - in this case using the distutils `package_dir={'': 'src'},` and `packages=find_packages(where='src')` is one option. You may want to run install/uninstall separately for each package. – bad_coder Jul 29 '21 at 11:28

0 Answers0