pythonimport

when i try to import module from my package i get error "AttributeError: module has no attribute"


i'm trying to make python package for TUI but when i try to import my package and use modules from it this error is occurring

Traceback (most recent call last):
  File "path to test.py", line 3, in <module>
    mypro.draw.box('+', None, None, 50, 25)
    ^^^^^^^^^
AttributeError: module 'my_project' has no attribute 'draw'

test.py looks like this

import my_project as mypro

mypro.draw.box('+', None, None, 50, 25)

im getting this error only when i directly import my package because when i try this

from my_project import draw as my_draw

my_draw.box('+', None, None, 50, 25)

now everything works fine

structure of project

my_project
│   LICENSE.txt
│   pyproject.toml
│   README.md
│   __init__.py
│
├───build
|
├───draw
│   │   shapes.py
│   │   __init__.py
│   │
│   └───__pycache__
│
├───my_project.egg-info
│
├───my_math
│   │   types.py
│   │   __init__.py
│   │
│   └───__pycache__
│
├───styling
│   │   models.py
│   │   palette.py
│   │   types.py
│   │   __init__.py
│   │
│   └───__pycache__
│
└───__pycache__

shapes.py

from ..styling import rgb, color_nameX, color_name, color_like
from sys import stdout as out

def box(fill: str, foreground: color_like | None, background: color_like | None,  width: int, height: int) -> None:

    if foreground: fore = foreground; fore.graund = "fore"
    else: fore = False

    if background: back = background; back.graund = "back"
    else: back = False

    for h in range(height):
        
        if fore: out.write(str(fore))
        if back: out.write(str(back))
        
        out.write(fill[0]*width)

        if fore: out.write("\x1b[39m")
        if back: out.write("\x1b[49m")

        out.write("\n")

Solution

  • I located the test.py code on the same level as the my_project folder. I found that in addition to the following entry suggested by @bsraskr.

    my_project/__init__.py

    from . import draw
    

    You also need:

    my_project/draw/__init__.py

    from .shapes import box