Understanding Databases ENV vars page 4

I am using Python 3.10.4
In the book it has this code:

from dotenv import load_dotenv
load_dotenv()
import os
assert os.environ.get(“DATABASE_BACKEND”) == “postgres”

The code does not seem to work.

from dotenv import load_dotenv
load_dotenv()
True
import os
assert os.environ.get("DATABASE_BACKEND") == "postgres"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError</module></stdin>

The data seems to be there:

os.environ['DATABASE_BACKEND']
'”postgres”'

If I do something like:
db = os.environ.get("DATABASE_BACKEND")
db2 = '"postgres"'
assert db == db2 I get a Assertion error as well. I also get it is i use only the single quote or single double quotes.

The assertion fails, but the data seems to be there. I don't know if this is going to cause problems down the road, but I am going to continue. If someone knows what is going on, I would appreciate knowing.

3 Replies

I'm no python expert but I'm pretty sure you're mixing ' (single quote) and " (double quote) incorrectly. I did this a few minutes ago:

stevewi@dave:~ $ export DATABASE_BACKEND=postgres
stevewi@dave:~ $ python3.9
Python 3.9.13 (main, May 19 2022, 01:16:32) 
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['DATABASE_BACKEND']
'postgres'
>>> os.environ.get('DATABASE_BACKEND')
'postgres'
>>> db =  os.environ.get("DATABASE_BACKEND")
>>> db
'postgres'
>>> db2 = 'postgres'
>>> assert db == db2
>>> db2 = "postgres"
>>> db2
'postgres'
>>> assert db == db2

The difference in version shouldn't matter. This is really basic stuff™

-- sw

Thanks for the reply. The quotes were what I got from the call. BUT today I did the same code and it worked. I don't remember, but I may have copied the code in the book instead of typing it. It is the only thing I can think of that may have influence the outcome.

I did try it again from scratch. The difference between what you did and what I did, was I created the .env file and put the vars in it. I did it your way and it worked, so then I created the.env file and put the vars in it expecting the failure. But surprise it worked fine.

I tried several times thinking I had made a simple typing error, but it is now working. Your response made me start over, so thank you for the response.

Just FYI, in python (and ruby, perl, php, etc),

"this string" == 'this string'
"this string" == "this string"
'this string' == 'this string'

etc. are all true; but

"this string" == '"this string"'
"'this string'" == 'this string'

etc. are all false.

-- sw

Reply

Please enter an answer
Tips:

You can mention users to notify them: @username

You can use Markdown to format your question. For more examples see the Markdown Cheatsheet.

> I’m a blockquote.

I’m a blockquote.

[I'm a link] (https://www.google.com)

I'm a link

**I am bold** I am bold

*I am italicized* I am italicized

Community Code of Conduct