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.

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.