0

I have a Python module called util. I would like to import a script in this package _util.py from another script in scripts folder.

Even if the util package has an empty __init__.py file it does not appear as a Python package but a normal directory, without the small dot on folder image.

code structure

How can I import this module?

Zach Valenta
  • 1,783
  • 1
  • 20
  • 35
Ahmet Tuğrul Bayrak
  • 3,466
  • 2
  • 15
  • 27
  • ideally it should be ``` from util import _util ``` – Chathuranga Dec 06 '18 at 07:35
  • How are you trying to import it? Is there any class inside _util.py? – Josef Ginerman Dec 06 '18 at 07:38
  • there is no class in _util.py. I am trying to import it as "from util import _util" in scripts folder – Ahmet Tuğrul Bayrak Dec 06 '18 at 07:42
  • First, does `import util` work from you current script? If it does not that means that the folder containing util is not is `sys.path`. – Serge Ballesta Dec 06 '18 at 07:44
  • This sounds like https://stackoverflow.com/questions/4542352/import-from-sibling-directory ... unless your issue is the IDE not detecting that `util` is a package even after adding `__init__.py` – iamanigeeit Dec 06 '18 at 07:52
  • I guess the problem is the package is not detected as a package, because I get the following error when I try the suggested solution "ValueError: Attempted relative import in non-package" – Ahmet Tuğrul Bayrak Dec 06 '18 at 08:18
  • Can you add what version of Python you're using to your question? Additionally, please add how you're importing the module to the question; I see you've answered in a comment, but adding to the question will allow for greater visibility to other users who might not read the comments. – Zach Valenta Jan 08 '19 at 18:08

1 Answers1

0

A preliminary answer to your question is that modules or methods beginning with underscores are meant to be used internally.

  • _my_method() should only be referenced from within the module holding it
  • _my_module() should only be referenced from within the package holding it

That being said, this convention is meant to be a hint to other developers, not a strict prohibition. Perhaps the first step you can take to solve the import issue is to rename _util.py to util.py and proceed from there.

Zach Valenta
  • 1,783
  • 1
  • 20
  • 35