DEV Community

Sergio Luiz Custodio Rezende
Sergio Luiz Custodio Rezende

Posted on

Erro ao chamar uma biblioteca

Hello

I am in a dilemma where when calling a program that uses a library that is in another directory structure.
It gives an error if I do not declare the full path of the project.
In item 2 I show the normal program, but it gives an error when executed. In item 5 I show declaring the path, and it works when executed
I will describe the entire flow:

1- directory structure:
src/conta.py
tools/calcula.py

2- in the code conta.py:
import random
from tools.calcular import Calculator #<-error if you don't declare the path

result = Calculator.sum(4,2)
print(result)
Enter fullscreen mode Exit fullscreen mode

--------------ERROR

3- in the code calcula.py
class Calculator:
def init(self):
pass

    def sum(self, a, b):
    return a + b
Enter fullscreen mode Exit fullscreen mode

4- error via vscode:
"""
PS D:\portifolio\teste2> & d:/portifolio/teste2/.venv/Scripts/python.exe d:/portifolio/teste2/src/conta.py
Traceback (most recent call last):
File "d:\portifolio\teste2\src\conta.py", line 15, in
from tools.calcular import Calculator
ModuleNotFoundError: No module named 'tools'
"""

-------------IT WORKS

5- if you put the full path it works

in the code conta.py:
import random

    #------------------if you declare the path
    import sys
    import os
    project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
    if project_root not in sys.path:
    sys.path.insert(0, project_root)
    #------------------

    from tools.calcular import Calculator <-error when running via vscode

    result = Calculator.sum(4,2)
    print(f'SUM RESULT: {result}')

    result:
    SUM RESULT: 6
Enter fullscreen mode Exit fullscreen mode

QUESTION:
Has anyone had this problem, or know how to solve it?

Top comments (1)

Collapse
 
sergio_luizcustodioreze profile image
Sergio Luiz Custodio Rezende

The problem was solved as follows:

1- change the tools directory to the same level as the .py program

from:
str/conta.py

tools/calcula.py

to:

str/conta.py

str/tools/calcula.py