Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModuleNotFoundError & ImportError on Module Import Python 3.6

I've scoured through and found lots of questions with lots of answers but nothing seems to be hitting the mark.

I've set up two files config.py and test.py under one folder called test.

config includes the code:

class Config:
    def __init__(self, name):
        self.name = name

while test has:

try:
    # Trying to find module in the parent package
    from . import config
    print(config.debug)
    del config
except ImportError:
    print('Relative import failed')

try:
    # Trying to find module on sys.path
    import config
    print(config.debug)
except ModuleNotFoundError:
    print('Absolute import failed')

This has been put together as per the answer supplier on this stack answer.

Unfortunately I'm getting both errors appearing, when I just try to directly call it from config import Config I get ModuleNotFoundError

I'm truly lost on this one and can't figure out where to go from here.

Using Python 3.6, atom.io as my IDE.

like image 690
Jake Bourne Avatar asked Apr 30 '18 12:04

Jake Bourne


1 Answers

#test.py

class Test:
    try:
        # Trying to find module in the parent package
        from . import config
        print(config.Config.debug)
        del config
    except ImportError:
        print('Relative import failed')

    try:
        # Trying to find module on sys.path
        import config
        print(config.Config.debug)
    except ModuleNotFoundError:
        print('Absolute import failed')


#config.py

class Config:
    debug = True
    def __init__(self, name):
        self.name = name

#config.py

In this file, the error was appearing because there was no variable debug = True

class Config:
    debug = True
    def __init__(self, name):
        self.name = name

#test.py

In this file, the error was appearing because you were executing the print of the import of the file and trying to access the variable in a direct way, that is, you would need 3 steps... import, class, variable >>> config.Config.debug

print(config.Config.debug)

I hope it helped you 😁😁😁

like image 73
Cristielson Silva Avatar answered Sep 17 '22 15:09

Cristielson Silva