# Reading and writing a global variable

**URL:** https://discourse.julialang.org/t/reading-and-writing-a-global-variable/121996
**Category:** New to Julia
**Created:** [October 30, 2024, 2:45pm UTC](https://discourse.julialang.org/t/reading-and-writing-a-global-variable/121996 "2024-10-30T14:45:23Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![Matthijs\_1971](https://avatars.discourse-cdn.com/v4/letter/m/bb73d2/32.png) [@Matthijs\_1971](https://discourse.julialang.org/u/Matthijs_1971)
#### Post date: [October 30, 2024, 2:45pm UTC](https://discourse.julialang.org/t/reading-and-writing-a-global-variable/121996/1 "2024-10-30T14:45:23Z")

</div>

Please consider the following code:

```julia
module MyModule
    global MY_GLOBAL = 42
    
    function test()::Nothing
        println("MY_GLOBAL ", MY_GLOBAL)
        
        # MY_GLOBAL = 3
        return nothing
    end
end # MyModule

MyModule.test()

```

As is, this code just runs and `MY_GLOBAL` is in scope for reading. Now if the line `MY_GLOBAL = 3` is commented back in, the script fails on the line with the `println` call - which it could execute before. The error is _ERROR: LoadError: UndefVarError: `MY_GLOBAL` not defined_. Of course, adding `global MY_GLOBAL` in the function makes the code run, but that is not the point. IMHO, a variable is in scope in a function or not and that should not depend on read or write attempts. What is going on?

---

<div class="post-metadata">

### Author: ![pdeffebach](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pdeffebach/32/10320_2.png) [@pdeffebach](https://discourse.julialang.org/u/pdeffebach)
#### Post date: [October 30, 2024, 3:03pm UTC](https://discourse.julialang.org/t/reading-and-writing-a-global-variable/121996/2 "2024-10-30T15:03:33Z")

</div>

Inside a function scope, Julia first looks for all new assignments.

If an there is an assignment which shares the same name as a global variable, it treats _all_ references to that variable as local, even ones that happen before the assignment.

This creates somewhat confusing errors, for sure.

---

<div class="post-metadata">

### Author: ![bertschi](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bertschi/32/33462_2.png) [@bertschi](https://discourse.julialang.org/u/bertschi)
#### Post date: [October 30, 2024, 4:50pm UTC](https://discourse.julialang.org/t/reading-and-writing-a-global-variable/121996/3 "2024-10-30T16:50:24Z")

</div>

Just for the record, Python works exactly the same in this case:

```python
my_global = 42

def fun():
     print(my_global)
     # Fails if line below is uncommented
     # my_global = 3

fun()

```
