Skip to content
Advertisement

Is it possible to import a folder as a module?

I have a library I’m working on that is intended to be imported like import raycekar as rk and have its individual files referenced as rk.unit.whatever. This is the directory structure:

RayceKar
|-raycekar
| |-__init__.py
| |-ui.py
| |-env.py
`-main.py

From within main.py, if I from raycekar import ui, I can access ui. If I want to import raycekar as rk, rk.ui raises an AttributeError unless the from a import b variation is used first.

How can I make it such that accessing attributes as rk.ui or rk.env works without having to perform a from raycekar import *?

I’m working with Python 3.8+

Advertisement

Answer

What did you write in your __init__.py file? For me it worked by writing this in my __init__.py file:

from .ui import *
from .env import *

But every additional file you add the raycekar directory you will have to manually import in your __init__.py just as shown before.

I hope this helps.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement