Normally, Python doesn’t enforce uniqueness on Enum values: The @unique decorator enforces:
Want your Python Enum class to be sortable? The regular Enum doesn’t do it, but IntEnum does: Days.SUN < Days.THU # True!Days.MON > Days.WED # False!
Enums are a great addition to Python: They print nicer and are symbolic! But… not sortable (yet).
Can you get Python to enforce constants? Yes, with type checking: Ruff won’t complain. Instead, type it as Final and run mypy: mypy myprog.pymyprog.py:6: error: Cannot assign to final name “NAME” [misc]
About immutable vs. constant in Python: – Immutable: The value cannot change. If you own an immutable shirt, you can’t change its color, or add/remove a button.– Constant: Once assigned, a name will always refer to a value. But: Python’s constants are unenforced conventions!
Want the unique key-value pairs from two Python dicts? dict.items() returns a set-like object: This returns the unique key-value pairs: {(‘b’, 20), (‘a’, 10), (‘d’, 40), (‘c’, 30)}
Want the unique keys from two Python dicts? dict.keys() returns a set-like object, supporting set operators:
Differences between dict.pop and dict.popitem in Python: dict.pop: – removes a pair based on a key– returns removed value– optional 2nd arg is returned if key isn’t there dict.popitem: – no arguments– returns the most-recently-inserted pair– returns (key, value) tuple
To remove a key-value pair from a Python dict, use dict.pop: Or… pass a second argument to dict.pop. You’ll get it instead of an exception:
Merge two Python dicts with | which returns a new dict. Conflicts? The right-side dict gets priority: d1 | d2 # {‘a’: 10, ‘b’: 100, ‘c’: 200, ‘d’: 300}d2 | d1 # {‘b’: 20, ‘c’: 30, ‘d’: 300, ‘a’: 10}