-2

I somehow struggle with a seemingly really simple problem regarding importing a class from a module. I have the following file-structure:

program.py
package/
    __init__.py
    someClass.py
    module.py

Those are the contents of each file:

###program.py###
from package import SomeClass
c=SomeClass()
print(c.a)
_________________
###package/__init__.py###
from .someClass import SomeClass
__________________
###package/someClass.py###
import module as m
class SomeClass:
    def __init__(self):
        self.a=m.add(1,1)
_______________
###package/module.py###
def add(a,b):
    return(a+b)

Running this code gives me the error ModuleNotFoundError: No module named 'module' at the line import module as m. I know, that I probably need some kind of dot notation at some point. But I cannot figure out, where and how. Thanks for the help.

Simon

  • Does `import .module as m` work? [this question](https://stackoverflow.com/questions/7279810/what-does-a-in-an-import-statement-in-python-mean) might help. – bc1155 May 10 '23 at 08:17
  • No, `import .module as m` gives me a `SyntaxError: invalid syntax` – Simon Schey May 10 '23 at 08:21
  • Have you packaged and *installed* this? Why do you expect `import module` to work? Do you understand how Python will look for package namaes? If you haven't done any actual packaging and installation, then you are relying on your working directory being added to the search path. Presumably, your working directory is the same directory as `program.py`, so that means, you'd need `import package.module`. Also, generally it is better to avoid relative imports. So you'd need `import package.someClass` etc. – juanpa.arrivillaga May 10 '23 at 08:38
  • 1
    I think I found the solution after the 100th try... `from . import module as m` seems to work. @juanpa.arrivillaga, of course, if I want to actually use the package in multiple programs, I will need to place it somewhere, where python will find it. – Simon Schey May 10 '23 at 08:47
  • Apologies, my previous answer was wrong. Try `from . import module as m` – bc1155 May 10 '23 at 08:55

1 Answers1

0

from . import module as m seems to answer my question

  • It is crucial to understand this will only work (or equivalently, `import package.module` ) if the directory `package` is in is in the module search path. Presumably, in your case, it is because the working directory from which you invoked Python was that directory (which gets added to the module search path automatically). But if you tried to run the Python script from another directory, it wouldn't work – juanpa.arrivillaga May 10 '23 at 09:13
  • And I point this out because your initial imports seem to suggest that you assumed that the search path would involve *the directories that contain the source code*, but that isn't how it works, although it is a common misapprehension. – juanpa.arrivillaga May 10 '23 at 09:15