我有一些函数,这些函数的实现细节取决于传递给它们的对象的类型(具体来说,是选择链接Django模型以生成QuerySet的正确方法)。以下两个选项中的哪一个是更Pythonic的实现方式?
如果是梯子
def do_something(thing: SuperClass) -> "QuerySet[SomethingElse]":
if isinstance(thing,SubClassA):
return thing.property_set.all()
if isinstance(thing,SubClassB):
return thing.method()
if isinstance(thing,SubClassC):
return a_function(thing)
if isinstance(thing,SubClassD):
return SomethingElse.objects.filter(some_property__in=thing.another_property_set.all())
return SomethingElse.objects.none()
字典
def do_something(thing: SuperClass) -> "QuerySet[SomethingElse]":
return {
SubClassA: thing.property_set.all(),SubClassB: thing.method(),SubClassC: a_function(thing),SubClassD: SomethingElse.objects.filter(some_property__in=thing.another_property_set.all()),}.get(type(thing),SomethingElse.objects.none())
Dictionary选项的重复代码更少,行数更少,但是if梯子使PyCharm和MyPy更加快乐(尤其是使用类型检查)。
我假设两者之间的任何性能差异都可以忽略不计,除非它位于经常调用的例程的内部循环中(如>> 1请求/秒)。