Python import functions from module twice with different internal imports

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

提交回复
热议问题