0

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)?

2
  • 9
    Why are you assigning numpy = None? This makes Python think numpy is a local variable. Commented Sep 2, 2020 at 10:23
  • If your function contains an assignment to a variable, then by default the variable is local to the function. Commented Sep 2, 2020 at 10:26

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

7 Comments

@Asocia, Done. What does OP stand for?
The code is meaningless, just for reproducing the issue I met. But I am confused why the variable is local before excuating numpy = None
The codes are excuated line by line, so why numpy = None will influence the previous ussage of numpy? What did python interpreter do to the class before initializing it?
thx for your answer, it works. It seems like a rule of python, so why don't python convert numpy to local variable until assignment executed?
almost all the variables can be covered while assigning, why global variable cannot be covered by local variable? It is a technical limit or a thoughtful design?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.