Global variables

With the following code
def f1():
x.requires_grad = True

def f2(a,b,…):
x=1
f1()

calling f1() doesn’t seem to recognize x, defined in f2, as a global variable to f1?

Hi,
In your case, when f1 is defined your are trying to access x from global scope when it is not defined in global scope. To access variable from the scope of f2, I would do the following:


def f2(a,b,…):
    x=1
    def f1():
        x.requires_grad = True
    f1()

Here, when defining f1, it access x from the scope of f2. But, of course you can also pass x as parameter to f1 and do the following,

def f1(x):
    x.requires_grad = True  # x should be torch.Tensor

def f2(a,b,…):
    x=1   #  this would not work since x integer and torch.Tensor
    f1(x)

Regarding scoping, I would suggest the following reading: https://www.datacamp.com/tutorial/scope-of-variables-python

1 Like

thanks so much. Then with my original lines I can only add global like the following if I want to put f1 outside of f2?
def f1():
global x
print(x)

def f2(a,b,…):
global x
x=1
f1()

Yes, global keyword puts variable into global scope. Therefore, it would work. But, (as always) be careful with the use of global variables.

Note: I would also suggest to use ``` symbol to show code (rather than plain text), it makes it easier to read for others

1 Like