Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

233
Views
Define class method based on import success

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)

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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")
over 4 years ago · Santiago Trujillo Report

0

You could try:

class Test:
    def test(self):        
        try:
            import numpy
            import_succeeded = True
        except:
            import_succeeded = False
        
        if import_succeeded:
            pass
        else:
            pass
over 4 years ago · Santiago Trujillo Report

0

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")
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!