Home > other >  Define class method based on import success
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:

Thanks for all the hints I received

the solution I'm going to use is:

try:
    import numpy
except ImportError:
    numpy = None

class xxx:

    if numpy:
        def main2():
            ret_array= numpy.array([],dtype=numpy.double)
            return ret_array
    else:
        def main2():
            print ("do nothing")

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

CodePudding user response:

Importing (again) the module inside of 1st version of main2() will work.

class xxx:
    try:
        import numpy
        def main2():
            import numpy
            ret_array= numpy.array([],dtype=numpy.double)
            return ret_array
    except ImportError:
        def main2():
            print ("do nothing")

y = xxx.main2()
print(y)

CodePudding user response:

Use ABC

from abc import ABC, abstractmethod

class ICalculator(ABC):
  @abstractmethod
  def calculate(self) -> int:
    pass

class CalculatorNoNumPy(ICalculator):
    def calculate(self):
      return 7

class CalculatorWithNumPy(ICalculator):
    def calculate(self):
      return 9

try:
  import YouCantFindMe # TODO: replace with numpy
  calculator = CalculatorWithNumPy()
except ImportError:
   calculator = CalculatorNoNumPy()

print(calculator.calculate())
  • Related