Error in relative python import

Asked

Viewed 399 times

1

I’m looking to test simple python code using pytest. My hierarchy is as follows::

PythonExamples
    files
        mymath.py
    tests
        test_mymath.py

in test_mymath.py, I import mymath as

from ..files import mymath as mm
def test_mysum():
    assert mm.mysum(2,3) == 5

In the Pythonexamples folder I run the py.test tests command, but I get the following message:

Parent module '' not Loaded, cannot perform relative import

What can it be?

  • 1

    try: from ..files.mymath import mysum, in the case of mysum would be the def which is created within the mymath.py

1 answer

1

Try: from ..files.mymath import mysum

In the case of mysum would be the def which is created within the mymath.py

for example in a structure:

mypackage/
    __init__.py
    mymodule.py
    myothermodule.py

the mymodule.py

#!/usr/bin/env python3

# Exported function
def as_int(a):
    return int(a)

# Test function for module  
def _test():
    assert as_int('1') == 1

if __name__ == '__main__':
    _test()

the myothermodule.py

#!/usr/bin/env python3

from .mymodule import as_int

# Exported function
def add(a, b):
    return as_int(a) + as_int(b)

# Test function for module  
def _test():
    assert add('1', '1') == 2

if __name__ == '__main__':
    _test()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.