How to intercept creation or setting of variable in current module?

Need help, how to intercept operation on create new variable on current module in Julia 1.8?

For example, to intercept MyModule.x = 1 in Julia 1.8 i do this:

julia> module MyModule end;

julia> function Base.setproperty!(m::Module, p::Symbol, v)
           println("variable $p changed on $v in module $m")
           @eval m $p = $v  # waiting for julia 1.9 and will use setglobal!()

julia> MyModule.x = 1;
variable x changed on 1 in module Main.MyModule

How to intercept x = 1 in Main?

julia> Main.x = 1;
variable x changed on 1 in module Main

julia> x = 1;  # must print like Main.x = 1

Any ideas?

So you want to circumvent the restriction / error “cannot assign variables in other modules”?

Could you explain what you are trying to accomplish with this?

MyModule.x would be a global; so it should presumably be a const.

If you want specific variables to be assignable from the outside of MyModule, you could just write a function (in MyModule) to assign those values.
Do you really want to permit creation of arbitrary globals (with possible side effects)?

I must create a trigger on change or add the variable in the current module.

When a variable is created or modified in the current module, my function must be called.

This must happen regardless of how the module variable is created or modified. When julia> x=1 in Main too.

It would help to get a bigger picture idea of what you are trying to accomplish.

If you just need to run a function when a variable in MyModule is modified, can’t you ensure that the variable is modified by calling a function (MyModule.change_x())? Then change_x() can call the function you need to be called.

I can’t.

Variables in Main or any other module are created in a independent way.

I only must to call foo() when a module variable is created or modified.

If the variable was created in Main from the REPL like this:

julia> x = 1;

i must call foo() too.

Sorry - I don’t know how to accomplish this.

For curiosity - the pattern you are aiming for seems very unusual. Why do you need to create variables in a module from the REPL?

Perhaps the question to ask is: is this the right design choice?

I am trying to visualise the workspace without refresh all module variables by Base.names().