Until now, when it came to getting environment variables in Python, it was like this.
import os
dsn = os.environ.get('DATABASE_URL')
But recently I learned that there is a method called ʻos.getenv`.
Reference: Difference between os.getenv and os.environ.get in Python --Qiita
Since ʻos.getenv is equivalent to ʻos.environ.get
, the above code can be rewritten as:
from os import getenv
dsn = getenv('DATABASE_URL')
It seems that either one is not officially recommended, but I personally think that ʻos.getenv` is better because it is "** it is clear why you are importing os **".
Since the os module has several uses, it is hard to understand "what is this for?" Even if it says ʻimport os, but if it is
from os import getenv`, it is" You're importing because of environment variables. "
from os import environ
, but it's unpleasant to import an object that is not callable (it's a matter of feeling, so if you don't care about this, it may be good).Recommended Posts