Circular Import Error while importing create_engine in Sqlalchemy

Viewed 2493

I am trying the CS50 Web Development with Python Course, and in the sql section, while importing create_engine from sqlalchemy I got this error

ImportError: cannot import name 'create_engine' from partially initialized module 'sqlalchemy' (most likely due to a circular import)

Here is the snippet:

DATABASE_URL = "postgres://usrname:password@YourHost:5432/flights"


from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

engine = create_engine(DATABASE_URL)
db = scoped_session(sessionmaker(bind=engine))   

flights = db.execute("SELECT origin, destination, duration FROM flights").fetchall() 

for flight in flights:
    print(f"{flight.origin} to {flight.destination}, {flight.duration} minutes.")

Timestamp for the Video:

https://video.cs50.net/web/2018/spring/lectures/3?t=1h9m52s

2 Answers

This can result from a namespace collision - i.e. naming the file you are executing sqlalchemy.py. To fix this, change the name of the script you are executing to something else.

I dont see a circular import here, but a possible work-around is to

import sqlalchemy as sqlalchemy_package
engine = sqlalchemy_package.create_engine(DATABASE_URL)

, replacing the line engine = create_engine(DATABASE_URL)

Related