1

I found a couple of different answers and related questions here already but still I can't figure out what I am doing wrong.

I have a python app with layout like this:

main.py
sources/
    __init__.py
    utils.py

My __init__.py contains:

from sources.utils import show

where show is a function defined in utils

I want to be able to write in main.py:

from sources import show
show()

but instead I get an error ImportError: cannot import name 'show'

Any help will be greatly appreciated


EDIT:

Seems that the problem is caused by the PyCharm IDE I'm using. The same code being run in python directly from linux console works like charm.

Sorry for bothering you guys and thank you for help.

Best Regards, Max

Community
  • 1
  • 1
Max Pasek
  • 13
  • 4

3 Answers3

1

To quote the official recommendations:

Python 2.x, imports are implicitly relative. For instance, if you're editing the file foo/__init__.py and want to import the module at foo/bar.py, you could use import bar.

In Python 3.0, this won't work, as all imports will be absolute by default. You should instead use from foo import bar; if you want to import a specific function or variable from bar, you can use relative imports, such as from .bar import myfunction)

Either use absolute import in __init__.py (from sources.util import show) -- or explicit relative import (from .util import show).

Given this setup:

sh$ cat sources/utils.py 
def show():
    print("show")

sh$ cat sources/__init__.py 
from sources.utils import show
# could be
# from .utils import show

sh$ cat main.py 
from sources import show

show()

It will work as expected both in Python 2 & 3:

sh$ python2 main.py 
show
sh$ python3 main.py 
show
Community
  • 1
  • 1
Sylvain Leroux
  • 50,096
  • 7
  • 103
  • 125
0

Try this:

__init__.py

import utils
show = utils.show

main.py

from sources import show
show()
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
0

As seen in comments....

Change __init__.py to be

from utils import show
reptilicus
  • 10,290
  • 6
  • 55
  • 79