[FIXED] Importing packages in Python

Issue

I am probably missing something obvious but anyway:

When you import a package like os in Python, you can use any submodules/subpackages off the bat. For example this works:

>>> import os
>>> os.path.abspath(...)

However, I have my own package which is structured as follows:

FooPackage/
  __init__.py
  foo.py

and here the same logic does not work:

>>> import FooPackage
>>> FooPackage.foo
AttributeError: 'module' object has no attribute 'foo'

What am I doing wrong?


Solution

You need to import the submodule:

import FooPackage.foo

What you're doing is looking for foo in FooPackage/__init__.py. You could solve it by putting import FooPackage.foo as foo (or from . import foo) in FooPackage/__init__.py, then Python will be able to find foo there. But I recommend using my first suggestion.



Answered By - Rob Wouters
Answer Checked By - David Marino (Python.Easybugfix Volunteer)

Related Posts

Post a Comment