# Syntactical sugar for \`getfield\`

**URL:** https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075
**Category:** General Usage
**Created:** [December 19, 2020, 1:08am UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075 "2020-12-19T01:08:29Z")
**Posts on this page:** 19
**Page:** 1

<div class="post-metadata">

### Author: ![gcalderone](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gcalderone/32/1539_2.png) [@gcalderone](https://discourse.julialang.org/u/gcalderone)
#### Post date: [December 19, 2020, 1:08am UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075/1 "2020-12-19T01:08:29Z")

</div>

Each time I implement a new `getproperty` method for a structure I found myself filling the code with lengthy (and sometimes nested) calls to `getfield`. So far the best looking solution I came up with is:

```julia
⋄ = getfield # type \diamond<TAB>

```

It also has a relatively high precedence with respect to other operators.

MWE:

```julia
import Base.getproperty
⋄ = getfield

struct MyStruct
    greet::String
end

function getproperty(s::MyStruct, name::Symbol)
    @info "Accessing the $name property"
    s ⋄ name # in place of the longer `getfield(s, name)`
end

s = MyStruct("Hi")
s.greet * " there!"
s⋄:greet * " there!" # correct operator precedence

```

Is there any other recommended, or widely used syntactic sugar for `getfield` ?

---

<div class="post-metadata">

### Author: ![CameronBieganek](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cameronbieganek/32/6915_2.png) [@CameronBieganek](https://discourse.julialang.org/u/CameronBieganek)
#### Post date: [December 19, 2020, 1:55am UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075/2 "2020-12-19T01:55:17Z")

</div>

For an immutable struct, I’ve used this pattern:

```julia
struct A
	x::Int
	d::Dict{Int,Int}
end

x(a::A) = getfield(a, :x)
d(a::A) = getfield(a, :d)

```

```julia
julia> a = A(42, Dict(1 => 2, 3 => 4))
A(42, Dict(3 => 4,1 => 2))

julia> x(a)
42

julia> d(a)[5] = 6
6

julia> d(a)
Dict{Int64,Int64} with 3 entries:
  3 => 4
  5 => 6
  1 => 2

```

Note that with this pattern it is still pretty easy to mutate the contents of the dictionary.

---

<div class="post-metadata">

### Author: ![marius311](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/marius311/32/3953_2.png) [@marius311](https://discourse.julialang.org/u/marius311)
#### Post date: [December 19, 2020, 2:35am UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075/3 "2020-12-19T02:35:05Z")

</div>

Is there a reason not to just overload `getproperty` and then use the normal `.` syntax?

---

<div class="post-metadata">

### Author: ![CameronBieganek](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cameronbieganek/32/6915_2.png) [@CameronBieganek](https://discourse.julialang.org/u/CameronBieganek)
#### Post date: [December 19, 2020, 2:59am UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075/4 "2020-12-19T02:59:07Z")

</div>

@marius311 I’m not quite sure what you mean by that. Can you give an example?

---

<div class="post-metadata">

### Author: ![JeffreySarnoff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeffreysarnoff/32/1980_2.png) [@JeffreySarnoff](https://discourse.julialang.org/u/JeffreySarnoff)
#### Post date: [December 19, 2020, 3:08am UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075/5 "2020-12-19T03:08:46Z")

</div>

that would be preferred as

> The syntax a.b calls getproperty(a, :b).

@CameronBieganek:

```julia
julia> struct A
           x::Int
           d::Dict{Int,Int}
       end

julia> a = A(5, Dict([1=>2, 2=>3]))
A(5, Dict(2 => 3, 1 => 2))

julia> a.x
5

julia> a.d[2]
3

```

---

<div class="post-metadata">

### Author: ![CameronBieganek](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cameronbieganek/32/6915_2.png) [@CameronBieganek](https://discourse.julialang.org/u/CameronBieganek)
#### Post date: [December 19, 2020, 3:10am UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075/6 "2020-12-19T03:10:08Z")

</div>

Clearly in my brief example I left out the part where I overload `getproperty`…

---

<div class="post-metadata">

