Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
submodule import problem
#1
I am having a problem with modules and packages. I can make my imports work outside the package or I can make them work inside the package. I have not figured out a way to make them work in both scopes and I assume this is because I am still rather ignorant about Python.

This demonstrates the problem. I have a program that uses a package:

program.py
import package.b as b
print(b.average(2, 4))
Inside the package I have two modules: a and b.
a.py
def sum(x, y):
    return x + y
b.py
import a
def average(x, y):
    return a.sum(x, y) / 2
The directory structure is:

Output:
program.py package\ __init__.py <-- Empty a.py b.py
If I run b.py there are no errors. When I run program.py I get the message
File "...\b.py" line 1 in <module>
Module Not Found: No Module named a

I changed module b to use a relative reference:
b.py
from . import a
def average(x, y):
    return a.sum(x, y) / 2
If I run program.py there are no errors. When I run b.py I get the message
Error:
File "....\b.py" line 1 in <module> from . import a ImportError: attempted relative import with no known parent package
I have read dozens of tutorials on how to make a package. I have read dozens of articles about import and __init__.py and PYTHONPATH and setup.py and every topic that looks like it may point toward and answer. I fear I am missing some vital piece Python understanding and this is so trivial that nobody talks about it.
Reply


Messages In This Thread
submodule import problem - by deanhystad - Feb-29-2020, 09:32 PM
RE: submodule import problem - by Gribouillis - Mar-01-2020, 07:10 AM
RE: submodule import problem - by snippsat - Mar-01-2020, 11:22 AM
RE: submodule import problem - by deanhystad - Mar-01-2020, 01:52 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  problem in import module from other folder akbarza 5 1,524 Sep-01-2023, 07:48 AM
Last Post: Gribouillis
  [WORKED AROUND] Problem installing elitech-datareader, 'cannot import build_py_2to3' NeilUK 4 1,776 Jul-09-2023, 10:01 AM
Last Post: NeilUK
  Import requests/beautifulsoup problem Jokadaro_ 3 2,084 Dec-05-2021, 01:22 PM
Last Post: Jokadaro_
  Problem with Flask Bcrypt import module marcello86 2 5,801 Aug-31-2020, 08:10 PM
Last Post: marcello86
  problem with mapnik in anaconda python 2: from _mapnik import * ImportError: DLL load parsley 0 1,924 Dec-11-2019, 07:50 AM
Last Post: parsley
  File Import Problem St_Patrick 8 4,373 Aug-04-2018, 02:29 PM
Last Post: St_Patrick
  Python3: problem to import personals modules PyForIO 2 3,529 Mar-04-2018, 12:42 PM
Last Post: PyForIO

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020