Pyodbc - can't connect to database

Hi,
I’m trying to connect to a MS SQL database using the pyodbc module and I get the following error:

pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Named Pipes Provider: Could not open a connection to SQL Server [2].  (2) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (2)')

The connection string is:

conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=localhost;DATABASE=testdb;UID=operator;PWD=******')

I have enabled TCP/IP and named pipes in the server configuration, restarted the server, disabled firewall, allowed remote connections in the server settings. I have no issues connecting using SSMS.
I’m not sure what to check for any further.