Python import functions from module twice with different internal imports

前端 未结 3 1553
难免孤独
难免孤独 2021-01-22 20:13

I have a module lib that needs numpy. So, for instance, let\'s say I have a hypothetical function that looks like

import numpy
def doS         


        
3条回答
  •  后悔当初
    2021-01-22 20:57

    If your desire is to avoid duplicating your code base, make your interface a class instead. For example:

    class using_numpy:
        import numpy
    
        @classmethod
        def do_something(cls, x):
            return cls.numpy.sqrt(x)
    
    class using_autograd(using_numpy):
        from autograd import numpy
    

    Now using_numpy.do_something will use numpy, and using_autograd.do_something will use autograd.numpy.

    Alternatively, if you are uncomfortable with classmethod, you could make your interfaces instances of a class, for example:

    class interface:
        def __init__(self, mdl):
            self.mdl = mdl
    
        def do_something(self, x):
            return self.mdl.sqrt(x)
    
    import numpy
    import autograd
    
    with_numpy = interface(numpy)
    with_autograd = interface(autograd.numpy)
    

提交回复
热议问题