### Author: ![pdeffebach](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pdeffebach/32/10320_2.png) [@pdeffebach](https://discourse.julialang.org/u/pdeffebach)
#### Post date: [December 19, 2020, 3:14am UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075/7 "2020-12-19T03:14:59Z")

</div>

Its still nice to define these methods if you don’t want the user to use the fields directly. DataFrames defines `getproperty` to work with columns but then also has internal methods for accessing the actual fields of a data frame.

---

<div class="post-metadata">

### Author: ![JeffreySarnoff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeffreysarnoff/32/1980_2.png) [@JeffreySarnoff](https://discourse.julialang.org/u/JeffreySarnoff)
#### Post date: [December 19, 2020, 3:17am UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075/8 "2020-12-19T03:17:01Z")

</div>

I agree. Often, I use e.g.

```julia
struct Struct
  value::Int
end

value(x::Struct) = x.value

```

An additional benefit is that this may simplify a later modification.

---

<div class="post-metadata">

### Author: ![CameronBieganek](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cameronbieganek/32/6915_2.png) [@CameronBieganek](https://discourse.julialang.org/u/CameronBieganek)
#### Post date: [December 19, 2020, 3:27am UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075/9 "2020-12-19T03:27:38Z")

</div>

Here’s a better example than my previous one:

```julia
struct PropertyDict{V}
	d::Dict{Symbol,V}
end

d(pd::PropertyDict) = getfield(pd, :d)
Base.getproperty(pd::PropertyDict, sym::Symbol) = d(pd)[sym]
Base.setproperty!(pd::PropertyDict, sym::Symbol, val) = ( d(pd)[sym] = val )

```

```julia
julia> p = PropertyDict(Dict(:a => 1))
PropertyDict{Int64}(Dict(:a => 1))

julia> p.a
1

julia> p.b = 2
2

julia> p.b
2

```

I’m not certain, but my initial thought was that @marius311 meant that you can do something like this:

```julia
function getproperty(pd::PropertyDict, sym::Symbol)
    if sym == :d
        getfield(pd, :d)
    else
        getfield(pd, :d)[sym]
    end
end

```

That pattern can work in some scenarios, but in the case of the `PropertyDict` above, you want to be able to put any symbol into the dictionary as a key. In other words, you want to allow for the possibility that `:d` is one of the keys in the dictionary.

---

<div class="post-metadata">

### Author: ![marius311](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/marius311/32/3953_2.png) [@marius311](https://discourse.julialang.org/u/marius311)
#### Post date: [December 19, 2020, 4:03am UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075/10 "2020-12-19T04:03:42Z")

</div>

That was just a question for the OP, basically why create syntactic sugar for `getfield` when `getproperty` already has it.

---

<div class="post-metadata">

### Author: ![CameronBieganek](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cameronbieganek/32/6915_2.png) [@CameronBieganek](https://discourse.julialang.org/u/CameronBieganek)
#### Post date: [December 19, 2020, 4:21am UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075/11 "2020-12-19T04:21:41Z")

</div>

It seems like we’re talking past each other here. Take a closer look at my second example. The issue arises when you overload `getproperty`. Once you do that, you can no longer use dot syntax to access the underlying fields of your struct, so you have to run around calling `getfield(a, :x)` all the time, which gets messy real fast.

---

<div class="post-metadata">

### Author: ![JeffreySarnoff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeffreysarnoff/32/1980_2.png) [@JeffreySarnoff](https://discourse.julialang.org/u/JeffreySarnoff)
#### Post date: [December 19, 2020, 5:44am UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075/12 "2020-12-19T05:44:10Z")

</div>

