17

In C, one can declare static variables with local function scope (example).

Can something similar be done in Julia?

My use case is declaring sub-functions, but do not want Julia to have to reparse them every time the code executes. Declaring them outside of the function is ugly and gives them higher scope, which I want to avoid.

example:

function foo(x)
    static bar = t -> stuff with t

    ...
    bar(y)
    ...
end

While I could declare bar() outside of foo(), I would prefer bar to only be in the local namespace.

Thank you.

Community
  • 1
  • 1
Mageek
  • 4,691
  • 3
  • 26
  • 42

3 Answers3

16

You can create a new scope around the function, to hold the variable.

let
    global foo
    function bar(t)
        #stuff with t
    end
    y = 2
    function foo(x)
        #...
        bar(y)
        #...
    end
end

Then only foo(x) will be visible to the outside

ivarne
  • 3,753
  • 1
  • 27
  • 31
5

Based on @ivarne's answer.

let bar = t -> t^2
    global foo
    function foo(x)
        bar(x)
    end
end

But I don't think this is an ideal solution. IMHO it would be better to have a static keyword. The extra block is unwieldy. There is some discussion about this in Julia development:

https://github.com/JuliaLang/julia/issues/15056

https://github.com/JuliaLang/julia/issues/12627

a06e
  • 18,594
  • 33
  • 93
  • 169
4

Note that y needs to be a let variable in @ivarne's answer, or it will overwrite any y in global scope:

julia> y = 4
4

julia> let
           global foo
           function bar(t)
               #stuff with t
           end
           y = 2
           function foo(x)
               #...
               bar(y)
               #...
           end
       end
foo (generic function with 1 method)

julia> y
2
kmsquire
  • 1,302
  • 12
  • 12