Accessing Internal variables in a function

I came across following snippet in Flux tutorial:

function linear(in, out)
  W = randn(out, in)
  b = randn(out)
  x -> W * x .+ b
end

linear1 = linear(5, 3) # we can access linear1.W etc
linear1.W

Here linear1.W can print the value of W. I am bit confused regarding the exact nature of linear1. Are internals of the function accessible in julia?

My own attempt proved futile:

function add_22_2_xy(x,y)
     a  = 22
     return a + x + y
end

ex1 = add_22_2_xy

ex1.a

Above snippet returns

type #add_22_2_xy has no field a

Can someone clarify when internals of a function can be accessed?

Your linear function returns an anonymous function, but your add_22_2_xy function returns a number. Also, in the first example you call the linear function, and in the second you just assign the add_22_2_xy function to a variable.

I think it’s something specific to closure. As the documentation says:

A closure is simply a callable object with field names corresponding to captured variables. For example, the following code:

function adder(x)
    return y->x+y
end

is lowered to (roughly):

struct ##1{T}
   x::T
end

(_::##1)(y) = _.x + y

function adder(x)
    return ##1(x)
end

So because the W is captured by the closure, you can access it like a field.

3 Likes