.env
(dotenv) files are a type of file commonly used for storing application secrets and variables, for example API tokens and URLs, although they may also be used for storing other configurable values. While they are commonly used for storing secrets, at a high level their purpose is to load environment variables into a program.
Dotenv files are especially suited for storing secrets as they are a key-value store in a file, which can be easily loaded in most programming languages and ignored by version control systems like Git with a single entry in a .gitignore
file.
In Python you can use dotenv files with the python-dotenv
module from PyPI, which can be installed with pip install python-dotenv
. To use dotenv files you'll first need a file called .env
, with content such as the following:
TOKEN=a00418c85bff087b49f23923efe40aa5
Next, in your main Python file, you need to load the environment variables from the dotenv file you just created:
from dotenv import load_dotenv
load_dotenv()
The variables from the file have now been loaded into your program's environment, and you can access them using os.getenv()
anywhere in your program, like this:
from os import getenv
my_token = getenv("TOKEN")
For further reading about tokens and secrets, please read this explanation.Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if
statement, and will only run if the if
statement evaluates to True
. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if
statement above as no more lines can be inside the if
statement below that line.
Indentation is used after:
1. Compound statements (eg. if
, while
, for
, try
, with
, def
, class
, and their counterparts)
2. Continuation lines
More Info 1. Indentation style guide 2. Tabs or Spaces? 3. Official docs on indentation