Julia: feature request: kwargs for getindex

Created on 18 Jan 2018  路  10Comments  路  Source: JuliaLang/julia

Current behavior is to treat = as assignment inside []

julia> Meta.@lower x[a=1] = 3
:(begin
      a = 1
      setindex!(x, 3, 1)
      return 3
  end)

But for consistency with (), I would like to have it parse as a kwcall

setindex!(x, 3; a=1)

Currently, that has to be written:

x[(a = 1,)] = 3

which is much less nice.

parser

Most helpful comment

I wanted to use this syntax for multidimensional arrays with "named" dimensions (as in the Python library xarray). So if M is a two-dimensional array with dimensions named x and y, I'd like to be able to write M[x=3, y=2] to index the (3, 2) element. Currently there's no way to use the subscript notation for getindex(A; dims...).

All 10 comments

I've used things like a[i += 1] to simultaneously increment a counter and do getindex or setindex, but presumably this would continue to work, since keywords happen in parsing and += is dealt with in lowering.

Agree, this seems like a really bizarre misfeature request to me. The fact that indexing is lowered to a function call is incidental, indexing syntax is not function call syntax.

I wanted to use this syntax for multidimensional arrays with "named" dimensions (as in the Python library xarray). So if M is a two-dimensional array with dimensions named x and y, I'd like to be able to write M[x=3, y=2] to index the (3, 2) element. Currently there's no way to use the subscript notation for getindex(A; dims...).

That does seem more useful to me than doing an assignment inside an indexing expression (a[b+=1] is indeed a separate case and would continue to work).

I find that argument convincing.

In function calls, we also allow e.g. x+=1 but---obviously---treat x=1 as a keyword argument, so doing the same for indexing seems fine.

Is this on the wrong milestone?

No; for 0.7 we added a deprecation warning, and for 1.0 the new desired behavior (lowering to kwargs) needs to be added to replace it.

Re-opening to track the possibility of adding this feature in 1.x now that the old behavior has been deprecated.

It appears this feature was implemented in 1.0 as part of #28366:

julia> dump(:(x[a=1]))
Expr
  head: Symbol ref
  args: Array{Any}((2,))
    1: Symbol x
    2: Expr
      head: Symbol kw
      args: Array{Any}((2,))
        1: Symbol a
        2: Int64 1
Was this page helpful?
0 / 5 - 0 ratings

Related issues

TotalVerb picture TotalVerb  路  3Comments

arshpreetsingh picture arshpreetsingh  路  3Comments

ararslan picture ararslan  路  3Comments

sbromberger picture sbromberger  路  3Comments

musm picture musm  路  3Comments