4 ms·
Why does _ need to be special cased like this? In Python this works with any variable name. e.g. >>> p = { "Alice": ["g", 1, "a@a"], "Bob": ["b", 2, "b@b"
by __alexs 14y ago
Why does _ need to be special cased like this? In Python this works with any variable name.
e.g.
>>> p = { "Alice": ["g", 1, "a@a"], "Bob": ["b", 2, "b@b"]}
>>> [(name, email) for name, (unused, unused, email) in p.iteritems()]
[('Bob', 'b@b'), ('Alice', 'a@a')]
- adgar 14y agoThe idea is that if you reuse a formal parameter name and have not used _, then you more than likely introduced a subtle bug. For example x and y can look similar enough next to each other, so missing that you instead wrote `x, x` might take you way longer than necessary.
- sp332 14y agoMultiple underscores work in Ruby 1.8, too, but for a different reason: Ruby 1.8 doesn't care about duplicated arguments in block parameters. It looks like this used to work in 1.8, but a "duplicate checker" was added in 1.9?
- falcolas 14y agoPython also supports the '_' character in that same manner. It's just a legal variable name that is given special meaning when in the interactive interpreter. >>> p = { "Alice": ["g", 1, "a@a"], "Bob": ["b", 2, "b@b"]} >>> [(name, email) for name, (_, _, email) in p.iteritems()] [('Bob', 'b@b'), ('Alice', 'a@a')]
- ori_b 14y agoRuby defines 'map', 'each', and other iteration utilities as higher order functions. This means that, while it works for tuples, this does not for looping. The equivalent code in Python would be this: def each_fn(unused, unused, email): pass map(iter_fn, list) And this does in fact give a syntax error: SyntaxError: duplicate argument 'unused' in function definition
- msbarnett 14y ago> Why does _ need to be special cased like this? In Python this works with any variable name. To, in general, make giving multiple arguments for a function or block/lambda the same name a syntax error. Python special-cases generators, but having multiple identical argument names for a function in Python is a syntax error. Ruby is a bit more 'regular' in that in both blocks/lambdas and functions, reusing an argument name is always an error. '_' then functions not as a name but a special 'disregard' symbol.