Created
April 4, 2021 02:23
-
-
Save lukeburns/a895d77e5f9b0552acae82f4e6b58918 to your computer and use it in GitHub Desktop.
Nodelike require in Julia (probably you shouldn't do this)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| macro require(mod) | |
| try | |
| Base.require(__module__, Symbol(mod)) # like require("module") | |
| catch e | |
| mod = string(mod) | |
| include(mod) # like require("./module.js") | |
| end | |
| end | |
| macro assign(ex) | |
| if string(ex.head) == "=" | |
| syms = string(ex.args[1]) | |
| for (a, b) in [("{", "("), ("}", ")"), ("(", ""), (")", "")] | |
| syms = replace(syms, a => b) | |
| end | |
| syms = rstrip.(lstrip.(string.(syms))) | |
| syms = filter(!isempty, syms) | |
| object = ex.args[2] | |
| for sym in syms | |
| @eval $(Symbol(sym)) = try | |
| getproperty($object, Symbol($(sym))) # structs, modules | |
| catch e | |
| try | |
| if haskey($object, $sym) | |
| get($object, $sym, nothing) # dicts | |
| end | |
| catch e | |
| # allow for partial assignments, like { a, b } = { a: 0 } | |
| end | |
| end | |
| end | |
| end | |
| end | |
| # matrix.jl | |
| A = [0 -1; 1 0] | |
| # main.jl | |
| A = @require("matrix.jl") | |
| @require("Statistics").det(A) | |
| @assign { tr } = @require(Statistics); tr(A) # equivalent to import Statistics: tr |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wanted to be able to do:
instead of
and without polluting the global namespace.