1

I am trying to read through some source code and found this. Someone tell me what the second parameter "29" does? I am used to only seeing one parameter

OWNER_ID = os.environ.get("OWNER_ID", "29")
Luqman
  • 127
  • 8

1 Answers1

0

Because os.environ returns a dedicated mapping type (and not a dictionary as user2357112 has pointed out in the comment) that inherits the get() method from the Mapping class, it works similarly to dict.get(). So the following line:

OWNER_ID = os.environ.get("OWNER_ID", "29")

would be equivalent to

try:
    OWNER_ID = os.environ["OWNER_ID"]
except KeyError:
    OWNER_ID = "29"

It implicitly handles the KeyError and returns the default value "29" instead of raising an error if the key "OWNER_ID" does not exist.

See also:

Troll
  • 1,895
  • 3
  • 15
  • 34
  • 2
    `os.environ` is not a dict. It's an instance of a dedicated mapping type, so it can write changes back to the actual environment when `os.environ` is mutated. – user2357112 Nov 04 '21 at 03:33
  • (Unfortunately, it won't reflect any changes that happen to the actual environment that *aren't* performed by mutating `os.environ`. This even includes [not showing the effect of calls to `os.putenv`](https://ideone.com/XzYSdp) - if you call `os.putenv` to set environment variables, Python provides no API to see the new values. Even `os.getenv` won't show them, because `os.getenv` looks at `os.environ` instead of the real environment.) – user2357112 Nov 04 '21 at 03:36
  • @user2357112supportsMonica Ok, I see. I have taken a look at the [source code](https://github.com/python/cpython/blob/main/Lib/os.py#L768) and it seems like `os.environ` is a variable that calls the `_createenviron()` function, which returns a class that inherits from `MutableMapping` and has a `get()` method. It is not a dict. Thank you for pointing out. – Troll Nov 04 '21 at 04:03