【发布时间】:2020-12-22 23:04:28
【问题描述】:
我正在编写一个包含许多函数的 python 包,我在其中设置了本地导入以避免缺少包错误(这样即使我没有安装某个包,我的其他函数仍然可以工作)。
但是,我已经编写了一个装饰器来包装我的一些函数,但是如果装饰器中的参数需要某个包,我就无法进行本地导入。当我需要在函数参数的注解中从另一个包中导入某种类型时,会出现类似的本地导入问题。
def do_fancy_stuff(arg):
def wrapped_func(func):
def inner_func():
print(f"Using {arg} on the target function!")
# Some other statements to define the inner function, for simplicity here I just run func()
func()
return inner_func
return wrapped_func
@do_fancy_stuff("A")
def some_func1():
import numpy
pass
@do_fancy_stuff("B")
def some_func2():
pass
# How can I avoid an import statement here and put it in the decorator?
# import numpy
@do_fancy_stuff(numpy.inf) # error here
def some_func3():
pass
# Similarly I need to import numpy outside the function if I want to do the annotation...
# import numpy
def other_func1(input_array : numpy.ndarray): # Error
pass
我有一个想法,对函数外的所有导入使用 try-except。但这会破坏我最初的想法,即函数的所有依赖项都应该在该函数中本地定义。
另一个想法是使用exec 或者写一个小函数来包装它,但它似乎使代码的可读性大大降低:
def _get_numpy_inf():
import numpy
return numpy.inf
有没有更好的方法直接在装饰器语句和注释中进行本地导入,比如?
@do_fancy_stuff(import numpy; numpy.inf)
(import numpy; @do_fancy_stuff(numpy.inf) )
def other_func1(input_array : import numpy; numpy.ndarray):
# Just some imaginations, it doesn't work
【问题讨论】: