【问题标题】:Python switch-case unexpectedly executing all casesPython switch-case 意外执行所有案例
【发布时间】:2021-11-30 09:53:30
【问题描述】:

原帖(编辑/更新如下:)

我正在尝试在 Python 中创建一个 switch-case 函数以避免非常长的 if:elseif:elseif:elseif...else 语句(运行 3.7,所以没有 3.10 的 match-case 语句)。所以,我正在玩弄这个字典查找(为了这个例子的目的,故意保持简短)。

我已经在程序的其他地方定义了一个类似的函数,它按预期工作。但是,新的 switch-case 函数应该调用其他函数来响应提供的输入(我的其他查找只是返回一个值)。奇怪的是,它执行每个案例,而不仅仅是所需的案例。而且,我不明白为什么。

# switcher.py
# optional cli args: ipaddress, port

def config_updater(k, v):
    print(f'config_update(k,v): {k, v}')  # Sanity check
    switcher = {
        'ipaddress': update_ip(v),
        'port': update_port(v)
    }

    return switcher.get(k)


def update_ip(a):
    global host_ip
    host_ip = a
    print(f'update_ip: host_ip updated to {a}')


def update_port(b):
    global host_port
    host_port = b
    print(f'update_port: host_port updated to {b}')

#
# Code for command line argparse functionality goes here
# Essentially, arguments (ipaddress, port) can be optionally added at command line
#

args = parser.parse_args()
dargs = vars(args)  # Creates a dictionary of command line arguments and their values

# Setting default values if no arguments added at command line
global host_ip, host_port
host_ip = 'localhost'
host_port = 4840
i = 1  # For loop counter

for field, value in dargs.items():
    print(f'\n\nFor loop iteration: {i}\n')  # Sanity check
    i += 1
    print(f'Printing current field-value pair: {field}, {value}\n')  # Sanity check
    if value is not None:
        config_updater(field, value)

print(f'\n\nPrinting final statement:')
print(f'IP address: {host_ip}')
print(f'Port: {host_port}')

现在,当它像这样运行时:

$ python3 switcher.py -ip 192.168.0.28 -p 2228

我得到以下输出,它为两个参数运行 update_ip 和 update_port 而不仅仅是它们各自的查找。

For loop iteration: 1

Printing current field-value pair: ipaddress, 192.168.0.28

config_update(k,v): ('ipaddress', '192.168.0.28')
update_ip: host_ip updated to 192.168.0.28
update_port: host_port updated to 192.168.0.28


For loop iteration: 2

Printing current field-value pair: port, 2228

config_update(k,v): ('port', '2228')
update_ip: host_ip updated to 2228
update_port: host_port updated to 2228


Printing final statement:
IP address: 2228
Port: 2228

为了澄清,我期望输出是:

For loop iteration: 1

Printing current field-value pair: ipaddress, 192.168.0.28

config_update(k,v): ('ipaddress', '192.168.0.28')
update_ip: host_ip updated to 192.168.0.28


For loop iteration: 2

Printing current field-value pair: port, 2228

config_update(k,v): ('port', '2228')
update_port: host_port updated to 2228


Printing final statement:
IP address: 192.168.0.28
Port: 2228

我是否从根本上误解了如何使用这些查找来调用其他函数?

编辑(基于标记的答案和 cmets):

我修改后的代码继续使用字典查找 - 与原始问题内联 - 但已调整为使用已经可用的全局 argsparser 变量,现在看起来像这样:

# switcher.py
# optional cli args: ipaddress, port

def get_default_config(field):
    switcher = {
        'ipaddress': set_default_ip,
        'port': set_default_port
    }
    func_to_use = switcher.get(field)
    if func_to_use:
        return func_to_use()


def set_default_ip():
    args.ipaddress = 'localhost'
    print(f'update_ip: host_ip updated to {args.ipaddress}')


def set_default_port():
    args.port = 4840
    print(f'update_port: host_port updated to {args.port}')

#
# Code for command line argparse functionality goes here
# Essentially, arguments (ipaddress, port) can be optionally added at command line
#

args = parser.parse_args()
dargs = vars(args)

for field, value in dargs.items():
    if value is None:
        get_default_config(field)

print('\n\n')
print(f'IP address set to: {args.ipaddress}')
print(f'Port set to: {args.port}')

感谢所有做出贡献的人!

【问题讨论】:

  • update_ip(v) 在字典创建过程中直接调用“update_ip”。仅将函数对象 update_ip 用作 dict 值并返回 switcher.get(k)(v)。港口也一样。
  • 整个事情看起来严重过度设计。您已经有 IP 地址和端口的全局可访问表达式:args.ipaddress 和 args.port。
  • @MichaelButscher 确实可以解决问题。我也理解其中的区别。谢谢。
  • @chepner 我同意这可能有点过头了。特别是在这个非常简短的例子中。检查 args.ipaddress 和 args.port 值是否未设置为 None 的几个 if 语句将执行相同的工作并且可能更具可读性。但是,老实说,我一直不喜欢更长的 if:elif 语句,发现它们笨拙,我想这是一个简短的例子,只是作为概念证明。诚然,无论如何,3.10 都有 match-case 内置功能,我无法想象我会经常使用它。
  • 谁说过if 声明?我是说当您可以直接使用args.ipaddress 和args.port 时,您不需要新的全局变量(以及设置它们的所有机器)。需要知道全局名称 args 与必须知道全局名称 ipaddress 和 port 的函数之间几乎没有区别。

标签: python switch-statement python-3.7


【解决方案1】:

当你这样定义字典时

switcher = {
        'ipaddress': update_ip(v),
        'port': update_port(v)
    }

您调用函数,这些函数的返回值被分配给字典的那个键。

相反,您希望将函数本身分配为字典中的值,然后在您知道需要哪一个时调用它们。

switcher = {
        'ipaddress': update_ip,
        'port': update_port
    }
func_to_use = switcher.get(k)
if func_to_use:
    return func_to_use(v)

【讨论】:

  • 谢谢!我理解这里的问题(即构建字典并同时调用函数,因为我已经传递了参数)。这成功了。
猜你喜欢
  • 2014-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-05
  • 2020-03-15
  • 2015-07-27
  • 2015-07-16
  • 2014-11-09
相关资源
最近更新 更多