I mean, you’ve already experienced one way that you can check: if you try to assign to a variable name and get the error you just got, that name is unavailable (in current module scope). Beyond that, the answer to your question somewhat depends on why you want to do this:
- Are you wanting to programmatically find out what names are available for assignment for the purpose of e.g. writing some developer tooling?
- Do you just want to be able to use the names you want even if they’re defined elsewhere?
- Do you not want your long-running calculation to error out after 30 minutes because you have a
Int=5
statement somewhere in your code, so you want advance notice if you ever make this error?
For 1, doing this programmatically isn’t necessarily as easy as it seems like it should be. Basically what you’re asking is to get a list of all symbols defined in a specific module. Theoretically, I think this is what the names
function is intended to be for, but practically it doesn’t get you there. The best answer I’ve seen is from Tim Holy a few years ago:
function namesin(mymod)
nms = names(mymod; imported=true)
for mod in Base.loaded_modules_array()
if isdefined(mymod, nameof(mod))
append!(nms, names(mod))
end
end
nms
end
And then you could use this funciton to check whether e.g. Int
is already assigned:
julia> :Int in namesin(Main)
true
julia> :other_symbol in namesin(Main)
false
For 2, you do have options: you can create a module without Int
defined within it, or you can use let
to shadow variable names within the let
-block’s scope:
julia> baremodule ThisModuleOnlyImportsCore
Int = 5
end
Main.ThisModuleOnlyImportsCore
julia> ThisModuleOnlyImportsCore.Int
5
julia> let Int=6
x = Int + 3
println(x)
println("let statements always assign to a new variable location instead of trying to assign to existing")
end
9
let statements always assign to a new variable location instead of trying to assign to existing
For 3, I believe the linting capability of LanguageServer.jl (used in e.g. the julia vs-code extension) should catch this, but don’t quote me on that.