简体   繁体   中英

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.

import foo可以正常工作。

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM