I'd like to understand if there's better solution .
for following tree:
|-main.py
├── app_config
│ ├── db_config.py
| |--- settings.py
Main.py importing class from db_config
from app_config.db_config import DBContext
So in db_config.py each import of other class would be in the context/position of main
meaning
from app_config.settings import SingletonMeta
This obviously works but during development sometimes need to test db_config.py itself
and each time need to change import of settings.py
from settings import SingletonMeta
I wonder if there's more efficient way
You can add the following code in your db_config.py script:
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from app_config.settings import <package>
This way, you add the parent directory of db_config.py to sys and this will alows you to import packages inside your script as from app_config.settings import <any package under app_config > and also in main.py
Related
I'm trying to import the db module from the __init__ file, after comand from . import db, gets attempted relative import with no known parent package
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
My catalog structure:
Procjet
├── __init__.py
├── auth.py
└── templates
i tried it:
from . import db
from .. import db
from project import db
from .project import db
and always i gets attempted relative import with no known parent package
Opening the project folder directly in an IDE should fix the issue.
You could check if the correct path is in sys.path in debug mode for example.
You could try my new import library: ultraimport
It gives the programmer more control over their imports and lets you do file system based relative and absolute imports.
To import the db object relatively, your auth.py could look like this:
import ultraimport
db = ultraimport('__dir__/__init__.py', 'db')
This will always work, no matter how you run your program and independent of your sys.path.
I want to have project structure as you can see below:
some API module, which i use to make some tools.
├── api
│ ├── __init__.py
│ ├── some_script.py
├── tools
│ └── tool1.py
api/some_script.py
def func():
print("Func1")
class some_object():
...
api/__init__.py
from .some_script import some_object, func
Where in tool1.py is
from ..api import func
I want that tools in folder, but I keep getting import error. To this point I had tool1.py in no folder and it worked fine (but with code
from api import func)
ImportError: attempted relative import with no known parent package
How to make it work this way?
Thanks for answers
I tried your code and got the same error, turns out you need to help the import using sys here is how to do it:
import sys
sys.path.append("..")
from api import some_script
#basic beatle
helped me solve it. With some other sources and this one works:
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
Python project structure:
src/
- package-name/
-- A/
---B/
b1.py
---C/
c1.py
In c1.py, it uses a function defined in b1.py. I try 2 ways:
Method1: from src.package-name.A.B.b1 import b1_func
Method2: from ..B.b1 import b1_func
The import module starts from package-name directory, so src/ will not be visible in the imported module. So Method1 not working when import my own module.
Method2 is not working when run in IDE. ValueError: attempted relative import beyond top-level package
Any suggestions? thanks.
Do you have __init__.py files in A and B? It may be worthwhile to properly import b1_func into B's and then A's init files.
B __init__.py
from .b1_file import b1_func
or whatever
and A __init__.py
from B import b1_func
Then you should be able to import ..b1_func
I change the "Content Root" to the package-name directory in PyCharm and import package-name.B.b1. It works.
follow these steps to import the packages wherever u want
First of all, add __init__.py in all folders
i.e: __init__.py in src and __init__.py in package and __init__.py in A
and __init__.py in B and __init__.py in C.
If u want to import the functions from b1.py in c1.py add these lines in c1.py file.
import sys
sys.path.append(“../”)
#if u want from src folder add ../../
from B.b1 import YourFunctionName
I have a Django project (Python 2.7.15) with the following structure:
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
utils.py
utils/
__init__.py
filters.py
In my utils/filters.py file I have a class MyFilter. From polls/admin.py, however, when I try to run from utils.filters import MyFilter, I get ImportError: No module named filters. How can I import my custom filter inside the polls app without renaming the polls/utils.py module or the utils package?
NOTE: This it's not a circular import problem. This happens even if I don't import anything from utils/filters.py. It's a name conflict between utils/ and polls/utils.py. Python tries to find filters.MyFilter inside polls/utils.py and it doesn't find it so it throws the error. I just want to figure out a way to bypass this conflict and force python to look for filters.MyFilter inside the utils/ package in the project root.
In Python 2, import utils is ambiguous because it can be a relative or an absolute import.
If you enable the Python 3 behaviour by adding the following import to the top of your module,
from __future__ import absolute_import
then from utils.filters import MyFilter will be treated as an absolute import and will work.
Once you have added the future import, you would need to use an explicit relative import import .utils if you wanted to import polls/utils.py from polls/admin.py.
Edit: __init__.py files are included, but I'm using Python 3 - I don't think it matters.
Another edit: Anything in config.py will import with no problem. If I simply omit from cache import Cache then no errors. Interestingly, no errors occur when importing Config in config.py
I cannot figure out what's wrong here. I'm getting an error whenever I try to import a specific class. Here's what my project layout looks like:
app/
dir1/
config.py
cache.py
manager.py
__init__.py
test/
test.py
__init__.py
cache.py:
import sys
import os
sys.path.append(os.path.dirname(__file__))
from manager import Manager, AnotherClass
from config import Config
manager.py
import sys
import os
sys.path.append(os.path.dirname(__file__))
from config import Config
from cache import Cache
test.py
cwd = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.abspath(os.path.join(cwd, os.pardir)) + '/dir1')
from cache import Cache, AnotherClass
from manager import Manager
test = Cache()
...
So when I run test.py I get this:
File "/path/to/project/app/dir1/<module>
from cache import Cache
ImportError: cannot import name 'Cache'
from manager import Manager line 5,
Even though config.Config loads just fine, no errors there, but as soon as I try to import cache.Cache it suddenly can't find or import any class in cache.py. All files have the same permissions. Can someone tell me what's wrong here?
You are missing the __init__.py file in your module
app/
__init__.py
dir1/
__init__.py
config.py
cache.py
manager.py
test/
test.py
and instead of messing with sys.path should do a relative import like
from .config import Config
from .cache import Cache
Python 2 may also need a line
from __future__ import absolute_import
before those imports.