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

5
  • 1
    change __init__.py to be from utils import show Commented Jan 28, 2015 at 21:51
  • @reptilicus Don't you mean from .utils (with the . relative import syntax) ? Commented Jan 28, 2015 at 21:56
  • Thanks for quick respnse, but it didn't change much. Now the PyCharm IDE is complaining about unresolved reference to 'utils' and the error remains. Commented Jan 28, 2015 at 22:09
  • @MaxPasek Can you provide the full Traceback? Commented Jan 28, 2015 at 22:10
  • The traceback was supposed to be here but I already found the answer. Thanks once again :) Commented Jan 28, 2015 at 22:33

3 Answers 3

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 
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

__init__.py

import utils show = utils.show 

main.py

from sources import show show() 

Comments

0

As seen in comments....

Change __init__.py to be

from utils import show 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.