1

I have a script that have multiple files and a config file with all the variables store in one Python file.

Folder structure:

Folder structure

Config file:

Config file

If I try to run the main file which calls the head function imported, an error pops up saying that the config cannot be imported.

Imports:

Imports image

karel
  • 5,489
  • 46
  • 45
  • 50
Jorge Creus
  • 17
  • 1
  • 4
  • Please clarify: How do you run the main file? Which file is the head function in? Is there any detailed warning about the "cannot be imported" error? – Dummmy Aug 31 '21 at 10:09
  • I´m running the main file and this error pops up import * only allowed at module level – Jorge Creus Aug 31 '21 at 10:12
  • It appears that `import *` inside a function is prohibited intendedly. Please check https://stackoverflow.com/questions/3571514/python-why-should-from-module-import-be-prohibited. – Dummmy Aug 31 '21 at 10:14

2 Answers2

1

Your Functions folder has a __init__.py file. If your app executes from Main.py (ie if Main.py satisfies __name__ == "__main__") therefore wherever you are in your app you could import the config like this:

from Functions.Config import *

Edit:

However,from module import * is not recommended with local import. You could give an alias to the import and call name.variable instead of calling name directly. Example:

def head():
    # import packages
    import Function.Config as conf
    print(conf.more_200)
head()
>>> 50
0

Your syntax are wrong.

It is supposed to be from Config import * and not import .Config import *

pxDav
  • 1,498
  • 9
  • 18
  • HEllo, This error poop up import * only allowed at module level – Jorge Creus Aug 31 '21 at 10:09
  • That is because you put all of the imports in a function, which triggers a `SyntaxWarning` warning. To prevent this, put all of your imports on the top of your python file instead of in a function. – pxDav Aug 31 '21 at 10:14
  • Both two codes can be valid syntactically. It just depends on whether it is inside a package to use relative imports or not. For ref: https://realpython.com/absolute-vs-relative-python-imports/#relative-imports. – Dummmy Aug 31 '21 at 10:16
  • But if you do not want to do that, it's fine. Warning doesn't stop the program from executing. – pxDav Aug 31 '21 at 10:16