0

When defining a function, * means to collect parameters, and ** means to collect keyword parameters.

env = {**os.environ}

os.environ is not a dict,why the above code works?

  • it has `.keys()`, `.items()`, `__getitem__`, etc. similar to dictionary so it can behave like dictionary. – furas Oct 20 '22 at 02:38
  • in some situations `**` means `"collect keyword parameters"` but in other situations it means `"unpack dictionary"` – furas Oct 20 '22 at 02:40
  • 1
    Related: [What is a mapping object, according to dict type?](https://stackoverflow.com/q/40667093/674039) – wim Oct 20 '22 at 02:41
  • 2
    Moreover: [Class that acts as mapping for **unpacking](https://stackoverflow.com/questions/8601268/class-that-acts-as-mapping-for-unpacking) – metatoaster Oct 20 '22 at 02:41

1 Answers1

2

Although ** is typically used on dictionaries, it allows you to unpack any Mapping.

Note that:

import os
from typing import Mapping

print(isinstance(os.environ, Mapping))

Prints:

True

Similarly, * allows you to unpack any iterable.

Grismar
  • 27,561
  • 4
  • 31
  • 54
  • You should probably demonstrate with [`collections.abc.Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping) instead. `typing.Mapping` is deprecated. Also, I think both dupe-hammering _and_ answering together is a bit weird. – wim Oct 20 '22 at 02:58
  • There's nothing against providing an answer to a question that's a dupe - it's a dupe, so it should get closed, but I figured giving OP a basic answer might help them. Not sure how that's weird. – Grismar Oct 20 '22 at 03:55
  • 1
    It’s explained why that’s discouraged here: https://meta.stackoverflow.com/q/286072/674039 – wim Oct 20 '22 at 06:06
  • The argument made there is fair - I wasn't hunting for upvotes (and in fact assumed I wouldn't get one), in retrospect should have provided the info in a comment (the reason I didn't was because I figured a short bit of code would be more helpful). Not so much weird as undesirable for good reason. – Grismar Oct 20 '22 at 06:19