Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

235
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda