Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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')]


Ruby 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


> 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.


Python 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')]


Multiple 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?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: