0

As a JavaScript developer Python scoping doesn't make sense at all. Just came across this example. Just to give a peek:

def policy_backward(eph, epdlogp):
  """ backward pass. (eph is array of intermediate hidden states) """
  dW2 = np.dot(eph.T, epdlogp).ravel()
  dh = np.outer(epdlogp, model['W2'])
  dh[eph <= 0] = 0 # backpro prelu
  dW1 = np.dot(dh.T, epx)
  return {'W1':dW1, 'W2':dW2}

The question is: how this function will have access to epx? It is not a global variable (but as I know, you couldn't anyways without defining it global inside the function body), it is not initialized inside the function, and it is not defined inside it's parameters. So how will it get access to it?

Was trying to somehow reproduce the logic:

def a():
    x = x or 3
    x += 1
    
def b():
    x = 3
    a()
    print(x)
b()

But getting x referenced before assigned no matter what I do.

Gergő Horváth
  • 3,195
  • 4
  • 28
  • 64
  • 1
    I have no idea what this code is doing - the variable naming in particular is horrible and gives no help as to the intention. But having clicked on the link and searched the wider code, `epx` *is* global (in that particular module, anyway). It's defined/initialised inside the `while` loop a bit further down, and therefore in global scope. One of Python's peculiarities coming from languages like Javascript is that there is no explicit declaration of variables (it's something I dislike, although otherwise I do like Python as a language). – Robin Zigmond Nov 13 '20 at 20:27
  • Also https://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python – buran Nov 13 '20 at 20:30
  • 2
    In Python you can **read** from a global variable without the `global` keyword -- only **assigning** to it requires the keyword. `epx` is indeed a global variable there, but the reference to it is only resolved when the function runs, i.e. `epx` can be defined after the function is defined. – xjcl Nov 13 '20 at 21:10

0 Answers0