python equivalent of (process.env.PORT || 3000)

Viewed 1146

I don't know if this is the best place to ask but wanted to know what the python equivalent to const port = process.env.PORT || 3000; is?

The main purpose being I want to be able to set environment variables in python depending on the environment

1 Answers

You can use os.environ.get('PORT', 3000). The os.environ map supports the .get method, which returns the value if the key is present, otherwise the second argument is returned.

~$ PORT=4000 python

>>> import os
>>> os.environ.get('PORT', 5000)
'4000'

You might want to wrap the command in int to get an int regardless of whether the environment variable or the default value is used, but the behaviour will be the same as in your Javascript example.

Related