I have some interface class, if numpy is available I would provide some extra method for the class (faster implementation)
It is possible to define some function based on the success of an import, but the same code does not work for class methods.
This code
try:
import numpy
def main2():
ret_array= numpy.array([],dtype=numpy.double)
return ret_array
except ImportError:
def main2():
print ("do nothing")
successfully defines a main2()
which returns an empty numpy array
But this code
class xxx:
try:
import numpy
def main2():
ret_array= numpy.array([],dtype=numpy.double)
return ret_array
except ImportError:
def main2():
print ("do nothing")
results in an exception
if I try to call main2()
xxx.main2()
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "test2.py", line 17, in main2
ret_array= numpy.array([],dtype=numpy.double)
NameError: name 'numpy' is not defined
Is there some other way to achieve this? (based on the availability of a module define a class method differently)