Al Sweigart
Al Sweigart

Reputation: 12969

Python 3: How do I import __init__.py from a module in its package?

I'm on Python 3.7. I created a foo module, which has the following folder layout:

foo/
    __init__.py

I put all the code for the foo package in the __init__.py file. I'm able to run import foo from other scripts as normal.

Later on, I wanted to add a util.py file to this package. The folder layout became:

foo/
    __init__.py
    util.py

My question is: Inside util.py, I'd like to access the classes, functions, etc. defined in __init__.py. How can I "import" __init__.py from the util.py file? Is this even possible? If I have to rearrange my code, then how?

I've tried to add the following to util.py:

from . import __init__
print(__init__.some_var_in_init)

But I get this error message:

Traceback (most recent call last):
  File "util.py", line 3, in <module>
    print(__init__.some_var_in_init)
AttributeError: 'method-wrapper' object has no attribute 'some_var_in_init'

So I'm guessing that's not the way to go about it.

Upvotes: 1

Views: 219

Answers (2)

Al Sweigart
Al Sweigart

Reputation: 12969

I found the answer. It isn't enough to add import foo, but the parent folder must be added as well:

import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

import foo
print(foo.some_var_in_init)

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155584

import foo will work just fine.

Upvotes: 0

Related Questions