> [@gcalderone](#):
>
> Each time I implement a new `getproperty` method for a structure I found myself filling the code with … calls to `getfield` … Is there any other recommended, or widely used syntactic sugar for `getfield`?

No, there is not (at least not at the time this is written).

---

<div class="post-metadata">

### Author: ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)
#### Post date: [January 21, 2021, 8:20am UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075/14 "2021-01-21T08:20:54Z")

</div>

I see that this thread is a bit old (but popped up on the front page now).

But is it really a good idea to let properties and fields share the same names? I see properties as part of the interface, but fieldnames as implementation details, and would think that their names should be decoupled.

And even if you don’t want properties as part of the interface, it seems to me that they should be ‘virtual fields’ that have unique names, separate from the fieldnames.

---

<div class="post-metadata">

### Author: ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)
#### Post date: [January 21, 2021, 2:07pm UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075/15 "2021-01-21T14:07:15Z")

</div>

> [@DNF](#):
>
> But is it really a good idea to let properties and fields share the same names?

Yes. This is not problematic, but convenient, as fields provide a default for properties.

Of course, one is free to design an API where the two are distinct.

---

<div class="post-metadata">

### Author: ![gcalderone](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gcalderone/32/1539_2.png) [@gcalderone](https://discourse.julialang.org/u/gcalderone)
#### Post date: [January 21, 2021, 3:22pm UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075/16 "2021-01-21T15:22:24Z")

</div>

I’m afraid my initial question was slightly misleading. I’ll try to rephrase as follows:

The default implementation of `getproperty` is to call `getfield`, and the dot-syntax is a sugar for `getproperty`. Hence, in my module implementation, I can access structure fields with `struct.fieldname`.

Now assume I want to provide a high-level interface(\*) by implementing a `getproperty` method for my structure definitions. All my `struct.fieldname` statements would no longer works, and I need to explicitly invoke `getfield` (possibily several times in the same statement, when dealing with nested structures…).

Is there any alternative, commonly adopted, sugar for `getfield`?

According to above answers, I guess the final answer is “no”.  
Which is not necessarily a big deal: `⋄` works for me. It is just aesthetically unpleasant…

* * *

(\*): e.g. to protect the implementation details and, most importantly, provide access to views over specific fields of multi-level nested structures.

But the key point here is to assume there is a very good reason to overload `getproperty` (to simplify usage outside my module), while still accessing fields with `getfield` (within my module).  
Answers like “Why do you need that?”, “Do this instead”, etc. are attempts to circumvent this assumption…

---

<div class="post-metadata">

### Author: ![mcabbott](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mcabbott/32/6603_2.png) [@mcabbott](https://discourse.julialang.org/u/mcabbott)
#### Post date: [January 21, 2021, 3:31pm UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075/17 "2021-01-21T15:31:54Z")

</div>

I don’t know any conventions, but you can do something like this for internal use… can’t avoid typing the `:` without a macro though:

```julia
julia> (..)(x, s::Symbol) = getfield(x, s);

julia> (1:3)'..:parent
1:3

```

---

<div class="post-metadata">

### Author: ![gcalderone](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gcalderone/32/1539_2.png) [@gcalderone](https://discourse.julialang.org/u/gcalderone)
#### Post date: [January 21, 2021, 4:00pm UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075/18 "2021-01-21T16:00:26Z")

</div>

Yes this is nicer, but operator precedence is not correct.

The following raises an error:

```julia
(..)(x, s::Symbol) = getfield(x, s);
(1:3)'..:parent .+ 1

```

while

```julia
⋄ = getfield
(1:3)'⋄:parent .+ 1

```

works as expected.

---

<div class="post-metadata">

### Author: ![mcabbott](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mcabbott/32/6603_2.png) [@mcabbott](https://discourse.julialang.org/u/mcabbott)
#### Post date: [January 21, 2021, 4:11pm UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075/19 "2021-01-21T16:11:31Z")

</div>

Oh yea, good point. You could shadow `^` since that has high precedence, and is easy to type:

```julia
^(x, s::Symbol) = getfield(x, s)
^(x,y) = Base.:^(x,y) # fall-through on other types
(1:3)'^:parent .+ 1

```

There was an issue somewhere to make some more double-ascii operators with varying precedence, there is `++` but say `^^` would be neat here.

---

<div class="post-metadata">

### Author: ![gcalderone](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gcalderone/32/1539_2.png) [@gcalderone](https://discourse.julialang.org/u/gcalderone)
#### Post date: [January 21, 2021, 4:19pm UTC](https://discourse.julialang.org/t/syntactical-sugar-for-getfield/52075/20 "2021-01-21T16:19:07Z")

</div>

So far, `^` is the best solution!!  
Thanks.
