0

I would like to import modules from another folder and test them. My directory looks like this:

- relative_imports:
    - folder1:
        - file1.py
            - class one_1(): ...
            - class one_2(): ...
        - file2.py
            - class two_1(): ...
            - class two_2(): ...
    - folder2:
        - file3.py

In file3.py I would like to import classes: one_1, one_2, two_1, two_2. From file1.py and file2.py. I want to be able to access and test these classes.

I would not like to use the sys path method, but I would rather work with relative paths from the point of view of file3.py.

I have tried several variations of the following code with no success.

from relative_imports.folder1.file1 import one_1

val = one_1()

I have also tried using __init__.py files but I seem to have not found the correct method of importing the modules.

ignacio
  • 1,181
  • 2
  • 15
  • 28
H1 Jacobs
  • 1
  • 2
  • 1
    Does this answer your question? [How to do relative imports in Python?](https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python) – Daniel F Jul 15 '22 at 15:08
  • make sure each subdirectory has a `__init__.py` file – drum Jul 15 '22 at 15:08

1 Answers1

0

If I have understood your question properly, you want to access classes from a module present in a different folder.

You can do this easily by aliasing.

scenario: You want to access a class from file1.py in folder1 and use that data inside folder2 file3.py

file1.py

class ADDITION():
  def __init__(self):
      pass
  
  def addTwoNumbers(self,number1, number2):
      return numner1 + number2

global addition
addition = ADDITION()

No, If you would like to import the ADDITION class into file3.py

file3.py

from file1 import addition

if __name__ == '__main__':
  print(addition.addTwoNumbers(10,20))

Pramodh
  • 35
  • 5