Python 如何处理多个函数的过滤器?

Python 如何处理多个函数的过滤器?,python,python-3.x,python-2.7,Python,Python 3.x,Python 2.7,在下面的场景中,我的大多数函数都需要根据条件返回不同的内容 def get_root_path(is_cond_met=False): if is_cond_met: return "something" else return "something else" def get_filename(is_cond_met=False): if is_cond_met: return "file name A" els

在下面的场景中,我的大多数函数都需要根据条件返回不同的内容

def get_root_path(is_cond_met=False):
    if is_cond_met:
        return "something"
    else
        return "something else"

def get_filename(is_cond_met=False):
    if is_cond_met:
        return "file name A"
    else
        return "file name B"
is_cond\u met
对于我调用的所有函数都是通用的。我刚刚在这里放了两个,但是我有超过15个

注意:实际函数包含复杂的逻辑,而不仅仅返回几个硬编码字符串。

def get_root_path(is_cond_met=False):
    if is_cond_met:
        ## 
        ## Logic 
        ## 
        return "something"
    else
        #
        # Logic 
        #
        return "something else"

上面的代码可以工作,但是看起来并不是最优的,也不是pythonic的。有更好的解决办法吗

您可以编写一个返回此类函数的函数:

def conditional(a, b, default=False):
    def cond(value=default):
        return a if value else b
    return cond

get_root_path = conditional("something", "something else")
get_filename = conditional("file name A", "file name B")

您可以编写一个函数来返回这样的函数:

def conditional(a, b, default=False):
    def cond(value=default):
        return a if value else b
    return cond

get_root_path = conditional("something", "something else")
get_filename = conditional("file name A", "file name B")

您可以使用以下两个通用函数将过滤器函数有效地链接在一起:

from functools import partial


def check(condition, values):
    return values[int(condition)]

def chain(condition, values):
    return list(map(partial(check, condition), values))


root_paths = "something", "something else"
filenames = "file name A", "file name B"

values = [root_paths, filenames]

is_cond_met = False
result = chain(is_cond_met, values)
print(result)  # -> ['something', 'file name A']

is_cond_met = True
result = chain(is_cond_met, values)
print(result)  # -> ['something else', 'file name B']

您可以使用以下两个通用函数将过滤器函数有效地链接在一起:

from functools import partial


def check(condition, values):
    return values[int(condition)]

def chain(condition, values):
    return list(map(partial(check, condition), values))


root_paths = "something", "something else"
filenames = "file name A", "file name B"

values = [root_paths, filenames]

is_cond_met = False
result = chain(is_cond_met, values)
print(result)  # -> ['something', 'file name A']

is_cond_met = True
result = chain(is_cond_met, values)
print(result)  # -> ['something else', 'file name B']

你能使用:
返回“something”如果它是另一个“something”
?如果它只是一个静态值开始:
配置={'something_cond':{'root_path':'something','filename':'something'},否则:{'root_path':…}
…?!您甚至可能想查看环境变量或其他配置选项。您试图避免/优化的是什么?您可以使用:
返回“something”,如果是其他“something”
?如果它只是以静态值开头:
配置={'some cond':{'root\u path':'something',filename':'something'},否则:{'root_path':…}
…??您甚至可能想要查看环境变量或其他配置选项。您试图避免/优化什么?方法非常好,但是,我的函数很大,只有很少的行或逻辑,最后它们返回一些值。方法非常好,但是,我的函数很大,只有很少的行或逻辑,并且最后,它们返回一些值。