Skip to content Skip to sidebar Skip to footer

Python: Free Variable 'numpy' Referenced Before Assignment In Enclosing Scope

I am adding some code into an existing class for testing purposes. Normally this class, eigensystem_CUDA_implementation, relies on some functions and attributes of its parent. Wh

Solution 1:

Your code will fail if numpy is already imported. You only import it inside the if block, so if it's already imported it won't be defined inside that block. But later in the same function you reference np as a local variable.

Anyway, you don't really need to worry about importing numpy. Just do import numpy as np unconditionally. If it's already imported, it will just re-use the imported version. It won't waste memory or anything importing it twice.

That said, this code looks rather unwieldy and fragile. You should see if there's a better way to do this, by for instance defining a separate function that patches up the class with the necessary attributes. Having a class and an import inside a method inside another class is getting pretty hairy.

Solution 2:

When you put an import within a function, like you're doing in __init__, the variable that the module gets assigned to is local to that function. If you want it to be a global variable, you need to make it one explicitly with a global statement. global np, cuda, SourceModule may do it.

Also, it may not be enough to check for numpy in sys.modules before using np, as numpy could have been imported by a different module, rather than the current one. You could check np in locals(), but it might be easier to simply do the imports unconditionally.

Post a Comment for "Python: Free Variable 'numpy' Referenced Before Assignment In Enclosing Scope"