TomSawyer
TomSawyer

Reputation: 3820

How to import a folder with absolute path as package?

The path is app/base/admin/crud/__init__.py.

I want to import an entire folder as a package like this:

import app.base.admin.crud as cx

But it doesn't work and gives this error:

AttributeError: module 'app.base' has no attribute 'admin'

But when I import it's function like this from app.base.admin.crud import crud, it works.

What's going on here?

Upvotes: 0

Views: 248

Answers (1)

David M.
David M.

Reputation: 2640

See the documentation about packages.

More specifically that part:

[...] when using syntax like import item.subitem.subsubitem, each item except for the last must be a package; the last item can be a module or a package but can’t be a class or function or variable defined in the previous item.

When using the import x.y.z statement alone (without from), you're actually importing a package for usage in your code as x.y.z.something(). Each part of that path must be a proper package (in other words, contain a __init__.py file)

Upvotes: 1

Related Questions