Lilla
Lilla

Reputation: 209

Importing packages in Python, attribute error

I'm new in Python and I'm trying to understand how packages and import statement work. I made this package, located in my Desktop:

package/
   __ init __.py
   module2.py
   subpackage1/
      __ init __.py
      module1.py

Here's what's inside __ init __ .py in the package folder:

__ all __ =["module2"]
import os
os.chdir("C:/Users/Leo--/Desktop/Package")
import subpackage1.module1
os.chdir("C:/Users/Leo--/Desktop")

and inside __ init __ .py in subpackage1 folder:

__ all __ =["module1"]

I want to import module1.py and module2.py by only writing

import package

After typing the command above into the interpreter I can access with no problems any function of module1.py by writing

package.subpackage1.module1.mod1()

where mod1() is a function defined in module1.py. But when I type

package.module2.mod2()

I get "AttributeError: module 'package' has no attribute 'module2'" (mod2() is a function defined in module2.py). Why is that? Thank you in advance!

Upvotes: 3

Views: 6692

Answers (1)

Shreyash S Sarnayak
Shreyash S Sarnayak

Reputation: 2335

You get the AttributeError because you haven't imported the module2 in __init__.py file.

You shouldn't do os.chdir() in __init__.py to import submodules.

This is how I would do it:

__ init __.py in the package directory.

from . import module2
from . import subpackage

__ init __.py in the subpackage1 directory.

from . import module1

Upvotes: 3

Related Questions