Home > front end >  Python Define class method based on import success
Python Define class method based on import success

Time:12-06

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)

CodePudding user response:

You could try:

class Test:
    def test(self):        
        try:
            import numpy
            import_succeeded = True
        except:
            import_succeeded = False
        
        if import_succeeded:
            pass
        else:
            pass

CodePudding user response:

try:
    import numpy

    class xxx:
        def main2(self):
            ret_array = numpy.array([],dtype=numpy.double)
            print(ret_array)
except:
    class xxx:
        def main2(self):
            print("do nothing")
  • Related