Python import functions from module twice with different internal imports

前端 未结 3 1555
难免孤独
难免孤独 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:35

    You don't need to do anything to achieve this.

    If you do

    from lib import doSomething
    from lib_with_autograd import doSomething as doSomethingAutograd
    

    each of those functions uses the numpy imported in their specific module. So doSomethingAutograd uses the one imported in lib_with_autograd and doSomething uses the one imported in lib

    0 讨论(0)
  • 2021-01-22 20:56

    Since everything in python is an object, including modules, you can do something like:

    def doSomething(x, numpy=None):
        if numpy is None:
            import numpy
        return numpy.sqrt(x)
    

    Then you can call the function without setting numpy, then it will use the default numpy. If you want to use another numpy, just call it as such:

    from autograd import numpy as autograd_numpy
    doSomething(x, numpy=autograd_numpy)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题