1

I had a file at db/connection.py. I moved the file and now the path is project/db/connection.py. Previously I imported that file using this syntax:

import db.connection

And somewhere in the code I had access to the file:

db.connection.open_connection()

Since now the file is moved, I know only two options to import the file: using import and from import keywords. But both of them will change the reference to the file. I'll show you what I mean. If I use import:

import project.db.connection

Then the new reference is project.db.connection and I need to change the code that accesses the file as well, so that it becomes:

project.db.connection.open_connection()

If I use from import:

from project.db import connection

The same problem, but now the reference is connection.

I thought I could do that:

from project import db.connection

But python gives me an error at that line of code:

from project import db.connection
                     ^

SyntaxError: invalid syntax

So if it's possible, how to import the new file having the reference db.connection, so I don't need to change the code that accesses that file?

6
  • If I understand your question correctly, you can just do: import x as db.connection Commented Oct 23, 2022 at 10:58
  • @einekratzekkatze, unfortunately, the same syntax error at line import project.db.connection as db.connection Commented Oct 23, 2022 at 10:59
  • from project.db import connection…‽ Commented Oct 23, 2022 at 11:24
  • @deceze, this syntax imports the file as connection, but not as db.connection Commented Oct 23, 2022 at 12:26
  • Yeah, but if you always take care to import it as connection, then that's fine… Commented Oct 23, 2022 at 21:37

1 Answer 1

1
from project import db

Maybe you need to add __init__.py file in project and in project/db.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.