Humble_me
Humble_me

Reputation: 37

Numpy Referenced before assignment error in python

here is my python code:

import numpy
class test:
  def __init__(self,):
    print(numpy.__version__)
    if False:
      numpy = None

if __name__=='__main__':
  print(numpy.__version__)
  T = test()

when I run this code, the interpreter give me an error showed blow:

UnboundLocalError: local variable 'numpy' referenced before assignment

It seems like, before executing numpy = None, imported module "numpy" has been covered while there is no numpy variable.

My question is what exactly the interpreter did during initializing a class(not object)?

Upvotes: 0

Views: 103

Answers (1)

Safwan Samsudeen
Safwan Samsudeen

Reputation: 1707

EDIT: As a reply to your comment, Python goes through each line of code before executing it, and sees that the syntax is correct and other things. To test it, run the following code.

def foo():
    print("Hello, I won't be printed.")
    : # Syntax Error!!!
foo()

It will raise a SyntaxError without printing anything even though the SyntaxError is after the print statement, because it checks the code and then only runs it.

Inside a function, it also thinks that all the variables which are found to be assigned while checking are supposed to be local. If you don't want this, then you must explicitly say so using the global or nonlocal keywords.

class test:
  def __init__(self,):
    global numpy
    print(numpy.__version__)
    if False:
      numpy = None

Upvotes: 1

Related Questions