166 points · by bjourne · 4y ago · 96 comments
In functional languages this is called "destructuring assignment".
This article could be a great jumping off point into namedtuple[1], the walrus operator [2] and the Pattern Matching[3] (Python 3.10), which assist into getting back into the symbolic domain from the structural domain, though you will have to come up with names! :)
Remember that namedtuple has the following additional methods
_make Class method that makes a new instance from an existing sequence or iterable
_asdict Return a new dict which maps field names to their corresponding values
_replace Return a new instance of the named tuple replacing specified fields with new values
_fields Tuple of strings listing the field names
_field_defaults Dictionary mapping field names to default values.
[1] https://docs.python.org/3/library/collections.html#collectio...Also (but a bit minor, given that Google tells me Python’s named tuples are immutable, so I guess programmers will know that): if I were to read foo._replace(bar=42) I would think that to modify foo.
Because of that, I like scala’s foo.copy(bar=42) more. It makes it clearer that you have to do foo = foo.copy(bar=42) to ‘change’ the value of foo (actually: bind it to a new value).
MyClass = namedtuple("MyClass", ["make", "asdict", "fields"])
x = MyClass(make=10, asdict=11, fields=12)
print(x.asdict)
The "underscore-to-avoid-naming-conflicts" approach is used elsewhere in the Python standard library, too, although another example isn't coming to me at the moment.The core data model of "almost everything is a mutable lookup table" can be easy to work with and reason about at times, but sometimes it's a little too simple, and you end up with these kinds of ad-hoc and inconsistent workarounds even in the standard library.
I thought it's just called pattern matching. Most functional languages don't have assignment and have bindings instead.
This article describing the Python feature of multiple assignment demonstrates only the destructuring assignment (assignment, because it is Python and these variables can be reassigned). There is no control flow tied to this operation, except for the exceptions that can be thrown when the LHS and RHS have incompatible structure.
Clojure is another example of a language with destructuring binding that is not tied to a control flow construct. Clojure functions and `let` bindings can use a destructuring syntax to bind to elements in a data structure. There is no tightly-linked control flow structure that goes along with this binding mechanism. It is my understanding that there are several libraries available that implement pattern matching, but I do not use these.
Most often, when I have seen pattern matching described to an audience with a background in imperative languages, it is compared to a super-powered switch statement. This gives the impression that the important part is the control flow. Languages such as Python and Clojure show that there is inherent value in the destructuring assignment/bind, even out of the context of control flow.
Iterator unpacking:
first, *middle, last = t
is similar to a match/case with a sequence pattern: match t:
case first, *middle, last:
...
The former works for any iterable and the latter requires a sequence. The former raises an error for a non-iterable and the latter just skips the case for a non-sequence. Otherwise, they are similar.However, arguing that one is a special case of the other misses the entire point of structural pattern matching. We would almost never substitute the latter for the former. They mostly live in different worlds because we use them and think about them much differently:
# Something that would work but they we don't do
for item in somedict.items():
match item:
case [key, value]:
print(key.upper())
print(value)
print()
case _:
raise RuntimeError('unexpected kind of item')
# What we actually do
for key, value in somedict.items():
print(key.upper())
print(value)
print()
Sorry for the small rant, but I think this pedantic point isn't a useful line of thinking. That concepts and implementation have some overlap but should occupy a different concept maps in our brains — very much like the idea that dicts can do set-like things but that we're better off thinking about dicts as doing lookups and sets as doing uniquification, membership-testing, and set-to-set operations. - point to a structure / object
- declare a variable
- access the object / structure field and assign it to var
- repeat for every information you want to extract from the struct / object
is large and now replaced by something transparentUnpacking doesn't let you specify default values if cardinality doesn't match, nor can you extract dictionaries by keys.
Since operators.itemgetter and itertools.slice are limited, I end up either adding a dependency or reinventing the wheel for every project.
I'm a bit confused by this one, but maybe I'm misunderstanding. Does this not accomplish what you're defining?
def parse_record(first=0, second=1, **all_the_others) -> dict:
return dict(first=first, second=second, **all_the_others)
dictionary = dict(first=99, third=2)
parse_record(**dictionary)
> {"first": 99, "second": 1, "third": 2} d = {'a' : 10, 'b' : 20, 'c' : 30}
{'a' : v1, 'b' : v2, **others} = d
print(v1, v2, others) # prints 10, 20, {'c' : 30}The working code in Python, as a function, would be:
def extract(mapping, *args, **kwargs):
for a in args:
yield mapping[a]
for key, default in kwargs.items():
yield mapping.get(key, default)Python really needs something like:
{foo: "default", mapping} = mapping foo = mapping.pop("foo", "default")
It removes "foo" key from mapping if any. `foo` is "default" if "foo" is missing and `mapping["foo"]` otherwise.Dictionary unpacking compatible with the match/case syntax could look like:
{"foo": foo, **rest} = mapping
It asserts that there is "foo" key in mapping and puts its value into `foo`.Also using ? For attributes that might be there and being able to chain that is sooo awesome.
These two things make for example working with nested Json in JS so much better than in Python.
We would need a ? to says "ignore AttributeError, IndexError and KeyError on that access".
However, the use of {} for set is not a problem.
First, remember than Python is much, much older than JS. Insight is 20/20. Second, you could always use a different syntax.
Functional languages that have pattern matching have wildcard matches that allow you to explicitly handle things that don't match as expected and also have tail matching for lists.
> nor can you extract dictionaries by keys
I'm not exactly sure what you mean here, but you can definitely do that for records in F# and maps/structs in Elixir. It's done all the time.
Now you can do:
import operator
foo, bar, baz = operator.itemgetter('foo', 'bar', 'baz')(mapping)
But it's verbose, inelegant, and doesn't handle missing values. first, second, *others = some_tuple
I've opted for less-readable positional indexing several times for not realizing this. Looks like I have some updates to do. (lambda (x, y): x+y)((2, 3),) lambda (x1, y1), (x2, y2): return abs(x2 - x1) + abs(y2 - y1)Not as nice, but:
(lambda x, y: x+y)(*(2, 3))
Seems to work lambda i,(x,y): x[i]+y[j]
I never really understood the rationale here. Pep8 hates lambdas, which is also baffling. It seems as though tptb don't like lambdas, but there wasn't enough political will to remove them entirely, so they kneecapped them instead. Because... more lines = more readable??But we've got a walrus operator now, because... less lines = more readable?
https://mail.python.org/archives/list/python-dev@python.org/...
And if you really want to make the perfect lambda, you can do that with code generation and frame walking/patching.
first, *rest = xs
rest = tuple(rest)
because often I want to hash "rest".Another trick I often use:
the_only, = xs
This extracts the single element of a one-element iterable and throws an error if xs is empty or has more than one element.Example:
julia> X = (this = 3, that = 5)
(this = 3, that = 5)
julia> this
ERROR: UndefVarError: this not defined
julia> (;that, this) = X;
julia> this
3
julia> that
5
this works with structs as well (in fact anything with getproperty() defined, so like dataframe column too) >>> from types import SimpleNamespace
>>> d = {"one":1, "two":2}
>>> ns = SimpleNamespace(**d)
>>> ns.two
2
I consider it a bonus that the dict keys are grouped as attributes on an object :)However, I almost never use SimpleNamespace in real code. Dicts offer extra capabilities: get, pop, popitem, clear, copy, keys, values, items). Classes/instances offer extra capabilities: unique and shared keys in distinct namespaces, instances knowing their own type, and an elegant transformation of method calls ``a.m(b, c)`` --> ``type(a).m(a, b, c)``. Dataclasses and named tuples have their advantages as well. In practice, it is almost never that case that SimpleNamespace beats one of the alternatives.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
You can always partially unpack, just only put what you need on the LHS
# oops, ValueError on `item = "noequals"`
key, value = item.split("=", 1)
That alone makes destructuring somewhat limited, unless I'm either willing to validate my lengths ahead of time or do exception-driven control flow. Something like `?=` perhaps, to complement the walrus operator. key, sep, value = item.partition("=")
If you need to know whether there was a split/match that occurred you could test sep's truthiness. key, *value = item.split("=", 1)
if value:
value = value[0]
else:
value = None key, value ?= item.split("=", 1)
Modulo bike shedding over the actual syntax, of course.(Edit: the semantics of this could be even more generic, like Ruby's `[...] rescue value` syntax for turning any raised exception into a default value instead.)
value = value[0] if value else NoneI’m happy that js and python have also adopted it.
>>> n = list(range(10))
>>> n[::3] = 'fizz'
>>> n
['f', 1, 2, 'i', 4, 5, 'z', 7, 8, 'z']
It's weird but occasionally useful. head, *middle, tail = numbers x = y = None a = b = 10 # multiple assignment
a, b = b, a # simultaneous (or parallel) assignmentThe language specifies that simple statements can be separated by semicolons. Black eliminates this part of the language, essentially overriding Guido's decision.
The language specifies that four different quoting characters are available. Black eliminates this part of the language, mandating double quotes in code and single quotes in a repr output, essentially overriding Guido's decision.
The language specifies that in-line comments can start anywhere on a line. Black eliminates the writer's option to line-up their comments vertically, essentially overriding Guido's language decision.
The language allows and PEP 8 encourages using whitespace to aid readers in reading mathematical expressions just like sympy and LaTex do: ``3x*2 - 2x +5``. Black eliminates this possibility and mandates equal spacing regardless of operator precedence: ``3 * x * 2 - 2 * x + 5``. Once again, this overrides Guido's judgment.
Wouldn't be better for Guido to decide what the language allows rather than have a downstream tool narrow the range of what is possible?
Pushing extra spaces into slices is another one I don't care for.
for (auto& [key, value] : persons)
The nested bindings are neat. Don’t think you can do that in c++ yet.anyone know why this works in python
lst=[]
lst+=2, # note , in the end
print(lst) #[2] [] + (2,)
is a TypeError: can only concatenate list (not "tuple") to list
but L = []
L += (2,)
is totally cool.In the end, it makes sense because I can't tell you if []+() should be a tuple or a list, and even if I did, I might have a different answer for ()+[]; whereas L+=bla looks like the type of L should not change.
lst += (2,) () # Makes a zero-tuple. The parens are required.
2, # Makes a one-tuple.
(2,) # Makes a one-tuple. The parens are optional.
[2] # Makes a list of size one.
[(2)] # Also makes a list of size one.
[2,] # Also makes a list of size one.
f(x, y) # Call a function with two arguments.
f((x, y)) # Make a 2-tuple and call a function with one argument.BTW, kind of a tangent, I've always assumed (but not checked) that every "()" literal evaluates to one singleton zero-tuple, do you know if that's true?